mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
Merge pull request #281 from MacosPorters/archive/pull/401/head
loader: add standard output and printf formatting for a hosted C program (#400)
This commit is contained in:
11 files changed
+4645
-9
No files matched your search
@@ -147,6 +147,8 @@ remains unsupported.
|
||||
|
||||
- Added bounded guest CRT long-integer parsing for byte and wide strings.
|
||||
|
||||
- Added standard output for a hosted C program (#400, part of Gate A2): a `printf` formatting engine, the standard streams, and capture of what the guest writes to `stdout` and `stderr`. The services are `__acrt_iob_func`, `__stdio_common_vfprintf` (what `printf` and `fprintf` call in a program built with the mingw-w64 runtime), `fwrite`, `fputs`, `fflush` and `setvbuf`; a host reads the output through `ServicesState::standard_output` and `standard_error`. The engine handles the flags, width, precision and size prefixes of `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%` as Microsoft's format specification page and ISO C describe, reading arguments from the guest's `va_list`. The standard streams are text-mode streams, so a line feed is captured as carriage return and line feed. Floating-point and wide conversions, a locale object, other streams and files are not modelled and stop the guest with the runtime-limit fault instead of printing something wrong; `%n` and unknown conversions return -1 with `EINVAL`. All six services are `partial`. The engine's output matches the host C library's `snprintf` on 2,600 generated cases whose result ISO C defines (`crates/loader/tests/printf/reference.py`), with hand-written cases for the Windows-specific rules, and seven tests in `runtime_services.rs` call the services from guest code. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
|
||||
|
||||
- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review.
|
||||
|
||||
@@ -116,6 +116,58 @@ service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
|
||||
ref sysinfoapi.h GetSystemTimeAsFileTime
|
||||
test system_time_comes_from_the_injected_clock
|
||||
|
||||
# Standard streams and formatted output for a hosted C program. Output to
|
||||
# stdout and stderr is captured; any other stream, input, floating-point and
|
||||
# wide conversions stop the guest with the runtime-limit fault.
|
||||
|
||||
service ucrtbase.dll __acrt_iob_func(index: u32) -> ptr
|
||||
handler standard_stream
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for an index above 2 or when the streams cannot be allocated
|
||||
ref corecrt_wstdio.h __acrt_iob_func
|
||||
test standard_streams_are_three_stable_file_objects
|
||||
|
||||
service ucrtbase.dll __stdio_common_vfprintf(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32
|
||||
handler vfprintf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled
|
||||
ref corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax
|
||||
test formatted_output_reaches_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fwrite(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64
|
||||
handler fwrite
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr
|
||||
ref stdio.h fwrite
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fputs(text: ptr, stream: ptr) -> i32
|
||||
handler fputs
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr
|
||||
ref stdio.h fputs
|
||||
test fwrite_and_fputs_write_to_the_captured_standard_streams
|
||||
|
||||
service ucrtbase.dll fflush(stream: ptr) -> i32
|
||||
handler fflush
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails stops the guest for a stream that is not a standard stream
|
||||
ref stdio.h fflush
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
service ucrtbase.dll setvbuf(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32
|
||||
handler setvbuf
|
||||
status partial
|
||||
alias api-ms-win-crt-stdio-l1-1-0.dll
|
||||
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream
|
||||
ref stdio.h setvbuf
|
||||
test fflush_and_setvbuf_return_their_documented_results
|
||||
|
||||
service kernel32.dll GetLastError() -> u32
|
||||
handler get_last_error
|
||||
status partial
|
||||
|
||||
@@ -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; 37] = [
|
||||
pub static SERVICES: [ServiceMetadata; 43] = [
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetProcessPriorityBoost",
|
||||
@@ -141,6 +141,72 @@ pub static SERVICES: [ServiceMetadata; 37] = [
|
||||
reference: "sysinfoapi.h GetSystemTimeAsFileTime",
|
||||
tests: &["system_time_comes_from_the_injected_clock"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__acrt_iob_func",
|
||||
parameters: &[Parameter { name: "index", kind: "u32" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest for an index above 2 or when the streams cannot be allocated",
|
||||
reference: "corecrt_wstdio.h __acrt_iob_func",
|
||||
tests: &["standard_streams_are_three_stable_file_objects"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "__stdio_common_vfprintf",
|
||||
parameters: &[Parameter { name: "options", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }, Parameter { name: "format", kind: "ptr" }, Parameter { name: "locale", kind: "ptr" }, Parameter { name: "arguments", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled",
|
||||
reference: "corecrt_stdio_config.h __stdio_common_vfprintf; Microsoft Learn, vfprintf and format specification syntax",
|
||||
tests: &["formatted_output_reaches_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fwrite",
|
||||
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "count", kind: "u64" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "u64",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr",
|
||||
reference: "stdio.h fwrite",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fputs",
|
||||
parameters: &[Parameter { name: "text", kind: "ptr" }, Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr",
|
||||
reference: "stdio.h fputs",
|
||||
tests: &["fwrite_and_fputs_write_to_the_captured_standard_streams"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fflush",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "stops the guest for a stream that is not a standard stream",
|
||||
reference: "stdio.h fflush",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "setvbuf",
|
||||
parameters: &[Parameter { name: "stream", kind: "ptr" }, Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "mode", kind: "i32" }, Parameter { name: "size", kind: "u64" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
|
||||
failure: "-1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream",
|
||||
reference: "stdio.h setvbuf",
|
||||
tests: &["fflush_and_setvbuf_return_their_documented_results"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetLastError",
|
||||
@@ -518,6 +584,65 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__acrt_iob_func", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::standard_stream(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "__stdio_common_vfprintf", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let a4 = call.u64(4)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::vfprintf(&mut context, a0, a1, a2, a3, a4)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fwrite", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u64(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::fwrite(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fputs", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fputs(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "fflush", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::fflush(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("ucrtbase.dll", "setvbuf", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.i32(2)?;
|
||||
let a3 = call.u64(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::setvbuf(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
mod crt;
|
||||
mod crt_arguments;
|
||||
mod crt_callbacks;
|
||||
mod crt_format;
|
||||
mod crt_startup;
|
||||
mod crt_streams;
|
||||
mod events;
|
||||
mod files;
|
||||
mod gdk_queue;
|
||||
@@ -28,6 +30,7 @@ mod winsock;
|
||||
|
||||
use crate::runtime::HResult;
|
||||
pub use crt_arguments::{MAX_PROGRAM_ARGUMENT_BYTES, ProgramArgumentsError};
|
||||
pub use crt_streams::MAX_CAPTURED_OUTPUT;
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
@@ -205,6 +208,7 @@ pub struct ServicesState {
|
||||
last_errors: Mutex<BTreeMap<u64, u32>>,
|
||||
crt_arguments: Mutex<crt_arguments::CrtArguments>,
|
||||
synch: Mutex<synch::Synch>,
|
||||
crt_streams: Mutex<crt_streams::StandardStreams>,
|
||||
pub(crate) threads: Mutex<threads::ThreadTable>,
|
||||
pub(crate) hooks: Arc<threads::SchedulerHooks>,
|
||||
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
|
||||
@@ -235,6 +239,7 @@ impl ServicesState {
|
||||
last_errors: Mutex::default(),
|
||||
crt_arguments: Mutex::default(),
|
||||
synch: Mutex::default(),
|
||||
crt_streams: Mutex::default(),
|
||||
threads: Mutex::default(),
|
||||
hooks: Arc::default(),
|
||||
atexit: Mutex::default(),
|
||||
@@ -348,6 +353,23 @@ impl ServicesState {
|
||||
status
|
||||
}
|
||||
|
||||
/// Everything the guest has written to `stdout`, as the bytes a text-mode
|
||||
/// stream hands the operating system: each line feed the program wrote is
|
||||
/// a carriage return and a line feed here.
|
||||
pub fn standard_output(&self) -> Vec<u8> {
|
||||
self.crt_streams().output().to_vec()
|
||||
}
|
||||
|
||||
/// Everything the guest has written to `stderr`, in the same form as
|
||||
/// [`Self::standard_output`].
|
||||
pub fn standard_error(&self) -> Vec<u8> {
|
||||
self.crt_streams().error().to_vec()
|
||||
}
|
||||
|
||||
fn crt_streams(&self) -> std::sync::MutexGuard<'_, crt_streams::StandardStreams> {
|
||||
self.crt_streams.lock().expect("standard streams")
|
||||
}
|
||||
|
||||
/// Read the last-error value for a guest thread's TEB.
|
||||
pub fn last_error(&self, teb: u64) -> u32 {
|
||||
self.last_errors
|
||||
@@ -915,6 +937,83 @@ pub(crate) mod handlers {
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
// Standard streams and formatted output (#400). `crt_streams.rs` holds
|
||||
// the rules; a documented failure sets errno to EINVAL here.
|
||||
|
||||
fn or_einval<T>(
|
||||
context: &mut ServiceContext<'_>,
|
||||
outcome: crt_streams::Outcome<T>,
|
||||
) -> Outcome<T> {
|
||||
match outcome? {
|
||||
Ok(value) => Ok(value),
|
||||
Err(crt_streams::Invalid(value)) => {
|
||||
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn standard_stream(context: &mut ServiceContext<'_>, index: u32) -> Outcome<u64> {
|
||||
context.state.crt_streams().file(context.memory, index)
|
||||
}
|
||||
|
||||
pub fn vfprintf(
|
||||
context: &mut ServiceContext<'_>,
|
||||
options: u64,
|
||||
stream: u64,
|
||||
format: u64,
|
||||
locale: u64,
|
||||
arguments: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().print(
|
||||
context.memory,
|
||||
options,
|
||||
stream,
|
||||
format,
|
||||
locale,
|
||||
arguments,
|
||||
);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fwrite(
|
||||
context: &mut ServiceContext<'_>,
|
||||
buffer: u64,
|
||||
size: u64,
|
||||
count: u64,
|
||||
stream: u64,
|
||||
) -> Outcome<u64> {
|
||||
let outcome =
|
||||
context
|
||||
.state
|
||||
.crt_streams()
|
||||
.write_items(context.memory, buffer, size, count, stream);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fputs(context: &mut ServiceContext<'_>, text: u64, stream: u64) -> Outcome<i32> {
|
||||
let outcome = context
|
||||
.state
|
||||
.crt_streams()
|
||||
.put_string(context.memory, text, stream);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn fflush(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
|
||||
context.state.crt_streams().flush(stream)
|
||||
}
|
||||
|
||||
pub fn setvbuf(
|
||||
context: &mut ServiceContext<'_>,
|
||||
stream: u64,
|
||||
_buffer: u64,
|
||||
mode: i32,
|
||||
size: u64,
|
||||
) -> Outcome<i32> {
|
||||
let outcome = context.state.crt_streams().set_buffer(stream, mode, size);
|
||||
or_einval(context, outcome)
|
||||
}
|
||||
|
||||
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.last_error(context.teb))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,743 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Formatting for the narrow `printf` family.
|
||||
//!
|
||||
//! The rules are from Microsoft's "Format specification syntax: printf and
|
||||
//! wprintf functions" and, where that page is silent, from ISO C 7.21.6.1. A
|
||||
//! conversion specification is `%[flags][width][.precision][size]type`.
|
||||
//!
|
||||
//! Supported: the flags `-`, `+`, space, `#` and `0`; a width and a precision
|
||||
//! given as digits or as `*`; the size prefixes `hh`, `h`, `l`, `ll`, `j`,
|
||||
//! `z`, `t`, `I`, `I32` and `I64`; and the types `d`, `i`, `u`, `o`, `x`, `X`,
|
||||
//! `c`, `s`, `p` and `%%`.
|
||||
//!
|
||||
//! Refused as invalid, as Windows does by default: `%n`, and a character that
|
||||
//! has no meaning as a type. Refused as not modelled, so that nothing is
|
||||
//! printed wrongly: the floating-point types, and wide characters and strings.
|
||||
//!
|
||||
//! Where the documentation leaves a choice, the choice made here is marked
|
||||
//! "Xenora's choice" at the code that makes it.
|
||||
|
||||
use crate::memory::MemoryError;
|
||||
|
||||
/// The most one call may produce, and the largest width or precision.
|
||||
pub(super) const MAX_OUTPUT: usize = 1 << 20;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum FormatError {
|
||||
/// The format is not valid: `%n`, an unknown type, a size prefix that
|
||||
/// does not apply to its type, or a string that ends inside a
|
||||
/// specification.
|
||||
Invalid,
|
||||
/// The format is valid and asks for something that is not modelled.
|
||||
Unsupported,
|
||||
/// The output, a width or a precision exceeds [`MAX_OUTPUT`].
|
||||
TooLong,
|
||||
/// Reading an argument or a string failed.
|
||||
Fault(MemoryError),
|
||||
}
|
||||
|
||||
/// Where the arguments and strings of one call come from.
|
||||
pub(super) trait Source {
|
||||
/// The next 8-byte argument slot.
|
||||
fn argument(&mut self) -> Result<u64, MemoryError>;
|
||||
/// The bytes of the string at `address` up to its terminator, or the first
|
||||
/// `limit` of them. Never called with a null address.
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Size {
|
||||
None,
|
||||
Char,
|
||||
Short,
|
||||
/// `l`: a `long`, which is 32 bits on Windows, or a wide character or
|
||||
/// string.
|
||||
Long,
|
||||
/// `ll`, `j`, `z`, `t`, `I` and `I64`: 64 bits on a 64-bit system.
|
||||
Quad,
|
||||
/// `I32`.
|
||||
Int32,
|
||||
/// `w`: a wide character or string.
|
||||
Wide,
|
||||
/// `L`: a `long double`.
|
||||
LongDouble,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Flags {
|
||||
left: bool,
|
||||
plus: bool,
|
||||
space: bool,
|
||||
alternate: bool,
|
||||
zero: bool,
|
||||
}
|
||||
|
||||
struct Spec {
|
||||
flags: Flags,
|
||||
width: usize,
|
||||
precision: Option<usize>,
|
||||
size: Size,
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
format: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.format.get(self.at).copied()
|
||||
}
|
||||
|
||||
fn take(&mut self, byte: u8) -> bool {
|
||||
let found = self.peek() == Some(byte);
|
||||
self.at += usize::from(found);
|
||||
found
|
||||
}
|
||||
|
||||
/// Decimal digits, possibly none.
|
||||
fn number(&mut self) -> Result<usize, FormatError> {
|
||||
let mut value = 0usize;
|
||||
while let Some(digit @ b'0'..=b'9') = self.peek() {
|
||||
value = value * 10 + usize::from(digit - b'0');
|
||||
if value > MAX_OUTPUT {
|
||||
return Err(FormatError::TooLong);
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn size(&mut self) -> Size {
|
||||
if self.take(b'h') {
|
||||
return if self.take(b'h') {
|
||||
Size::Char
|
||||
} else {
|
||||
Size::Short
|
||||
};
|
||||
}
|
||||
if self.take(b'l') {
|
||||
return if self.take(b'l') {
|
||||
Size::Quad
|
||||
} else {
|
||||
Size::Long
|
||||
};
|
||||
}
|
||||
if self.take(b'I') {
|
||||
let rest = &self.format[self.at..];
|
||||
if rest.starts_with(b"64") {
|
||||
self.at += 2;
|
||||
return Size::Quad;
|
||||
}
|
||||
if rest.starts_with(b"32") {
|
||||
self.at += 2;
|
||||
return Size::Int32;
|
||||
}
|
||||
// `I` alone is ptrdiff_t or size_t.
|
||||
return Size::Quad;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'j' | b'z' | b't') => {
|
||||
self.at += 1;
|
||||
Size::Quad
|
||||
}
|
||||
Some(b'w') => {
|
||||
self.at += 1;
|
||||
Size::Wide
|
||||
}
|
||||
Some(b'L') => {
|
||||
self.at += 1;
|
||||
Size::LongDouble
|
||||
}
|
||||
_ => Size::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An `int` argument is the low half of its slot.
|
||||
fn int(slot: u64) -> i32 {
|
||||
slot as u32 as i32
|
||||
}
|
||||
|
||||
fn bounded(value: usize) -> Result<usize, FormatError> {
|
||||
if value > MAX_OUTPUT {
|
||||
Err(FormatError::TooLong)
|
||||
} else {
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pad `body` to the field width. `zeros` puts the padding after the first
|
||||
/// `lead` bytes (a sign or prefix) as zeros instead of before them as blanks.
|
||||
fn pad(out: &mut Vec<u8>, spec: &Spec, lead: usize, body: &[u8], zeros: bool) {
|
||||
let fill = spec.width.saturating_sub(body.len());
|
||||
if spec.flags.left {
|
||||
out.extend_from_slice(body);
|
||||
out.resize(out.len() + fill, b' ');
|
||||
} else if zeros {
|
||||
out.extend_from_slice(&body[..lead]);
|
||||
out.resize(out.len() + fill, b'0');
|
||||
out.extend_from_slice(&body[lead..]);
|
||||
} else {
|
||||
out.resize(out.len() + fill, b' ');
|
||||
out.extend_from_slice(body);
|
||||
}
|
||||
}
|
||||
|
||||
fn digits(mut value: u64, base: u64, upper: bool) -> Vec<u8> {
|
||||
let table: &[u8; 16] = if upper {
|
||||
b"0123456789ABCDEF"
|
||||
} else {
|
||||
b"0123456789abcdef"
|
||||
};
|
||||
let mut reversed = Vec::new();
|
||||
loop {
|
||||
reversed.push(table[(value % base) as usize]);
|
||||
value /= base;
|
||||
if value == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
reversed.reverse();
|
||||
reversed
|
||||
}
|
||||
|
||||
fn integer(out: &mut Vec<u8>, spec: &Spec, kind: u8, slot: u64) -> Result<(), FormatError> {
|
||||
let signed = matches!(kind, b'd' | b'i');
|
||||
// Without a size prefix an integer argument is a 32-bit int, and so is a
|
||||
// long. `hh` and `h` arguments arrive as an int and are converted back.
|
||||
let (negative, magnitude) = if signed {
|
||||
let value = match spec.size {
|
||||
Size::None | Size::Long | Size::Int32 => i64::from(int(slot)),
|
||||
Size::Char => i64::from(slot as u8 as i8),
|
||||
Size::Short => i64::from(slot as u16 as i16),
|
||||
Size::Quad => slot as i64,
|
||||
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
|
||||
};
|
||||
(value < 0, value.unsigned_abs())
|
||||
} else {
|
||||
let value = match spec.size {
|
||||
Size::None | Size::Long | Size::Int32 => u64::from(slot as u32),
|
||||
Size::Char => u64::from(slot as u8),
|
||||
Size::Short => u64::from(slot as u16),
|
||||
Size::Quad => slot,
|
||||
Size::Wide | Size::LongDouble => return Err(FormatError::Invalid),
|
||||
};
|
||||
(false, value)
|
||||
};
|
||||
|
||||
let (base, upper) = match kind {
|
||||
b'o' => (8, false),
|
||||
b'x' => (16, false),
|
||||
b'X' => (16, true),
|
||||
_ => (10, false),
|
||||
};
|
||||
// The precision is the minimum number of digits, 1 by default. A zero
|
||||
// value with a precision of zero has no digits.
|
||||
let precision = spec.precision.unwrap_or(1);
|
||||
let mut number = if magnitude == 0 && precision == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
digits(magnitude, base, upper)
|
||||
};
|
||||
if number.len() < precision {
|
||||
let mut padded = vec![b'0'; precision - number.len()];
|
||||
padded.append(&mut number);
|
||||
number = padded;
|
||||
}
|
||||
|
||||
let mut body = Vec::new();
|
||||
if signed {
|
||||
// The blank is ignored when both it and + appear.
|
||||
if negative {
|
||||
body.push(b'-');
|
||||
} else if spec.flags.plus {
|
||||
body.push(b'+');
|
||||
} else if spec.flags.space {
|
||||
body.push(b' ');
|
||||
}
|
||||
}
|
||||
if spec.flags.alternate {
|
||||
match kind {
|
||||
// ISO C: the precision grows, only if it must, so that the first
|
||||
// digit is a zero. A zero value with a precision of zero is "0".
|
||||
b'o' if number.first() != Some(&b'0') => body.push(b'0'),
|
||||
b'x' if magnitude != 0 => body.extend_from_slice(b"0x"),
|
||||
b'X' if magnitude != 0 => body.extend_from_slice(b"0X"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let lead = body.len();
|
||||
body.append(&mut number);
|
||||
bounded(body.len().max(spec.width))?;
|
||||
// 0 is ignored with - and when an integer has a precision.
|
||||
let zeros = spec.flags.zero && spec.precision.is_none();
|
||||
pad(out, spec, lead, &body, zeros);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Format `format` with the arguments and strings `source` supplies. Returns
|
||||
/// the bytes to write; their number is the function result of the `printf`
|
||||
/// family.
|
||||
pub(super) fn format(format: &[u8], source: &mut dyn Source) -> Result<Vec<u8>, FormatError> {
|
||||
let mut out = Vec::new();
|
||||
let mut parser = Parser { format, at: 0 };
|
||||
while let Some(byte) = parser.peek() {
|
||||
parser.at += 1;
|
||||
if byte != b'%' {
|
||||
out.push(byte);
|
||||
bounded(out.len())?;
|
||||
continue;
|
||||
}
|
||||
if parser.take(b'%') {
|
||||
out.push(b'%');
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut flags = Flags::default();
|
||||
loop {
|
||||
match parser.peek() {
|
||||
Some(b'-') => flags.left = true,
|
||||
Some(b'+') => flags.plus = true,
|
||||
Some(b' ') => flags.space = true,
|
||||
Some(b'#') => flags.alternate = true,
|
||||
Some(b'0') => flags.zero = true,
|
||||
_ => break,
|
||||
}
|
||||
parser.at += 1;
|
||||
}
|
||||
let width = if parser.take(b'*') {
|
||||
// ISO C: a negative width is the - flag and a positive width.
|
||||
let value = int(source.argument().map_err(FormatError::Fault)?);
|
||||
flags.left |= value < 0;
|
||||
bounded(value.unsigned_abs() as usize)?
|
||||
} else {
|
||||
parser.number()?
|
||||
};
|
||||
let precision = if !parser.take(b'.') {
|
||||
None
|
||||
} else if parser.take(b'*') {
|
||||
// ISO C: a negative precision is taken as if it were omitted.
|
||||
let value = int(source.argument().map_err(FormatError::Fault)?);
|
||||
match usize::try_from(value) {
|
||||
Ok(value) => Some(bounded(value)?),
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
Some(parser.number()?)
|
||||
};
|
||||
let size = parser.size();
|
||||
let spec = Spec {
|
||||
flags,
|
||||
width,
|
||||
precision,
|
||||
size,
|
||||
};
|
||||
let kind = parser.peek().ok_or(FormatError::Invalid)?;
|
||||
parser.at += 1;
|
||||
|
||||
match kind {
|
||||
b'd' | b'i' | b'u' | b'o' | b'x' | b'X' => {
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
integer(&mut out, &spec, kind, slot)?;
|
||||
}
|
||||
b'c' => {
|
||||
match spec.size {
|
||||
Size::None | Size::Short => {}
|
||||
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
// The precision has no effect on a character.
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
// Xenora's choice: 0 pads any type, as the page's description
|
||||
// of the flag is not limited to numbers.
|
||||
pad(&mut out, &spec, 0, &[slot as u8], spec.flags.zero);
|
||||
}
|
||||
b's' => {
|
||||
match spec.size {
|
||||
Size::None | Size::Short => {}
|
||||
Size::Long | Size::Wide => return Err(FormatError::Unsupported),
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
let address = source.argument().map_err(FormatError::Fault)?;
|
||||
let limit = spec.precision.unwrap_or(MAX_OUTPUT + 1);
|
||||
let text = if address == 0 {
|
||||
// Xenora's choice: the precision also limits "(null)".
|
||||
let null = b"(null)";
|
||||
null[..null.len().min(limit)].to_vec()
|
||||
} else {
|
||||
source.string(address, limit).map_err(FormatError::Fault)?
|
||||
};
|
||||
bounded(text.len().max(spec.width))?;
|
||||
pad(&mut out, &spec, 0, &text, spec.flags.zero);
|
||||
}
|
||||
b'p' => {
|
||||
if spec.size != Size::None {
|
||||
return Err(FormatError::Invalid);
|
||||
}
|
||||
let slot = source.argument().map_err(FormatError::Fault)?;
|
||||
// "An address in hexadecimal digits" is all the page says.
|
||||
// Xenora's choice: sixteen upper-case digits, and no other
|
||||
// flag or precision has an effect.
|
||||
let text = format!("{slot:016X}");
|
||||
pad(&mut out, &spec, 0, text.as_bytes(), false);
|
||||
}
|
||||
// Wide characters and strings, floating point and the counted
|
||||
// string structures are valid and not modelled.
|
||||
b'C' | b'S' | b'Z' | b'e' | b'E' | b'f' | b'F' | b'g' | b'G' | b'a' | b'A' => {
|
||||
return Err(FormatError::Unsupported);
|
||||
}
|
||||
// %n is disabled by default, and any other character has no
|
||||
// meaning as a type.
|
||||
_ => return Err(FormatError::Invalid),
|
||||
}
|
||||
bounded(out.len())?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FormatError, MAX_OUTPUT, Source, format};
|
||||
use crate::memory::MemoryError;
|
||||
|
||||
/// A string argument is the address `STRINGS + 0x100 * index`.
|
||||
const STRINGS: u64 = 0x1000_0000;
|
||||
|
||||
struct Call {
|
||||
slots: Vec<u64>,
|
||||
strings: Vec<Vec<u8>>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl Source for Call {
|
||||
fn argument(&mut self) -> Result<u64, MemoryError> {
|
||||
let slot = self.slots.get(self.next).copied();
|
||||
self.next += 1;
|
||||
slot.ok_or(MemoryError::UnmappedAddress(self.next as u64))
|
||||
}
|
||||
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
|
||||
let index = ((address - STRINGS) / 0x100) as usize;
|
||||
let text = self
|
||||
.strings
|
||||
.get(index)
|
||||
.ok_or(MemoryError::UnmappedAddress(address))?;
|
||||
Ok(text[..text.len().min(limit)].to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
fn run(text: &str, slots: &[u64], strings: &[&str]) -> Result<String, FormatError> {
|
||||
let mut call = Call {
|
||||
slots: slots.to_vec(),
|
||||
strings: strings
|
||||
.iter()
|
||||
.map(|text| text.as_bytes().to_vec())
|
||||
.collect(),
|
||||
next: 0,
|
||||
};
|
||||
let bytes = format(text.as_bytes(), &mut call)?;
|
||||
assert_eq!(call.next, slots.len(), "{text}: arguments consumed");
|
||||
Ok(String::from_utf8(bytes).unwrap())
|
||||
}
|
||||
|
||||
fn ok(text: &str, slots: &[u64], strings: &[&str]) -> String {
|
||||
run(text, slots, strings).unwrap_or_else(|error| panic!("{text}: {error:?}"))
|
||||
}
|
||||
|
||||
/// The host C library's `snprintf`, on cases whose behaviour ISO C
|
||||
/// defines and Windows shares. `tests/printf/reference.py` wrote the file
|
||||
/// and says how each line is laid out.
|
||||
#[test]
|
||||
fn output_matches_the_host_c_library_on_defined_cases() {
|
||||
let vectors = include_str!("../../tests/printf/vectors.txt");
|
||||
let unhex = |text: &str| -> Vec<u8> {
|
||||
(0..text.len() / 2)
|
||||
.map(|at| u8::from_str_radix(&text[2 * at..2 * at + 2], 16).unwrap())
|
||||
.collect()
|
||||
};
|
||||
let mut cases = 0;
|
||||
for line in vectors.lines().filter(|line| !line.starts_with('#')) {
|
||||
let fields: Vec<&str> = line.split('\t').collect();
|
||||
let [template, arguments, expected] = fields[..] else {
|
||||
panic!("three fields: {line}");
|
||||
};
|
||||
let template = unhex(template);
|
||||
let (mut slots, mut strings) = (Vec::new(), Vec::new());
|
||||
for argument in arguments.split(',').filter(|text| !text.is_empty()) {
|
||||
let (kind, value) = argument.split_once(':').unwrap();
|
||||
match kind {
|
||||
"i" => slots.push(u64::from_str_radix(value, 16).unwrap()),
|
||||
"s" => {
|
||||
slots.push(STRINGS + 0x100 * strings.len() as u64);
|
||||
strings.push(unhex(value));
|
||||
}
|
||||
"n" => slots.push(0),
|
||||
_ => panic!("argument kind {kind}"),
|
||||
}
|
||||
}
|
||||
let mut call = Call {
|
||||
slots,
|
||||
strings,
|
||||
next: 0,
|
||||
};
|
||||
let shown = String::from_utf8_lossy(&template).into_owned();
|
||||
let got = format(&template, &mut call)
|
||||
.unwrap_or_else(|error| panic!("{shown} {arguments}: {error:?}"));
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&got),
|
||||
String::from_utf8_lossy(&unhex(expected)),
|
||||
"{shown} with {arguments}"
|
||||
);
|
||||
assert_eq!(call.next, call.slots.len(), "{shown}: arguments consumed");
|
||||
cases += 1;
|
||||
}
|
||||
assert!(cases > 2000, "{cases} cases");
|
||||
}
|
||||
|
||||
/// Rules the host C library does not share or that the reference leaves
|
||||
/// out, each from the format specification page.
|
||||
#[test]
|
||||
fn windows_sizes_follow_the_format_specification_page() {
|
||||
// "The formatter consumes integer arguments ... as 32-bit int types";
|
||||
// a long is a 32-bit type on Windows. The upper half of the slot is
|
||||
// not part of either.
|
||||
let slot = 0xFFFF_FFFF_8000_0001;
|
||||
assert_eq!(ok("%d", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%ld", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%lu", &[slot], &[]), "2147483649");
|
||||
assert_eq!(ok("%lx", &[0x1_2345_6789], &[]), "23456789");
|
||||
assert_eq!(ok("%I32d", &[slot], &[]), "-2147483647");
|
||||
assert_eq!(ok("%I32u", &[slot], &[]), "2147483649");
|
||||
// ll, I64, j, t, z and I alone are 64-bit.
|
||||
for size in ["ll", "I64", "j", "t", "z", "I"] {
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}d"), &[slot], &[]),
|
||||
"-2147483647",
|
||||
"{size}"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}u"), &[u64::MAX], &[]),
|
||||
"18446744073709551615",
|
||||
"{size}"
|
||||
);
|
||||
assert_eq!(
|
||||
ok(&format!("%{size}x"), &[0x1_2345_6789], &[]),
|
||||
"123456789",
|
||||
"{size}"
|
||||
);
|
||||
}
|
||||
assert_eq!(ok("%I64d", &[1 << 63], &[]), "-9223372036854775808");
|
||||
// I followed by other digits is the size I and then literal text?
|
||||
// No: digits after the size are not a type, so the format is invalid.
|
||||
assert_eq!(run("%I16d", &[1], &[]), Err(FormatError::Invalid));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_characters_and_pointers() {
|
||||
// "If the argument that corresponds to %s ... is a null pointer,
|
||||
// "(null)" is displayed."
|
||||
assert_eq!(ok("[%s]", &[0], &[]), "[(null)]");
|
||||
assert_eq!(ok("[%10s]", &[0], &[]), "[ (null)]");
|
||||
assert_eq!(ok("[%-8s]", &[0], &[]), "[(null) ]");
|
||||
// Xenora's choice: the precision limits it too.
|
||||
assert_eq!(ok("[%.3s]", &[0], &[]), "[(nu]");
|
||||
// h is a single-byte character or string, as no prefix is.
|
||||
assert_eq!(
|
||||
ok("%hc%hs", &[u64::from(b'x'), super::tests::STRINGS], &["yz"]),
|
||||
"xyz"
|
||||
);
|
||||
// The precision has no effect on a character.
|
||||
assert_eq!(ok("[%.0c]", &[0x141], &[]), "[A]");
|
||||
// Xenora's choice for %p: sixteen upper-case hexadecimal digits.
|
||||
assert_eq!(ok("%p", &[0x1_4000_1abc], &[]), "0000000140001ABC");
|
||||
assert_eq!(ok("%p", &[0], &[]), "0000000000000000");
|
||||
assert_eq!(ok("[%20p]", &[0xABC], &[]), "[ 0000000000000ABC]");
|
||||
assert_eq!(ok("[%-20p]", &[0xABC], &[]), "[0000000000000ABC ]");
|
||||
// Xenora's choice: 0 pads a character and a string as it pads a number.
|
||||
assert_eq!(ok("[%03c]", &[u64::from(b'a')], &[]), "[00a]");
|
||||
assert_eq!(ok("[%05s]", &[STRINGS], &["ab"]), "[000ab]");
|
||||
assert_eq!(ok("[%-05s]", &[STRINGS], &["ab"]), "[ab ]");
|
||||
// "+: Use a sign (+ or -) to prefix the output value if it's of a
|
||||
// signed type", and the blank likewise: neither affects an unsigned
|
||||
// conversion.
|
||||
for (text, wanted) in [
|
||||
("%+u", "7"),
|
||||
("% u", "7"),
|
||||
("%+x", "7"),
|
||||
("% X", "7"),
|
||||
("%+o", "7"),
|
||||
("%+ 5u", " 7"),
|
||||
("%+d", "+7"),
|
||||
("% d", " 7"),
|
||||
] {
|
||||
assert_eq!(ok(text, &[7], &[]), wanted, "{text}");
|
||||
}
|
||||
// ISO C for %#.0o with a zero value, which the page does not cover.
|
||||
assert_eq!(ok("[%#.0o]", &[0], &[]), "[0]");
|
||||
assert_eq!(ok("[%.0o]", &[0], &[]), "[]");
|
||||
// Text between and around specifications is copied, and %% is a
|
||||
// percent sign.
|
||||
assert_eq!(
|
||||
ok("100%% of %s%c", &[STRINGS, u64::from(b'!')], &["it"]),
|
||||
"100% of it!"
|
||||
);
|
||||
assert_eq!(ok("", &[], &[]), "");
|
||||
assert_eq!(ok("plain", &[], &[]), "plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_formats_are_refused() {
|
||||
// "The n specifier is disabled by default", and "if a percent sign is
|
||||
// followed by a character that has no meaning as a format field, the
|
||||
// invalid parameter handler is invoked."
|
||||
for text in [
|
||||
"%n",
|
||||
"%hn",
|
||||
"count %d%n",
|
||||
"%y",
|
||||
"%",
|
||||
"%5",
|
||||
"%-",
|
||||
"%.",
|
||||
"%.3",
|
||||
"%l",
|
||||
"%ll",
|
||||
"%h",
|
||||
"%I64",
|
||||
"%5%",
|
||||
"% %",
|
||||
"%!",
|
||||
"%\u{1}",
|
||||
] {
|
||||
let slots = [1, 2, 3];
|
||||
let mut call = Call {
|
||||
slots: slots.to_vec(),
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Invalid),
|
||||
"{text:?}"
|
||||
);
|
||||
}
|
||||
// A size prefix that does not apply to its type.
|
||||
for text in [
|
||||
"%wd", "%Ld", "%wu", "%Lx", "%llc", "%hhc", "%jc", "%lls", "%zs", "%I64s", "%lp",
|
||||
"%hp", "%llp", "%I32c",
|
||||
] {
|
||||
assert_eq!(run(text, &[1], &["s"]), Err(FormatError::Invalid), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_conversions_that_are_not_modelled_are_refused() {
|
||||
for kind in ["e", "E", "f", "F", "g", "G", "a", "A"] {
|
||||
for prefix in ["", ".3", "l", "L", "10.2", "#"] {
|
||||
let text = format!("%{prefix}{kind}");
|
||||
let mut call = Call {
|
||||
slots: vec![0x3FF0_0000_0000_0000],
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Unsupported),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Wide characters and strings: C and S, and c and s with l or w.
|
||||
for text in ["%C", "%S", "%lc", "%ls", "%wc", "%ws", "%Z", "%hC", "%hS"] {
|
||||
let mut call = Call {
|
||||
slots: vec![STRINGS],
|
||||
strings: vec![b"w".to_vec()],
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(text.as_bytes(), &mut call),
|
||||
Err(FormatError::Unsupported),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
// Nothing is produced before a later refusal either: the caller gets
|
||||
// an error, not a prefix.
|
||||
assert_eq!(
|
||||
run("ok %d then %f", &[1, 2], &[]),
|
||||
Err(FormatError::Unsupported)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_faults() {
|
||||
let most = MAX_OUTPUT;
|
||||
// A width or precision up to the bound is honoured; one more is not.
|
||||
assert_eq!(ok(&format!("%{most}d"), &[7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run(&format!("%{}d", most + 1), &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(ok(&format!("%.{most}d"), &[7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run(&format!("%.{}d", most + 1), &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
run("%99999999999999999999d", &[7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// The same through *, and the total over several conversions.
|
||||
assert_eq!(ok("%*d", &[most as u64, 7], &[]).len(), most);
|
||||
assert_eq!(
|
||||
run("%*d", &[most as u64 + 1, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
run("%.*d", &[most as u64 + 1, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
let half = most / 2 + 1;
|
||||
assert_eq!(
|
||||
run(&format!("%{half}d%{half}d"), &[1, 2], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// The most negative width is a left-justified width past the bound.
|
||||
assert_eq!(
|
||||
run("%*d", &[0x8000_0000, 7], &[]),
|
||||
Err(FormatError::TooLong)
|
||||
);
|
||||
// A string is read only up to its precision.
|
||||
assert_eq!(ok("%.2s", &[STRINGS], &["abcdef"]), "ab");
|
||||
|
||||
// A missing argument or an unreadable string is a fault, wherever in
|
||||
// the specification it is needed.
|
||||
for text in [
|
||||
"%d",
|
||||
"%*d",
|
||||
"%.*d",
|
||||
"%5.*d",
|
||||
"%s",
|
||||
"%c",
|
||||
"%p",
|
||||
"%d %d %d %d",
|
||||
] {
|
||||
assert!(
|
||||
matches!(run(text, &[], &[]), Err(FormatError::Fault(_))),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
let mut call = Call {
|
||||
slots: vec![STRINGS + 0x900],
|
||||
strings: Vec::new(),
|
||||
next: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
format(b"%s", &mut call),
|
||||
Err(FormatError::Fault(MemoryError::UnmappedAddress(
|
||||
STRINGS + 0x900
|
||||
)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The standard streams of a hosted C program, and where their output goes.
|
||||
//!
|
||||
//! `__acrt_iob_func` hands out the `FILE` objects for `stdin`, `stdout` and
|
||||
//! `stderr`. What the guest writes to `stdout` and to `stderr` is kept in two
|
||||
//! host-side buffers that a host or a test reads through `ServicesState`.
|
||||
//!
|
||||
//! The standard streams "always open in text mode by default", and in text
|
||||
//! mode "each line feed is replaced with a carriage return-line feed pair"
|
||||
//! that "has no effect on the return value" (Microsoft Learn, "Text and
|
||||
//! binary mode file I/O" and "fwrite"). The buffers hold the bytes after that
|
||||
//! replacement, which is what the operating system would be handed.
|
||||
//!
|
||||
//! Output is never held back: there is no buffering to flush or to configure.
|
||||
//! Any other stream, and input, are not modelled, and using one stops the
|
||||
//! guest with the runtime-limit fault.
|
||||
|
||||
use super::crt_format::{self, FormatError, Source};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
|
||||
/// The exit for a request the runtime does not model.
|
||||
const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
/// `typedef struct _iobuf { void* _Placeholder; } FILE;` (corecrt_wstdio.h).
|
||||
const FILE_BYTES: u64 = 8;
|
||||
/// The most a format string or one `fwrite` or `fputs` may hold.
|
||||
const MAX_TRANSFER: u64 = 1 << 20;
|
||||
/// The most each captured stream keeps. Writing past it stops the guest.
|
||||
pub const MAX_CAPTURED_OUTPUT: usize = 16 << 20;
|
||||
|
||||
/// Option bits of `__stdio_common_vfprintf` (corecrt_stdio_config.h) that do
|
||||
/// not change anything this engine formats: the wide-specifier bit concerns
|
||||
/// the wide functions, and the exponent and rounding bits concern floating
|
||||
/// point. Any other bit stops the guest.
|
||||
const IGNORED_OPTIONS: u64 = 0x04 | 0x10 | 0x20;
|
||||
|
||||
/// `_IOFBF`, `_IOLBF` and `_IONBF` (stdio.h).
|
||||
const IOFBF: i32 = 0x0000;
|
||||
const IOLBF: i32 = 0x0040;
|
||||
const IONBF: i32 = 0x0004;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Stream {
|
||||
Input,
|
||||
Output,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct StandardStreams {
|
||||
/// Guest address of the three `FILE` objects, `stdin` first.
|
||||
files: Option<u64>,
|
||||
output: Vec<u8>,
|
||||
error: Vec<u8>,
|
||||
}
|
||||
|
||||
/// What a service returns when its documentation gives a failure result and
|
||||
/// an `errno` value: the handler sets `errno` to `EINVAL` and returns this.
|
||||
pub(super) struct Invalid<T>(pub T);
|
||||
|
||||
pub(super) type Outcome<T> = Result<Result<T, Invalid<T>>, ExitReason>;
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
/// The bytes of the C string at `address`, without its terminator.
|
||||
fn c_string(memory: &GuestMemory, address: u64, limit: u64) -> Result<Vec<u8>, MemoryError> {
|
||||
let mut bytes = Vec::new();
|
||||
for offset in 0..limit {
|
||||
let at = address.checked_add(offset).ok_or(MemoryError::Overflow)?;
|
||||
match memory.read_u8(at)? {
|
||||
0 => break,
|
||||
byte => bytes.push(byte),
|
||||
}
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Arguments from the guest's `va_list`: one 8-byte slot each, in order.
|
||||
struct VaList<'a> {
|
||||
memory: &'a GuestMemory,
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Source for VaList<'_> {
|
||||
fn argument(&mut self) -> Result<u64, MemoryError> {
|
||||
let slot = self.memory.read_u64(self.next)?;
|
||||
self.next = self.next.checked_add(8).ok_or(MemoryError::Overflow)?;
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
fn string(&mut self, address: u64, limit: usize) -> Result<Vec<u8>, MemoryError> {
|
||||
c_string(self.memory, address, limit as u64)
|
||||
}
|
||||
}
|
||||
|
||||
impl StandardStreams {
|
||||
pub(super) fn output(&self) -> &[u8] {
|
||||
&self.output
|
||||
}
|
||||
|
||||
pub(super) fn error(&self) -> &[u8] {
|
||||
&self.error
|
||||
}
|
||||
|
||||
/// `__acrt_iob_func`: the `FILE` object of `stdin` (0), `stdout` (1) or
|
||||
/// `stderr` (2). The three are allocated together from the process heap
|
||||
/// on first use.
|
||||
pub(super) fn file(&mut self, memory: &mut GuestMemory, index: u32) -> Result<u64, ExitReason> {
|
||||
if index > 2 {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let base = match self.files {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
let base = memory
|
||||
.map_heap_allocation(PROCESS_HEAP, (3 * FILE_BYTES) as usize)
|
||||
.map_err(fault)?;
|
||||
self.files = Some(base);
|
||||
base
|
||||
}
|
||||
};
|
||||
Ok(base + FILE_BYTES * u64::from(index))
|
||||
}
|
||||
|
||||
/// Which standard stream a non-null `FILE*` is. Any other pointer is a
|
||||
/// stream this runtime does not have.
|
||||
fn stream(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
let base = self.files.ok_or(RUNTIME_LIMIT)?;
|
||||
match file.wrapping_sub(base) {
|
||||
0 => Ok(Stream::Input),
|
||||
8 => Ok(Stream::Output),
|
||||
16 => Ok(Stream::Error),
|
||||
_ => Err(RUNTIME_LIMIT),
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream that can be written: `stdout` or `stderr`.
|
||||
fn writable(&self, file: u64) -> Result<Stream, ExitReason> {
|
||||
match self.stream(file)? {
|
||||
Stream::Input => Err(RUNTIME_LIMIT),
|
||||
stream => Ok(stream),
|
||||
}
|
||||
}
|
||||
|
||||
/// Append to a captured stream, in text mode: each line feed becomes a
|
||||
/// carriage return and a line feed.
|
||||
fn write(&mut self, stream: Stream, bytes: &[u8]) -> Result<(), ExitReason> {
|
||||
let captured = match stream {
|
||||
Stream::Output => &mut self.output,
|
||||
Stream::Error => &mut self.error,
|
||||
Stream::Input => return Err(RUNTIME_LIMIT),
|
||||
};
|
||||
let feeds = bytes.iter().filter(|byte| **byte == b'\n').count();
|
||||
if bytes.len() + feeds > MAX_CAPTURED_OUTPUT - captured.len() {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
for &byte in bytes {
|
||||
if byte == b'\n' {
|
||||
captured.push(b'\r');
|
||||
}
|
||||
captured.push(byte);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `__stdio_common_vfprintf`. Returns the number of characters written,
|
||||
/// before the text-mode replacement.
|
||||
pub(super) fn print(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
options: u64,
|
||||
file: u64,
|
||||
format: u64,
|
||||
locale: u64,
|
||||
arguments: u64,
|
||||
) -> Outcome<i32> {
|
||||
// A null stream or format: the function returns -1 and sets errno.
|
||||
if file == 0 || format == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
}
|
||||
if options & !IGNORED_OPTIONS != 0 || locale != 0 {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let template = c_string(memory, format, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if template.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
let mut source = VaList {
|
||||
memory,
|
||||
next: arguments,
|
||||
};
|
||||
let text = match crt_format::format(&template, &mut source) {
|
||||
Ok(text) => text,
|
||||
// Windows calls the invalid parameter handler for an invalid
|
||||
// format. Xenora's choice for when execution continues: nothing
|
||||
// is written and the result is that of a null format.
|
||||
Err(FormatError::Invalid) => return Ok(Err(Invalid(-1))),
|
||||
Err(FormatError::Unsupported | FormatError::TooLong) => return Err(RUNTIME_LIMIT),
|
||||
Err(FormatError::Fault(error)) => return Err(fault(error)),
|
||||
};
|
||||
self.write(stream, &text)?;
|
||||
Ok(Ok(text.len() as i32))
|
||||
}
|
||||
|
||||
/// `fwrite`. Returns the number of whole items written.
|
||||
pub(super) fn write_items(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
buffer: u64,
|
||||
size: u64,
|
||||
count: u64,
|
||||
file: u64,
|
||||
) -> Outcome<u64> {
|
||||
if buffer == 0 || file == 0 {
|
||||
return Ok(Err(Invalid(0)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let Some(length) = size
|
||||
.checked_mul(count)
|
||||
.filter(|bytes| *bytes <= MAX_TRANSFER)
|
||||
else {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
};
|
||||
if length == 0 {
|
||||
return Ok(Ok(0));
|
||||
}
|
||||
let mut bytes = vec![0; length as usize];
|
||||
memory.read_bytes(buffer, &mut bytes).map_err(fault)?;
|
||||
self.write(stream, &bytes)?;
|
||||
Ok(Ok(count))
|
||||
}
|
||||
|
||||
/// `fputs`. Writes the string without its terminator and returns a
|
||||
/// nonnegative value, here 0; `EOF` is -1.
|
||||
pub(super) fn put_string(
|
||||
&mut self,
|
||||
memory: &GuestMemory,
|
||||
text: u64,
|
||||
file: u64,
|
||||
) -> Outcome<i32> {
|
||||
if text == 0 || file == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
}
|
||||
let stream = self.writable(file)?;
|
||||
let bytes = c_string(memory, text, MAX_TRANSFER + 1).map_err(fault)?;
|
||||
if bytes.len() as u64 > MAX_TRANSFER {
|
||||
return Err(RUNTIME_LIMIT);
|
||||
}
|
||||
self.write(stream, &bytes)?;
|
||||
Ok(Ok(0))
|
||||
}
|
||||
|
||||
/// `fflush`. A null stream means every open stream. Nothing is ever held
|
||||
/// back, so there is nothing to do.
|
||||
pub(super) fn flush(&self, file: u64) -> Result<i32, ExitReason> {
|
||||
if file != 0 {
|
||||
self.stream(file)?;
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `setvbuf`. The mode and size are checked as documented and then have
|
||||
/// no effect.
|
||||
pub(super) fn set_buffer(&self, file: u64, mode: i32, size: u64) -> Outcome<i32> {
|
||||
if file == 0 {
|
||||
return Ok(Err(Invalid(-1)));
|
||||
}
|
||||
self.stream(file)?;
|
||||
let valid = match mode {
|
||||
// "No buffer is used, regardless of buffer or size."
|
||||
IONBF => true,
|
||||
// "Allowable range: 2 <= size <= INT_MAX".
|
||||
IOFBF | IOLBF => (2..=i32::MAX as u64).contains(&size),
|
||||
_ => false,
|
||||
};
|
||||
Ok(if valid { Ok(0) } else { Err(Invalid(-1)) })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Reference outputs for the printf formatting engine, from the host C library.
|
||||
|
||||
generate write vectors.txt beside this script
|
||||
--check regenerate in memory; exit 1 if the committed file differs
|
||||
|
||||
The cases are generated here, compiled into a small C program with the host
|
||||
`clang`, and formatted by the host C library's `snprintf`. That library is an
|
||||
implementation of ISO C 7.21.6.1 that shares no code with Xenora, so the file
|
||||
is an independent answer for every case whose result ISO C defines.
|
||||
|
||||
Left out on purpose, because the host and Windows differ or ISO C leaves the
|
||||
result undefined; `crt_format.rs` tests these by hand from Microsoft's page:
|
||||
|
||||
- the `l` size (a long is 64 bits on the host and 32 on Windows), `I`, `I32`
|
||||
and `I64`, which the host does not know
|
||||
- `%p`, and a null pointer for `%s`
|
||||
- `#` with `d`, `i`, `u`, `c` or `s`, `0` with `c` or `s`, and a precision
|
||||
with `c`, which ISO C leaves undefined
|
||||
- floating point, wide characters and `%n`, which the engine refuses
|
||||
|
||||
Each line of vectors.txt is three tab-separated fields:
|
||||
|
||||
format the format string, in hexadecimal
|
||||
arguments comma-separated, in order; `i:<16 hex digits>` is an 8-byte
|
||||
argument slot as the Win64 calling convention passes it (for an
|
||||
int the upper half is junk that must be ignored); `s:<hex>` is a
|
||||
string argument's bytes
|
||||
output what snprintf wrote, in hexadecimal
|
||||
|
||||
Standard library only (Python 3.9+). Needs `clang` on PATH.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
VECTORS = HERE / "vectors.txt"
|
||||
MASK64 = (1 << 64) - 1
|
||||
|
||||
|
||||
class Random:
|
||||
"""xorshift64*, so the cases do not depend on the Python version."""
|
||||
|
||||
def __init__(self, seed):
|
||||
self.state = seed
|
||||
|
||||
def next(self):
|
||||
s = self.state
|
||||
s ^= s >> 12
|
||||
s ^= (s << 25) & MASK64
|
||||
s ^= s >> 27
|
||||
self.state = s
|
||||
return (s * 0x2545F4914F6CDD1D) & MASK64
|
||||
|
||||
def below(self, bound):
|
||||
return self.next() % bound
|
||||
|
||||
def pick(self, items):
|
||||
return items[self.below(len(items))]
|
||||
|
||||
|
||||
EDGES = [0, 1, 2, 7, 8, 9, 10, 15, 16, 99, 100, 127, 128, 255, 256, 4095, 32767, 32768, 65535,
|
||||
65536, 2**31 - 1, 2**31, 2**32 - 1, 2**32, 2**63 - 1, 2**63, 2**64 - 1]
|
||||
|
||||
# size prefix -> (bits, C type for a signed conversion, C type for an unsigned one)
|
||||
SIZES = {
|
||||
"": (32, "int", "unsigned"),
|
||||
"hh": (8, "int", "unsigned"),
|
||||
"h": (16, "int", "unsigned"),
|
||||
"ll": (64, "long long", "unsigned long long"),
|
||||
"j": (64, "intmax_t", "uintmax_t"),
|
||||
"z": (64, "ssize_t", "size_t"),
|
||||
"t": (64, "ptrdiff_t", "size_t"),
|
||||
}
|
||||
STRINGS = [b"", b"a", b"ab", b"hello", b"hello, world", b" padded ", b"100%", b"tab\there",
|
||||
bytes([0xC3, 0xA9, 0x7E, 0x80, 0xFF]), b"x" * 40]
|
||||
|
||||
|
||||
def value(random):
|
||||
kind = random.below(4)
|
||||
if kind == 0:
|
||||
return random.pick(EDGES)
|
||||
if kind == 1:
|
||||
return (-random.pick(EDGES)) & MASK64
|
||||
if kind == 2:
|
||||
return random.below(1000)
|
||||
return random.next()
|
||||
|
||||
|
||||
def junk(random):
|
||||
"""Upper half of a slot that holds a 32-bit argument."""
|
||||
return random.pick([0, 0xFFFFFFFF, 0xDEADBEEF, random.next() >> 32]) << 32
|
||||
|
||||
|
||||
def int_argument(random, number):
|
||||
"""An `int` argument: its C text and its slot."""
|
||||
low = number & 0xFFFFFFFF
|
||||
signed = low - (1 << 32) if low >> 31 else low
|
||||
return f"(int)({signed})", f"i:{junk(random) | low:016x}"
|
||||
|
||||
|
||||
def spec(random, kinds):
|
||||
"""One conversion specification: (text, [(C argument, slot text)])."""
|
||||
kind = random.pick(kinds)
|
||||
arguments = []
|
||||
# + and blank ask for a sign on a signed conversion. On an unsigned one they
|
||||
# are defined and have no effect, which is worth checking.
|
||||
allowed = {"d": "-+ 0", "i": "-+ 0", "u": "-+ 0", "o": "-+ #0", "x": "-+ #0", "X": "-+ #0",
|
||||
"c": "-", "s": "-"}[kind]
|
||||
flags = "".join(flag for flag in allowed if random.below(3) == 0)
|
||||
if flags and random.below(2):
|
||||
flags = flags[::-1]
|
||||
text = "%" + flags
|
||||
|
||||
choice = random.below(6)
|
||||
if choice in (1, 2):
|
||||
text += str(random.pick([1, 2, 3, 5, 8, 12, 20, 33]))
|
||||
elif choice == 3:
|
||||
text += "*"
|
||||
width = random.pick([0, 1, 4, 9, 17, -1, -6, -15])
|
||||
arguments.append(int_argument(random, width))
|
||||
|
||||
if kind != "c":
|
||||
choice = random.below(7)
|
||||
if choice == 1:
|
||||
text += "."
|
||||
elif choice in (2, 3):
|
||||
text += "." + str(random.pick([0, 1, 2, 4, 7, 11, 25]))
|
||||
elif choice == 4:
|
||||
text += ".*"
|
||||
precision = random.pick([0, 1, 3, 6, 14, -1, -5])
|
||||
arguments.append(int_argument(random, precision))
|
||||
|
||||
if kind == "c":
|
||||
byte = random.pick([0x41, 0x7A, 0x20, 0x25, 0x01, 0x7F, 0x80, 0xFF, 0x00, random.below(256)])
|
||||
# The argument is an int; only its low byte is the character.
|
||||
number = byte | (random.below(3) << 8)
|
||||
arguments.append(int_argument(random, number))
|
||||
elif kind == "s":
|
||||
string = random.pick(STRINGS)
|
||||
literal = "".join(f"\\{byte:03o}" for byte in string)
|
||||
arguments.append((f'"{literal}"', "s:" + string.hex()))
|
||||
else:
|
||||
size = random.pick(list(SIZES))
|
||||
text += size
|
||||
bits, signed_type, unsigned_type = SIZES[size]
|
||||
number = value(random)
|
||||
if bits == 64:
|
||||
if kind in "di":
|
||||
signed = number - (1 << 64) if number >> 63 else number
|
||||
# LLONG_MIN has no literal of its own.
|
||||
literal = "(-9223372036854775807LL - 1)" if signed == -(1 << 63) else f"{signed}LL"
|
||||
arguments.append((f"({signed_type})({literal})", f"i:{number:016x}"))
|
||||
else:
|
||||
arguments.append((f"({unsigned_type})({number}ULL)", f"i:{number:016x}"))
|
||||
else:
|
||||
# hh and h arguments are passed as an int that need not be in
|
||||
# range: the library converts it before printing.
|
||||
arguments.append(int_argument(random, number))
|
||||
return text + kind, arguments
|
||||
|
||||
|
||||
def cases():
|
||||
random = Random(0x9E3779B97F4A7C15)
|
||||
out = []
|
||||
literals = ["", "a", " ", "x=", "[", "]", "%%", "100%% ", "\n", "end"]
|
||||
for index in range(2600):
|
||||
if index < 1500:
|
||||
kinds = "diuoxX"
|
||||
elif index < 1800:
|
||||
kinds = "cs"
|
||||
else:
|
||||
kinds = "diuoxXcs"
|
||||
count = 1 if index < 1800 else 1 + random.below(3)
|
||||
text, arguments = random.pick(literals), []
|
||||
for _ in range(count):
|
||||
piece, more = spec(random, kinds)
|
||||
text += piece + random.pick(literals)
|
||||
arguments += more
|
||||
out.append((text.encode(), arguments))
|
||||
return out
|
||||
|
||||
|
||||
def reference(all_cases):
|
||||
lines = ["#include <stdio.h>", "#include <stdint.h>", "#include <stddef.h>",
|
||||
"#include <sys/types.h>",
|
||||
"static char b[8192];",
|
||||
"static void emit(int n) {",
|
||||
" if (n < 0 || n >= (int)sizeof b) { puts(\"!\"); return; }",
|
||||
" for (int i = 0; i < n; i++) printf(\"%02x\", (unsigned char)b[i]);",
|
||||
" putchar('\\n');",
|
||||
"}",
|
||||
"int main(void) {"]
|
||||
for text, arguments in all_cases:
|
||||
literal = "".join(f"\\{byte:03o}" for byte in text)
|
||||
call = ", ".join([f'"{literal}"'] + [argument for argument, _ in arguments])
|
||||
lines.append(f" emit(snprintf(b, sizeof b, {call}));")
|
||||
lines += [" return 0;", "}"]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source, binary = Path(directory, "reference.c"), Path(directory, "reference")
|
||||
source.write_text("\n".join(lines) + "\n")
|
||||
subprocess.run(["clang", "-w", "-O0", source, "-o", binary], check=True)
|
||||
output = subprocess.run([binary], check=True, capture_output=True, text=True).stdout
|
||||
results = output.splitlines()
|
||||
if len(results) != len(all_cases) or "!" in results:
|
||||
sys.exit("the reference program did not format every case")
|
||||
return results
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
|
||||
sys.exit("usage: reference.py generate|--check")
|
||||
all_cases = cases()
|
||||
results = reference(all_cases)
|
||||
header = ["# Generated by crates/loader/tests/printf/reference.py from the host C library's",
|
||||
"# snprintf. Do not edit. Fields: format, arguments, output; see that script."]
|
||||
rows = [f"{text.hex()}\t{','.join(slot for _, slot in arguments)}\t{result}"
|
||||
for (text, arguments), result in zip(all_cases, results)]
|
||||
content = "\n".join(header + rows) + "\n"
|
||||
if argv[1] == "generate":
|
||||
VECTORS.write_text(content)
|
||||
elif not VECTORS.exists() or VECTORS.read_text() != content:
|
||||
sys.exit("vectors.txt differs from the host C library's output; run reference.py generate")
|
||||
print(f"vectors.txt: {len(rows)} cases")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -21,8 +21,8 @@ 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::{
|
||||
MAX_PROGRAM_ARGUMENT_BYTES, MockClock, ProgramArgumentsError, ServicesState,
|
||||
register_standard_services,
|
||||
MAX_CAPTURED_OUTPUT, MAX_PROGRAM_ARGUMENT_BYTES, MockClock, ProgramArgumentsError,
|
||||
ServicesState, register_standard_services,
|
||||
};
|
||||
|
||||
const BASE: u64 = 0x1_4000_0000;
|
||||
@@ -625,6 +625,443 @@ fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() {
|
||||
assert_eq!(guest.last_error(), 5);
|
||||
}
|
||||
|
||||
/// Guest memory for format strings, argument lists and strings.
|
||||
const TEXT: u64 = 0x100_0000;
|
||||
const TEXT_LEN: usize = 0x10_0000 + 0x1000;
|
||||
/// Where `print` puts the `va_list`, and where string arguments start.
|
||||
const VA_LIST: u64 = TEXT + 0x400;
|
||||
const STRINGS: u64 = TEXT + 0x800;
|
||||
/// What a program built with mingw-w64 passes as the options of
|
||||
/// `__stdio_common_vfprintf`.
|
||||
const MINGW_OPTIONS: u64 = 0x24;
|
||||
const LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
const STDIO_EINVAL: u32 = 22;
|
||||
/// The low 32 bits of an `int` result of -1, which is also `EOF`.
|
||||
const STDIO_MINUS_ONE: u64 = 0xFFFF_FFFF;
|
||||
|
||||
/// A guest with its three standard streams and room for text.
|
||||
fn stdio_guest() -> (Guest, [u64; 3]) {
|
||||
let mut guest = Guest::new();
|
||||
guest
|
||||
.memory
|
||||
.map_region(TEXT, TEXT_LEN, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let streams = [0, 1, 2].map(|index| guest.call("__acrt_iob_func", &[index]));
|
||||
(guest, streams)
|
||||
}
|
||||
|
||||
/// Put a NUL-terminated string in guest memory and return its address.
|
||||
fn place(guest: &mut Guest, at: u64, text: &[u8]) -> u64 {
|
||||
guest.memory.write_bytes(at, text).unwrap();
|
||||
guest.memory.write_u8(at + text.len() as u64, 0).unwrap();
|
||||
at
|
||||
}
|
||||
|
||||
/// Call `__stdio_common_vfprintf` as compiled code does: the format string
|
||||
/// and the `va_list` are in guest memory, and the fifth argument is on the
|
||||
/// stack above the shadow space.
|
||||
fn print_with(
|
||||
guest: &mut Guest,
|
||||
options: u64,
|
||||
stream: u64,
|
||||
format: &[u8],
|
||||
slots: &[u64],
|
||||
) -> (u64, ExitReason) {
|
||||
let format = place(guest, TEXT, format);
|
||||
for (index, slot) in slots.iter().enumerate() {
|
||||
guest
|
||||
.memory
|
||||
.write_u64(VA_LIST + 8 * index as u64, *slot)
|
||||
.unwrap();
|
||||
}
|
||||
guest.memory.write_u64(STACK_TOP + 32, VA_LIST).unwrap();
|
||||
let (cpu, exit) = guest.run("__stdio_common_vfprintf", &[options, stream, format, 0]);
|
||||
(cpu.get(Register::Rax) & 0xFFFF_FFFF, exit)
|
||||
}
|
||||
|
||||
fn print(guest: &mut Guest, stream: u64, format: &[u8], slots: &[u64]) -> u64 {
|
||||
let (count, exit) = print_with(guest, MINGW_OPTIONS, stream, format, slots);
|
||||
assert_eq!(
|
||||
exit,
|
||||
ExitReason::Halt,
|
||||
"{}",
|
||||
String::from_utf8_lossy(format)
|
||||
);
|
||||
count
|
||||
}
|
||||
|
||||
/// `__acrt_iob_func` (corecrt_wstdio.h) is what `stdin`, `stdout` and
|
||||
/// `stderr` expand to: indices 0, 1 and 2. A `FILE` is one pointer wide.
|
||||
#[test]
|
||||
fn standard_streams_are_three_stable_file_objects() {
|
||||
let (mut guest, streams) = stdio_guest();
|
||||
let mut sorted = streams;
|
||||
sorted.sort_unstable();
|
||||
assert!(sorted[0] != 0 && sorted[1] - sorted[0] >= 8 && sorted[2] - sorted[1] >= 8);
|
||||
// Each call returns the same object, and the index is an unsigned int.
|
||||
for (index, stream) in streams.into_iter().enumerate() {
|
||||
let index = index as u64;
|
||||
assert_eq!(guest.call("__acrt_iob_func", &[index]), stream);
|
||||
assert_eq!(
|
||||
guest.call("__acrt_iob_func", &[0xFFFF_FFFF_0000_0000 | index]),
|
||||
stream
|
||||
);
|
||||
}
|
||||
// There is no fourth standard stream.
|
||||
for index in [3, 4, 0x8000_0000, 0xFFFF_FFFF] {
|
||||
assert_eq!(
|
||||
guest.run("__acrt_iob_func", &[index]).1,
|
||||
LIMIT,
|
||||
"{index:#x}"
|
||||
);
|
||||
}
|
||||
// Asking for a stream writes nothing to it.
|
||||
assert!(guest.state.standard_output().is_empty());
|
||||
assert!(guest.state.standard_error().is_empty());
|
||||
}
|
||||
|
||||
/// `__stdio_common_vfprintf` is what `printf` and `fprintf` call. It returns
|
||||
/// "the number of characters written" (Microsoft Learn, vfprintf). The
|
||||
/// standard streams are text-mode streams, where "each line feed is replaced
|
||||
/// with a carriage return-line feed pair" that "has no effect on the return
|
||||
/// value" (fwrite). Expected text follows the format specification page.
|
||||
#[test]
|
||||
fn formatted_output_reaches_the_captured_standard_streams() {
|
||||
let (mut guest, [_, out, err]) = stdio_guest();
|
||||
// The calls the Gate A2 program makes, with the options mingw-w64 passes.
|
||||
assert_eq!(print(&mut guest, out, b"gate a2: %d arguments\n", &[3]), 21);
|
||||
let one = place(&mut guest, STRINGS, b"one");
|
||||
assert_eq!(print(&mut guest, out, b"arg %d = %s\n", &[1, one]), 12);
|
||||
assert_eq!(
|
||||
guest.state.standard_output(),
|
||||
b"gate a2: 3 arguments\r\narg 1 = one\r\n"
|
||||
);
|
||||
assert!(guest.state.standard_error().is_empty());
|
||||
|
||||
// stderr is a separate buffer.
|
||||
assert_eq!(print(&mut guest, err, b"%s: %#x\n", &[one, 0xa2]), 10);
|
||||
assert_eq!(guest.state.standard_error(), b"one: 0xa2\r\n");
|
||||
assert_eq!(guest.state.standard_output().len(), 35);
|
||||
|
||||
// The arguments are 8-byte slots read in order from the va_list: a width
|
||||
// from *, an int whose upper half is junk, a 64-bit value, a string with
|
||||
// a precision, a character and a pointer.
|
||||
let junk = 0xDEAD_BEEF_0000_0000;
|
||||
let slots = [
|
||||
6,
|
||||
junk | 0xFFFF_FFFE,
|
||||
u64::MAX,
|
||||
one,
|
||||
u64::from(b'!'),
|
||||
0x1_4000_2000,
|
||||
];
|
||||
let (mut fresh, [_, out, _]) = stdio_guest();
|
||||
let one = place(&mut fresh, STRINGS, b"one");
|
||||
let slots = [slots[0], slots[1], slots[2], one, slots[4], slots[5]];
|
||||
let text: &[u8] = b"[%*d] %llu %.2s%c %p";
|
||||
// The result is the number of characters in the text below: 50.
|
||||
let expected: &[u8] = b"[ -2] 18446744073709551615 on! 0000000140002000";
|
||||
assert_eq!(print(&mut fresh, out, text, &slots), 50);
|
||||
assert_eq!(expected.len(), 50);
|
||||
assert_eq!(fresh.state.standard_output(), expected);
|
||||
|
||||
// Several line feeds in one call, text with none, and an empty format.
|
||||
let (mut guest, [_, out, _]) = stdio_guest();
|
||||
assert_eq!(print(&mut guest, out, b"a\n\nb\n", &[]), 5);
|
||||
assert_eq!(print(&mut guest, out, b"no newline", &[]), 10);
|
||||
assert_eq!(print(&mut guest, out, b"", &[]), 0);
|
||||
// A carriage return the program wrote itself is kept as it is.
|
||||
assert_eq!(print(&mut guest, out, b"\r\n", &[]), 2);
|
||||
assert_eq!(
|
||||
guest.state.standard_output(),
|
||||
b"a\r\n\r\nb\r\nno newline\r\r\n"
|
||||
);
|
||||
|
||||
// The option bits that concern wide functions and floating point change
|
||||
// nothing here.
|
||||
for options in [0, 0x04, 0x10, 0x20, 0x24, 0x34] {
|
||||
let (mut guest, [_, out, _]) = stdio_guest();
|
||||
let (count, exit) = print_with(&mut guest, options, out, b"%5.3d|%-4x|", &[7, 255]);
|
||||
assert_eq!((count, exit), (11, ExitReason::Halt), "{options:#x}");
|
||||
assert_eq!(
|
||||
guest.state.standard_output(),
|
||||
b" 007|ff |",
|
||||
"{options:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What `__stdio_common_vfprintf` refuses. A null stream or format returns -1
|
||||
/// with `errno` `EINVAL` (Microsoft Learn, vfprintf). An invalid format calls
|
||||
/// the invalid parameter handler on Windows; here it returns the same -1 and
|
||||
/// writes nothing. What the runtime does not model stops the guest. In every
|
||||
/// case nothing reaches either stream.
|
||||
#[test]
|
||||
fn formatted_output_refuses_what_it_cannot_print_correctly() {
|
||||
let (mut guest, [input, out, _]) = stdio_guest();
|
||||
let quiet = |guest: &Guest| {
|
||||
assert!(guest.state.standard_output().is_empty());
|
||||
assert!(guest.state.standard_error().is_empty());
|
||||
};
|
||||
|
||||
// Null stream, null format.
|
||||
guest.set_errno(0);
|
||||
let format = place(&mut guest, TEXT, b"text");
|
||||
guest.memory.write_u64(STACK_TOP + 32, VA_LIST).unwrap();
|
||||
for args in [[MINGW_OPTIONS, 0, format, 0], [MINGW_OPTIONS, out, 0, 0]] {
|
||||
let result = guest.call("__stdio_common_vfprintf", &args);
|
||||
assert_eq!(result & 0xFFFF_FFFF, STDIO_MINUS_ONE, "{args:x?}");
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL, "{args:x?}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
quiet(&guest);
|
||||
|
||||
// %n is disabled by default, and a character with no meaning as a type
|
||||
// is invalid. The text before it is not written.
|
||||
for format in [&b"count%n"[..], b"before %d then %y", b"%", b"100%"] {
|
||||
let (count, exit) = print_with(&mut guest, MINGW_OPTIONS, out, format, &[1, 2]);
|
||||
assert_eq!((count, exit), (STDIO_MINUS_ONE, ExitReason::Halt));
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL);
|
||||
guest.set_errno(0);
|
||||
}
|
||||
quiet(&guest);
|
||||
|
||||
// Floating point and wide strings are valid and not modelled.
|
||||
for format in [&b"%f"[..], b"ok %d then %g", b"%ls", b"%S", b"%lc"] {
|
||||
let (_, exit) = print_with(&mut guest, MINGW_OPTIONS, out, format, &[1, 2]);
|
||||
assert_eq!(exit, LIMIT, "{}", String::from_utf8_lossy(format));
|
||||
}
|
||||
// Option bits that change how the format is read or that belong to the
|
||||
// buffer functions, and unknown bits.
|
||||
for options in [0x01, 0x02, 0x08, 0x40, 0x25, 1 << 32, u64::MAX] {
|
||||
let (_, exit) = print_with(&mut guest, options, out, b"x", &[]);
|
||||
assert_eq!(exit, LIMIT, "{options:#x}");
|
||||
}
|
||||
// A locale object.
|
||||
let format = place(&mut guest, TEXT, b"x");
|
||||
let args = [MINGW_OPTIONS, out, format, STRINGS];
|
||||
assert_eq!(guest.run("__stdio_common_vfprintf", &args).1, LIMIT);
|
||||
// stdin, and pointers that are no stream: beside a FILE object, inside
|
||||
// one, and elsewhere.
|
||||
for stream in [input, out + 1, out + 24, out - 16, TEXT, 8] {
|
||||
let (_, exit) = print_with(&mut guest, MINGW_OPTIONS, stream, b"x", &[]);
|
||||
assert_eq!(exit, LIMIT, "{stream:#x}");
|
||||
}
|
||||
// Unreadable memory is a fault at the address that could not be read.
|
||||
let unmapped = 0x9_0000_0000;
|
||||
let (_, exit) = print_with(&mut guest, MINGW_OPTIONS, out, b"%s", &[unmapped]);
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
guest.memory.write_u64(STACK_TOP + 32, unmapped).unwrap();
|
||||
for args in [
|
||||
[MINGW_OPTIONS, out, format, 0],
|
||||
[MINGW_OPTIONS, out, unmapped, 0],
|
||||
] {
|
||||
let format_reads_arguments = place(&mut guest, TEXT, b"%d");
|
||||
assert_eq!(format_reads_arguments, format);
|
||||
let exit = guest.run("__stdio_common_vfprintf", &args).1;
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
}
|
||||
quiet(&guest);
|
||||
// None of the stops set errno.
|
||||
assert_eq!(guest.errno(), 0);
|
||||
|
||||
// A guest that never asked for its streams has none to write to.
|
||||
let mut fresh = Guest::new();
|
||||
fresh
|
||||
.memory
|
||||
.map_region(TEXT, TEXT_LEN, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let (_, exit) = print_with(&mut fresh, MINGW_OPTIONS, out, b"x", &[]);
|
||||
assert_eq!(exit, LIMIT);
|
||||
}
|
||||
|
||||
/// `fwrite` "returns the number of full items the function writes" and, for a
|
||||
/// null buffer or stream, sets `errno` to `EINVAL` and returns 0. `fputs`
|
||||
/// returns "a nonnegative value if it's successful", copies no terminating
|
||||
/// null, and returns `EOF` with `EINVAL` for a null pointer (Microsoft Learn).
|
||||
#[test]
|
||||
fn fwrite_and_fputs_write_to_the_captured_standard_streams() {
|
||||
let (mut guest, [input, out, err]) = stdio_guest();
|
||||
let text = place(&mut guest, TEXT, b"cleanup ran\nxyz");
|
||||
// Twelve items of one byte, then three items of four bytes to stderr.
|
||||
assert_eq!(guest.call("fwrite", &[text, 1, 12, out]), 12);
|
||||
assert_eq!(guest.call("fwrite", &[text, 4, 3, err]), 3);
|
||||
assert_eq!(guest.state.standard_output(), b"cleanup ran\r\n");
|
||||
assert_eq!(guest.state.standard_error(), b"cleanup ran\r\n");
|
||||
// No items or no size writes nothing and returns 0.
|
||||
for (size, count) in [(0, 5), (5, 0), (0, 0)] {
|
||||
assert_eq!(guest.call("fwrite", &[text, size, count, out]), 0);
|
||||
}
|
||||
assert_eq!(guest.state.standard_output().len(), 13);
|
||||
// A byte of zero is data to fwrite.
|
||||
assert_eq!(guest.call("fwrite", &[text + 14, 1, 2, out]), 2);
|
||||
assert_eq!(guest.state.standard_output()[13..], [b'z', 0]);
|
||||
|
||||
guest.set_errno(0);
|
||||
for args in [[0, 1, 4, out], [text, 1, 4, 0]] {
|
||||
assert_eq!(guest.call("fwrite", &args), 0, "{args:x?}");
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL, "{args:x?}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
// stdin, another pointer, more than this runtime transfers at once, a
|
||||
// product that overflows, and unreadable memory.
|
||||
for args in [
|
||||
[text, 1, 4, input],
|
||||
[text, 1, 4, TEXT],
|
||||
[text, 1, (1 << 20) + 1, out],
|
||||
[text, 1 << 33, 1 << 33, out],
|
||||
] {
|
||||
assert_eq!(guest.run("fwrite", &args).1, LIMIT, "{args:x?}");
|
||||
}
|
||||
let exit = guest.run("fwrite", &[0x9_0000_0000, 1, 4, out]).1;
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
assert_eq!(guest.state.standard_output().len(), 15);
|
||||
assert_eq!(guest.errno(), 0);
|
||||
|
||||
// fputs writes up to the terminator and not the terminator itself.
|
||||
let (mut guest, [input, out, err]) = stdio_guest();
|
||||
let text = place(&mut guest, TEXT, b"cleanup ran\n");
|
||||
assert_eq!(guest.call("fputs", &[text, out]) & 0xFFFF_FFFF, 0);
|
||||
let empty = place(&mut guest, STRINGS, b"");
|
||||
assert_eq!(guest.call("fputs", &[empty, out]) & 0xFFFF_FFFF, 0);
|
||||
assert_eq!(guest.call("fputs", &[text + 8, err]) & 0xFFFF_FFFF, 0);
|
||||
assert_eq!(guest.state.standard_output(), b"cleanup ran\r\n");
|
||||
assert_eq!(guest.state.standard_error(), b"ran\r\n");
|
||||
guest.set_errno(0);
|
||||
for args in [[0, out], [text, 0]] {
|
||||
assert_eq!(guest.call("fputs", &args) & 0xFFFF_FFFF, STDIO_MINUS_ONE);
|
||||
assert_eq!(guest.errno(), STDIO_EINVAL, "{args:x?}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
for args in [[text, input], [text, TEXT]] {
|
||||
assert_eq!(guest.run("fputs", &args).1, LIMIT, "{args:x?}");
|
||||
}
|
||||
let exit = guest.run("fputs", &[0x9_0000_0000, out]).1;
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
assert_eq!(guest.state.standard_output().len(), 13);
|
||||
}
|
||||
|
||||
/// `fflush` "returns 0 if the buffer was successfully flushed", and a null
|
||||
/// stream means every open stream. `setvbuf` "returns 0 if successful"; for a
|
||||
/// null stream or a mode or size that is not valid it returns -1 and sets
|
||||
/// `errno` to `EINVAL`. The modes are `_IOFBF` (0), `_IOLBF` (0x40) and
|
||||
/// `_IONBF` (4), and the size must be from 2 to `INT_MAX` unless the mode is
|
||||
/// `_IONBF` (Microsoft Learn; values from stdio.h).
|
||||
#[test]
|
||||
fn fflush_and_setvbuf_return_their_documented_results() {
|
||||
let (mut guest, [input, out, err]) = stdio_guest();
|
||||
for stream in [0, input, out, err] {
|
||||
assert_eq!(
|
||||
guest.call("fflush", &[stream]) & 0xFFFF_FFFF,
|
||||
0,
|
||||
"{stream:#x}"
|
||||
);
|
||||
}
|
||||
for stream in [TEXT, out + 4, 16] {
|
||||
assert_eq!(guest.run("fflush", &[stream]).1, LIMIT, "{stream:#x}");
|
||||
}
|
||||
|
||||
const INT_MAX: u64 = 0x7FFF_FFFF;
|
||||
let junk = 0xFFFF_FFFF_0000_0000;
|
||||
guest.set_errno(0);
|
||||
for (args, result) in [
|
||||
// The call the mingw-w64 startup makes: stderr, unbuffered.
|
||||
([err, 0, 4, 0], 0),
|
||||
// No buffer is used, regardless of buffer or size.
|
||||
([out, TEXT, 4, 1], 0),
|
||||
([out, 0, 4, u64::MAX], 0),
|
||||
([out, 0, 0, 4096], 0),
|
||||
([out, TEXT, 0, 2], 0),
|
||||
([input, 0, 0x40, INT_MAX], 0),
|
||||
// The mode is an int.
|
||||
([out, 0, junk | 0x40, 2], 0),
|
||||
// A size outside 2 to INT_MAX, and modes that are not one of the three.
|
||||
([out, 0, 0, 1], STDIO_MINUS_ONE),
|
||||
([out, 0, 0, 0], STDIO_MINUS_ONE),
|
||||
([out, 0, 0x40, INT_MAX + 1], STDIO_MINUS_ONE),
|
||||
([out, 0, 1, 4096], STDIO_MINUS_ONE),
|
||||
([out, 0, 0x44, 4096], STDIO_MINUS_ONE),
|
||||
([out, 0, 0xFFFF_FFFF, 4096], STDIO_MINUS_ONE),
|
||||
([0, 0, 4, 0], STDIO_MINUS_ONE),
|
||||
] {
|
||||
assert_eq!(
|
||||
guest.call("setvbuf", &args) & 0xFFFF_FFFF,
|
||||
result,
|
||||
"{args:x?}"
|
||||
);
|
||||
let errno = if result == 0 { 0 } else { STDIO_EINVAL };
|
||||
assert_eq!(guest.errno(), errno, "{args:x?}");
|
||||
guest.set_errno(0);
|
||||
}
|
||||
assert_eq!(guest.run("setvbuf", &[TEXT, 0, 4, 0]).1, LIMIT);
|
||||
|
||||
// Neither function holds output back or lets any through.
|
||||
assert!(guest.state.standard_output().is_empty());
|
||||
assert_eq!(print(&mut guest, out, b"now", &[]), 3);
|
||||
assert_eq!(guest.state.standard_output(), b"now");
|
||||
}
|
||||
|
||||
/// Each captured stream keeps at most `MAX_CAPTURED_OUTPUT` bytes, counted
|
||||
/// after the text-mode replacement, and a write that would pass it stops the
|
||||
/// guest and adds nothing.
|
||||
#[test]
|
||||
fn captured_output_is_bounded() {
|
||||
let (mut guest, [_, out, err]) = stdio_guest();
|
||||
const CHUNK: u64 = 1 << 20;
|
||||
assert_eq!(MAX_CAPTURED_OUTPUT as u64, 16 * CHUNK);
|
||||
guest
|
||||
.memory
|
||||
.write_bytes(TEXT, &vec![b'x'; CHUNK as usize])
|
||||
.unwrap();
|
||||
for _ in 0..15 {
|
||||
assert_eq!(guest.call("fwrite", &[TEXT, 1, CHUNK, out]), CHUNK);
|
||||
}
|
||||
assert_eq!(guest.call("fwrite", &[TEXT, 1, CHUNK - 2, out]), CHUNK - 2);
|
||||
// Two bytes of room: a line feed takes both.
|
||||
guest.memory.write_bytes(TEXT, b"\n\nxx").unwrap();
|
||||
assert_eq!(guest.run("fwrite", &[TEXT, 1, 2, out]).1, LIMIT);
|
||||
assert_eq!(guest.run("fwrite", &[TEXT + 1, 1, 2, out]).1, LIMIT);
|
||||
assert_eq!(guest.state.standard_output().len(), MAX_CAPTURED_OUTPUT - 2);
|
||||
assert_eq!(guest.call("fwrite", &[TEXT, 1, 1, out]), 1);
|
||||
assert_eq!(guest.state.standard_output().len(), MAX_CAPTURED_OUTPUT);
|
||||
assert_eq!(guest.run("fwrite", &[TEXT + 2, 1, 1, out]).1, LIMIT);
|
||||
assert_eq!(guest.state.standard_output().len(), MAX_CAPTURED_OUTPUT);
|
||||
// The other stream has its own room.
|
||||
assert_eq!(guest.call("fwrite", &[TEXT + 2, 1, 2, err]), 2);
|
||||
assert_eq!(guest.state.standard_error(), b"xx");
|
||||
}
|
||||
|
||||
/// The module and symbol pairs a program built with mingw-w64 14.0.0 (UCRT)
|
||||
/// imports these six services by, read from such a program's import table.
|
||||
#[test]
|
||||
fn standard_stream_services_resolve_as_mingw_w64_imports_them() {
|
||||
let (registry, _) = standard(0);
|
||||
let named = |name: &str| ImportName::Name(name.to_owned());
|
||||
const STDIO: &str = "api-ms-win-crt-stdio-l1-1-0.dll";
|
||||
for symbol in [
|
||||
"__acrt_iob_func",
|
||||
"__stdio_common_vfprintf",
|
||||
"fwrite",
|
||||
"fputs",
|
||||
"fflush",
|
||||
"setvbuf",
|
||||
] {
|
||||
let service = registry
|
||||
.resolve(STDIO, &named(symbol))
|
||||
.unwrap_or_else(|| panic!("{symbol}"));
|
||||
let target = registry.resolve("ucrtbase.dll", &named(symbol)).unwrap();
|
||||
assert!(std::ptr::eq(service, target), "{symbol}");
|
||||
assert_eq!(service.status, ServiceStatus::Partial, "{symbol}");
|
||||
// Not through the runtime API set, which lists other symbols.
|
||||
assert!(
|
||||
registry
|
||||
.resolve("api-ms-win-crt-runtime-l1-1-0.dll", &named(symbol))
|
||||
.is_none(),
|
||||
"{symbol}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_error_is_set_by_failures_and_by_the_guest() {
|
||||
let mut guest = Guest::new();
|
||||
|
||||
@@ -343,6 +343,62 @@ Allocation failures also set the synthetic main thread's CRT `errno` to
|
||||
and CRT parameter or new-handler callbacks remain unsupported. See
|
||||
[Microsoft CRT allocation documentation](https://learn.microsoft.com/cpp/c-runtime-library/memory-allocation).
|
||||
|
||||
### Standard output and formatted printing
|
||||
|
||||
A hosted C program prints through the C runtime. Six services give it the
|
||||
standard streams, and what it writes to `stdout` and to `stderr` is captured
|
||||
where a host or a test can read it: `ServicesState::standard_output()` and
|
||||
`ServicesState::standard_error()`.
|
||||
|
||||
| Service | Behaviour |
|
||||
| --- | --- |
|
||||
| `__acrt_iob_func(index)` | The `FILE` object of `stdin` (0), `stdout` (1) or `stderr` (2) |
|
||||
| `__stdio_common_vfprintf(options, stream, format, locale, arguments)` | Formats with the arguments in the guest's `va_list`, writes to `stdout` or `stderr`, and returns the number of characters written. This is what `printf` and `fprintf` call |
|
||||
| `fwrite(buffer, size, count, stream)` | Writes `size * count` bytes and returns `count` |
|
||||
| `fputs(string, stream)` | Writes the string without its terminator and returns 0 |
|
||||
| `fflush(stream)` | Returns 0. A null stream means every stream |
|
||||
| `setvbuf(stream, buffer, mode, size)` | Checks the mode and size and returns 0 |
|
||||
|
||||
The standard streams are text-mode streams, so each line feed a program
|
||||
writes is captured as a carriage return and a line feed, as the Windows
|
||||
documentation of text mode describes. Function results count the characters
|
||||
before that replacement. Output is never held back: `fflush` has nothing to
|
||||
do and `setvbuf` only validates. Each captured stream keeps at most 16 MiB
|
||||
(`MAX_CAPTURED_OUTPUT`).
|
||||
|
||||
The formatting engine (`crates/loader/src/services/crt_format.rs`) follows
|
||||
Microsoft's "Format specification syntax: printf and wprintf functions" and
|
||||
ISO C:
|
||||
|
||||
- Flags `-`, `+`, blank, `#` and `0`; a width and a precision as digits or
|
||||
`*`; size prefixes `hh`, `h`, `l`, `ll`, `j`, `z`, `t`, `I`, `I32`, `I64`.
|
||||
- Types `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%`. An integer
|
||||
without a size prefix, and a `long`, is 32 bits. A null string prints
|
||||
`(null)`.
|
||||
- Its output is compared with the host C library's `snprintf` on 2,600
|
||||
generated cases whose result ISO C defines
|
||||
(`crates/loader/tests/printf/reference.py`).
|
||||
|
||||
Documented failures return their documented result and set `errno` to
|
||||
`EINVAL`: a null stream, format, buffer or string, and an invalid `setvbuf`
|
||||
mode or size. An invalid format, which includes `%n` because Windows
|
||||
disables it by default, also returns -1 with `EINVAL` and writes nothing;
|
||||
on Windows the invalid parameter handler runs first.
|
||||
|
||||
Everything else that is not modelled stops the guest with the runtime-limit
|
||||
fault and writes nothing, so that nothing is printed wrongly: the
|
||||
floating-point types (`e`, `f`, `g`, `a`), wide characters and strings (`C`,
|
||||
`S`, `lc`, `ls`), a locale object, option bits other than the three that do
|
||||
not affect these conversions, any stream other than `stdout` and `stderr`
|
||||
(files do not exist yet, and `stdin` cannot be written), an index above 2,
|
||||
more than 1 MiB in one call, and output past the 16 MiB bound.
|
||||
|
||||
Choices where the documentation leaves room, each marked in the source:
|
||||
`%p` prints sixteen upper-case hexadecimal digits; `0` pads a character and
|
||||
a string as it pads a number; a precision also limits `(null)`; `%#.0o` of
|
||||
zero prints `0`, which is ISO C's rule. All six services are `partial`. None
|
||||
of this has been compared with Windows.
|
||||
|
||||
### CRT integer conversion
|
||||
|
||||
UCRT and the CRT conversion API set expose strtol, strtoul, wcstol, and
|
||||
|
||||
@@ -6,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
|
||||
|
||||
| Measure | Count |
|
||||
| --- | ---: |
|
||||
| Services with a declared ABI | 37 |
|
||||
| Generated adapters | 37 |
|
||||
| Unique handler implementations | 37 |
|
||||
| Services with a declared ABI | 43 |
|
||||
| Generated adapters | 43 |
|
||||
| Unique handler implementations | 43 |
|
||||
| Implemented | 7 |
|
||||
| Partial | 27 |
|
||||
| Partial | 33 |
|
||||
| Stub | 3 |
|
||||
| Conformance-tested through guest dispatch | 37 |
|
||||
| API-set aliases (not services) | 37 |
|
||||
| Conformance-tested through guest dispatch | 43 |
|
||||
| API-set aliases (not services) | 43 |
|
||||
| Independently accepted | 0 |
|
||||
|
||||
| Service | Signature | Status | Failure |
|
||||
@@ -30,6 +30,12 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
|
||||
| `kernel32.dll!SetThreadPriority` | `(thread: handle, priority: i32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER |
|
||||
| `kernel32.dll!CloseHandle` | `(object: handle) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE |
|
||||
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
|
||||
| `ucrtbase.dll!__acrt_iob_func` | `(index: u32) -> ptr` | partial | stops the guest for an index above 2 or when the streams cannot be allocated |
|
||||
| `ucrtbase.dll!__stdio_common_vfprintf` | `(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32` | partial | -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled |
|
||||
| `ucrtbase.dll!fwrite` | `(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64` | partial | 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr |
|
||||
| `ucrtbase.dll!fputs` | `(text: ptr, stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr |
|
||||
| `ucrtbase.dll!fflush` | `(stream: ptr) -> i32` | partial | stops the guest for a stream that is not a standard stream |
|
||||
| `ucrtbase.dll!setvbuf` | `(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32` | partial | -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream |
|
||||
| `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 |
|
||||
|
||||
Reference in new issue
Block a user