Merge task/402-crt-files into task/419-gate-a2

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

No files matched your search

+4
View File
@@ -114,6 +114,8 @@ remains unsupported.
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
- Added files for a hosted C program (#402, part of Gate A2): `fopen`, `fclose`, `fgets` and `perror`, and file streams for the output services from #400, so `fprintf`, `fwrite` and `fputs` write to a file `fopen` returned. The files are the ones on the in-memory `C:` drive behind `CreateFileW`, so a file written through a C stream is the file `ReadFile` reads, and the reverse. `fopen` takes `r`, `w` or `a` with `+`, `b` and `t` as Microsoft's page describes them; text mode, the default, stores a line feed as carriage return and line feed, reads the pair back as a line feed and ends input at `CTRL+Z`. Failures return their documented results; the `errno` values beyond `EINVAL` for a null or empty argument are Xenora's choice. Nothing is buffered, there is no seeking, a C stream takes no part in Win32 sharing, and the other mode characters are refused. All four services are `partial`. Eight tests in `runtime_services.rs`, four in the new `crt_files.rs` that cross-check with `ReadFile` and `WriteFile`, and a unit test of the mode strings cover it. Not compared with Windows; awaiting independent review.
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
- Added non-alertable extended event waits through both Win64 wait APIs.
@@ -128,6 +130,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.
+87
View File
@@ -116,6 +116,93 @@ 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, and a stream from fopen is a file. A pointer
# that is no stream, reading stdin, and 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, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
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, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream
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 pointer that is no 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 pointer that is no stream
ref stdio.h setvbuf
test fflush_and_setvbuf_return_their_documented_results
# Files for a hosted C program, on the in-memory drive the handle services use.
service ucrtbase.dll fopen(name: ptr, mode: ptr) -> ptr
handler fopen
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM
ref stdio.h fopen
test a_file_written_through_a_stream_reads_back_line_by_line
service ucrtbase.dll fclose(stream: ptr) -> i32
handler fclose
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream
ref stdio.h fclose
test a_file_written_through_a_stream_reads_back_line_by_line
service ucrtbase.dll fgets(buffer: ptr, count: i32, stream: ptr) -> ptr
handler fgets
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream
ref stdio.h fgets
test fgets_reads_lines_within_its_count
service ucrtbase.dll perror(message: ptr) -> void
handler perror
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails never
ref stdio.h perror
test perror_writes_the_message_and_the_error_text_to_stderr
service kernel32.dll GetLastError() -> u32
handler get_last_error
status partial
+205 -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; 37] = [
pub static SERVICES: [ServiceMetadata; 47] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
@@ -141,6 +141,116 @@ 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, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
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, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream",
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 pointer that is no 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 pointer that is no stream",
reference: "stdio.h setvbuf",
tests: &["fflush_and_setvbuf_return_their_documented_results"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fopen",
parameters: &[Parameter { name: "name", kind: "ptr" }, Parameter { name: "mode", kind: "ptr" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM",
reference: "stdio.h fopen",
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fclose",
parameters: &[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 stream; stops the guest for a standard stream or a pointer that is no stream",
reference: "stdio.h fclose",
tests: &["a_file_written_through_a_stream_reads_back_line_by_line"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fgets",
parameters: &[Parameter { name: "buffer", kind: "ptr" }, Parameter { name: "count", kind: "i32" }, Parameter { name: "stream", kind: "ptr" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream",
reference: "stdio.h fgets",
tests: &["fgets_reads_lines_within_its_count"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "perror",
parameters: &[Parameter { name: "message", kind: "ptr" }],
result: "void",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "never",
reference: "stdio.h perror",
tests: &["perror_writes_the_message_and_the_error_text_to_stderr"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetLastError",
@@ -518,6 +628,100 @@ 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("ucrtbase.dll", "fopen", 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: u64 = handlers::fopen(&mut context, a0, a1)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fclose", 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::fclose(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fgets", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.i32(1)?;
let a2 = call.u64(2)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::fgets(&mut context, a0, a1, a2)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "perror", 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 () = handlers::perror(&mut context, a0)?;
Ok(0)
});
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 };
+149
View File
@@ -12,7 +12,10 @@
mod crt;
mod crt_arguments;
mod crt_callbacks;
mod crt_files;
mod crt_format;
mod crt_startup;
mod crt_streams;
mod events;
mod files;
mod gdk_queue;
@@ -28,6 +31,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};
@@ -199,6 +203,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`.
@@ -229,6 +234,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(),
@@ -342,6 +348,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
@@ -909,6 +932,132 @@ pub(crate) mod handlers {
.map_err(ExitReason::MemoryFault)
}
// Streams, files and formatted output (#400, #402). `crt_streams.rs` and
// `crt_files.rs` hold the rules; a failure that has an errno value sets it
// here. The stream state is always locked before the object state.
fn or_errno<T>(
context: &mut ServiceContext<'_>,
outcome: crt_streams::Outcome<T>,
) -> Outcome<T> {
match outcome? {
Ok(value) => Ok(value),
Err(crt_streams::Failed(value, errno)) => {
crt::set_errno(context.memory, context.teb, errno)?;
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 = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.print(
context.memory,
&mut drive,
options,
stream,
format,
locale,
arguments,
)
};
or_errno(context, outcome)
}
pub fn fwrite(
context: &mut ServiceContext<'_>,
buffer: u64,
size: u64,
count: u64,
stream: u64,
) -> Outcome<u64> {
let outcome = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.write_items(context.memory, &mut drive, buffer, size, count, stream)
};
or_errno(context, outcome)
}
pub fn fputs(context: &mut ServiceContext<'_>, text: u64, stream: u64) -> Outcome<i32> {
let outcome = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.put_string(context.memory, &mut drive, text, stream)
};
or_errno(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_errno(context, outcome)
}
pub fn fopen(context: &mut ServiceContext<'_>, name: u64, mode: u64) -> Outcome<u64> {
let outcome = {
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.open(context.memory, &mut drive, name, mode)
};
or_errno(context, outcome)
}
pub fn fclose(context: &mut ServiceContext<'_>, stream: u64) -> Outcome<i32> {
let outcome = context.state.crt_streams().close(context.memory, stream);
or_errno(context, outcome)
}
pub fn fgets(
context: &mut ServiceContext<'_>,
buffer: u64,
count: i32,
stream: u64,
) -> Outcome<u64> {
let outcome = {
let mut streams = context.state.crt_streams();
let drive = context.state.objects.lock().expect("guest object state");
streams.get_line(context.memory, &drive, buffer, count, stream)
};
or_errno(context, outcome)
}
pub fn perror(context: &mut ServiceContext<'_>, message: u64) -> Outcome<()> {
let address = context
.memory
.crt_errno_address(context.teb)
.map_err(ExitReason::MemoryFault)?;
let errno = context
.memory
.read_u32(address)
.map_err(ExitReason::MemoryFault)?;
let mut streams = context.state.crt_streams();
let mut drive = context.state.objects.lock().expect("guest object state");
streams.report(context.memory, &mut drive, message, errno)
}
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
Ok(context.state.last_error(context.teb))
}
+347
View File
@@ -0,0 +1,347 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The C runtime's file streams: what `fopen` opens.
//!
//! A stream reads and writes a file on the in-memory `C:` drive that the
//! handle services in `files.rs` also use, as the C runtime sits on Win32
//! files on Windows. The rules are from the Microsoft Learn pages "fopen,
//! _wfopen", "fclose, _fcloseall", "fgets, fgetws" and "perror, _wperror".
//!
//! Modes: `r`, `w` or `a`, then any of `+`, `b` and `t`. In text mode, which
//! is the default as `_fmode` starts as `_O_TEXT`, "LF characters are
//! translated to CR-LF combinations on output", "CR-LF combinations are
//! translated into single line feeds on input", and "CTRL+Z is interpreted as
//! an end-of-file character on input".
//!
//! Nothing is buffered: a write reaches the drive at once. There is no
//! seeking, so the only positions are the start, the end, and wherever the
//! last read or write left off.
use super::ObjectState;
use super::files::DriveEntry;
use crate::memory::{GuestMemory, PROCESS_HEAP};
use std::collections::BTreeMap;
/// errno.h values.
pub(super) const ENOENT: u32 = 2;
pub(super) const EBADF: u32 = 9;
pub(super) const ENOMEM: u32 = 12;
pub(super) const EACCES: u32 = 13;
pub(super) const EINVAL: u32 = 22;
pub(super) const EMFILE: u32 = 24;
pub(super) const ENOSPC: u32 = 28;
/// The most streams `fopen` keeps open at once.
pub(super) const MAX_OPEN_STREAMS: usize = 64;
/// `CTRL+Z`, which ends the input of a text-mode stream.
const CTRL_Z: u8 = 0x1A;
/// The text `perror` prints for an `errno` value. The page gives the text for
/// a missing file in its example; the others are the usual C library wording
/// and are Xenora's choice.
pub(super) fn error_text(errno: u32) -> &'static str {
match errno {
0 => "No error",
ENOENT => "No such file or directory",
EBADF => "Bad file descriptor",
ENOMEM => "Not enough space",
EACCES => "Permission denied",
EINVAL => "Invalid argument",
EMFILE => "Too many open files",
ENOSPC => "No space left on device",
_ => "Unknown error",
}
}
struct Mode {
readable: bool,
writable: bool,
/// Every write goes to the end of the file.
append: bool,
/// The file must already exist.
existing: bool,
/// The file's contents are destroyed on opening.
truncate: bool,
text: bool,
}
/// `r`, `w` or `a` first, then `+`, `b` and `t` in any order, each at most
/// once and not both `b` and `t`. Anything else is not a mode this runtime
/// opens, including the other characters the page lists.
fn parse_mode(mode: &[u8]) -> Option<Mode> {
let (&kind, rest) = mode.split_first()?;
let (mut update, mut binary, mut text) = (false, false, false);
for &byte in rest {
let seen = match byte {
b'+' => &mut update,
b'b' => &mut binary,
b't' => &mut text,
_ => return None,
};
if std::mem::replace(seen, true) {
return None;
}
}
if binary && text {
return None;
}
let (readable, writable, append, existing, truncate) = match kind {
b'r' => (true, update, false, true, false),
b'w' => (update, true, false, false, true),
b'a' => (update, true, true, false, false),
_ => return None,
};
Some(Mode {
readable,
writable,
append,
existing,
truncate,
text: !binary,
})
}
struct FileStream {
path: String,
/// Where the next read, or the next write of a stream that does not
/// append, takes place.
position: u64,
readable: bool,
writable: bool,
append: bool,
text: bool,
}
#[derive(Default)]
pub(super) struct FileStreams {
/// Open streams by the guest address of their `FILE` object.
open: BTreeMap<u64, FileStream>,
}
impl FileStreams {
pub(super) fn contains(&self, file: u64) -> bool {
self.open.contains_key(&file)
}
/// `fopen`. Returns the guest address of a new `FILE` object, or the
/// `errno` value of the failure.
pub(super) fn open(
&mut self,
memory: &mut GuestMemory,
drive: &mut ObjectState,
name: &[u8],
mode: &[u8],
) -> Result<u64, u32> {
// An empty name or mode is an invalid parameter: neither is a mode
// nor a name the drive accepts. Xenora's choice: so is any other mode
// it does not open and any other name the drive rejects.
let mode = parse_mode(mode).ok_or(EINVAL)?;
let path = ObjectState::drive_path(name).ok_or(EINVAL)?;
if self.open.len() >= MAX_OPEN_STREAMS {
return Err(EMFILE);
}
let create = match drive.drive_entry(&path) {
DriveEntry::Directory => return Err(EACCES),
DriveEntry::File => false,
DriveEntry::Missing { .. } if mode.existing => return Err(ENOENT),
DriveEntry::Missing { parent: false } => return Err(ENOENT),
DriveEntry::Missing { parent: true } => true,
};
// The FILE object is allocated before the drive is touched, so a
// failed fopen neither creates a file nor destroys the contents of
// one.
let file = memory
.map_heap_allocation(PROCESS_HEAP, 8)
.map_err(|_| ENOMEM)?;
if create && !drive.drive_create(&path) {
memory.release_heap_allocation(PROCESS_HEAP, file);
return Err(ENOSPC);
}
if mode.truncate {
drive.drive_truncate(&path);
}
self.open.insert(
file,
FileStream {
path,
position: 0,
readable: mode.readable,
writable: mode.writable,
append: mode.append,
text: mode.text,
},
);
Ok(file)
}
/// `fclose`. False when `file` is not an open stream.
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> bool {
if self.open.remove(&file).is_none() {
return false;
}
memory.release_heap_allocation(PROCESS_HEAP, file);
true
}
/// Write to an open stream, in its mode. Returns the `errno` value of a
/// failure, with nothing written.
pub(super) fn write(
&mut self,
drive: &mut ObjectState,
file: u64,
bytes: &[u8],
) -> Result<(), u32> {
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
if !stream.writable {
return Err(EBADF);
}
let stored: Vec<u8> = if stream.text {
let mut stored = Vec::with_capacity(bytes.len());
for &byte in bytes {
if byte == b'\n' {
stored.push(b'\r');
}
stored.push(byte);
}
stored
} else {
bytes.to_vec()
};
// "All write operations occur at the end of the file."
if stream.append {
stream.position = drive.drive_file(&stream.path).ok_or(EBADF)?.len() as u64;
}
match drive.drive_write(&stream.path, stream.position, &stored) {
Some(true) => {
stream.position += stored.len() as u64;
Ok(())
}
Some(false) => Err(ENOSPC),
// The file was deleted or moved while the stream was open.
None => Err(EBADF),
}
}
/// `fgets`: up to `limit` characters, ending after a newline. `None` is
/// end of file with nothing read.
pub(super) fn read_line(
&mut self,
drive: &ObjectState,
file: u64,
limit: usize,
) -> Result<Option<Vec<u8>>, u32> {
let stream = self.open.get_mut(&file).ok_or(EBADF)?;
if !stream.readable {
return Err(EBADF);
}
let data = drive.drive_file(&stream.path).ok_or(EBADF)?;
let mut at = usize::try_from(stream.position).map_or(data.len(), |at| at.min(data.len()));
let ended = at == data.len() || (stream.text && data[at] == CTRL_Z);
if limit == 0 {
// No room to read a character: an empty line unless the stream
// has ended.
return Ok((!ended).then(Vec::new));
}
let mut line = Vec::new();
while line.len() < limit && at < data.len() {
let mut byte = data[at];
if stream.text {
if byte == CTRL_Z {
break;
}
if byte == b'\r' && data.get(at + 1) == Some(&b'\n') {
at += 1;
byte = b'\n';
}
}
at += 1;
line.push(byte);
if byte == b'\n' {
break;
}
}
stream.position = at as u64;
Ok((!line.is_empty()).then_some(line))
}
}
#[cfg(test)]
mod tests {
use super::parse_mode;
/// The six access types of the `fopen` page, each alone and with `t` or
/// `b`, and what the page says of each.
#[test]
fn modes_follow_the_fopen_page() {
// (mode, readable, writable, append, must exist, truncates)
for (mode, readable, writable, append, existing, truncate) in [
("r", true, false, false, true, false),
("w", false, true, false, false, true),
("a", false, true, true, false, false),
("r+", true, true, false, true, false),
("w+", true, true, false, false, true),
("a+", true, true, true, false, false),
] {
for (suffix, text) in [("", true), ("t", true), ("b", false)] {
let mut spellings = vec![format!("{mode}{suffix}")];
if mode.len() == 2 && !suffix.is_empty() {
// "rb+" is the same mode as "r+b".
spellings.push(format!("{}{suffix}+", &mode[..1]));
}
for spelling in spellings {
let parsed = parse_mode(spelling.as_bytes())
.unwrap_or_else(|| panic!("{spelling} is a mode"));
assert_eq!(
(
parsed.readable,
parsed.writable,
parsed.append,
parsed.existing,
parsed.truncate,
parsed.text
),
(readable, writable, append, existing, truncate, text),
"{spelling}"
);
}
}
}
// "If t or b is prefixed to the argument, the function fails." The
// other mode characters the page lists are not opened here, and
// neither is anything that is not a mode.
for mode in [
"",
"t",
"b",
"tr",
"br",
"+r",
"x",
"rw",
"wr",
"ra",
"rbt",
"rtb",
"r++",
"rbb",
"wtt",
"wx",
"w+x",
"rc",
"rn",
"rN",
"rS",
"rR",
"wT",
"wD",
"r,ccs=UTF-8",
"R",
"W",
"r ",
" r",
"rb+t",
] {
assert!(parse_mode(mode.as_bytes()).is_none(), "{mode:?}");
}
}
}
+743
View File
@@ -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
)))
);
}
}
+412
View File
@@ -0,0 +1,412 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The 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.
//!
//! A stream that `fopen` returned is a file on the in-memory drive; its rules
//! are in `crt_files.rs`.
//!
//! Output is never held back: there is no buffering to flush or to configure.
//! A pointer that is no stream, reading `stdin` and closing a standard stream
//! are not modelled and stop the guest with the runtime-limit fault.
use super::ObjectState;
use super::crt_files::{self, EBADF, EINVAL, FileStreams};
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 longest file name or mode string `fopen` reads, in bytes.
const MAX_NAME: u64 = 260;
/// 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,
/// A stream `fopen` returned, by the address of its `FILE` object.
File(u64),
}
#[derive(Default)]
pub(super) struct StandardStreams {
/// Guest address of the three `FILE` objects, `stdin` first.
files: Option<u64>,
output: Vec<u8>,
error: Vec<u8>,
/// The streams `fopen` has open.
opened: FileStreams,
}
/// What a service returns when it fails with a result and an `errno` value:
/// the handler sets `errno` to the second field and returns the first.
pub(super) struct Failed<T>(pub T, pub u32);
pub(super) type Outcome<T> = Result<Result<T, Failed<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 stream a non-null `FILE*` is: a standard stream, or one `fopen`
/// returned. Any other pointer is no stream.
fn stream(&self, file: u64) -> Result<Stream, ExitReason> {
match self.files.map(|base| file.wrapping_sub(base)) {
Some(0) => Ok(Stream::Input),
Some(8) => Ok(Stream::Output),
Some(16) => Ok(Stream::Error),
_ if self.opened.contains(file) => Ok(Stream::File(file)),
_ => Err(RUNTIME_LIMIT),
}
}
/// A stream that may be written. Writing `stdin` is not modelled.
fn writable(&self, file: u64) -> Result<Stream, ExitReason> {
match self.stream(file)? {
Stream::Input => Err(RUNTIME_LIMIT),
stream => Ok(stream),
}
}
/// Write to a stream. A standard stream is captured in text mode: each
/// line feed becomes a carriage return and a line feed. A file stream can
/// fail, with the `errno` value in the inner result and nothing written.
fn write(
&mut self,
drive: &mut ObjectState,
stream: Stream,
bytes: &[u8],
) -> Result<Result<(), u32>, ExitReason> {
let captured = match stream {
Stream::Output => &mut self.output,
Stream::Error => &mut self.error,
Stream::Input => return Err(RUNTIME_LIMIT),
Stream::File(file) => return Ok(self.opened.write(drive, file, bytes)),
};
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(Ok(()))
}
/// `__stdio_common_vfprintf`. Returns the number of characters written,
/// before the text-mode replacement.
#[allow(clippy::too_many_arguments)]
pub(super) fn print(
&mut self,
memory: &GuestMemory,
drive: &mut ObjectState,
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(Failed(-1, EINVAL)));
}
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(Failed(-1, EINVAL))),
Err(FormatError::Unsupported | FormatError::TooLong) => return Err(RUNTIME_LIMIT),
Err(FormatError::Fault(error)) => return Err(fault(error)),
};
// "A negative value if an output error occurs."
Ok(match self.write(drive, stream, &text)? {
Ok(()) => Ok(text.len() as i32),
Err(errno) => Err(Failed(-1, errno)),
})
}
/// `fwrite`. Returns the number of whole items written.
pub(super) fn write_items(
&mut self,
memory: &GuestMemory,
drive: &mut ObjectState,
buffer: u64,
size: u64,
count: u64,
file: u64,
) -> Outcome<u64> {
if buffer == 0 || file == 0 {
return Ok(Err(Failed(0, EINVAL)));
}
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)?;
// Fewer items than `count` means an error. A failed write here
// writes none of them.
Ok(match self.write(drive, stream, &bytes)? {
Ok(()) => Ok(count),
Err(errno) => Err(Failed(0, errno)),
})
}
/// `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,
drive: &mut ObjectState,
text: u64,
file: u64,
) -> Outcome<i32> {
if text == 0 || file == 0 {
return Ok(Err(Failed(-1, EINVAL)));
}
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);
}
Ok(match self.write(drive, stream, &bytes)? {
Ok(()) => Ok(0),
Err(errno) => Err(Failed(-1, errno)),
})
}
/// `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(Failed(-1, EINVAL)));
}
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(Failed(-1, EINVAL))
})
}
/// `fopen`. Returns the new `FILE*`, or null with the `errno` value.
pub(super) fn open(
&mut self,
memory: &mut GuestMemory,
drive: &mut ObjectState,
name: u64,
mode: u64,
) -> Outcome<u64> {
// A null name or mode is an invalid parameter, as an empty one is.
if name == 0 || mode == 0 {
return Ok(Err(Failed(0, EINVAL)));
}
let name = c_string(memory, name, MAX_NAME + 1).map_err(fault)?;
let mode = c_string(memory, mode, MAX_NAME + 1).map_err(fault)?;
if name.len() as u64 > MAX_NAME || mode.len() as u64 > MAX_NAME {
return Ok(Err(Failed(0, EINVAL)));
}
Ok(self
.opened
.open(memory, drive, &name, &mode)
.map_err(|errno| Failed(0, errno)))
}
/// `fclose`. Returns 0, or `EOF` with `EINVAL` for a null stream. Closing
/// a standard stream is not modelled.
pub(super) fn close(&mut self, memory: &mut GuestMemory, file: u64) -> Outcome<i32> {
if file == 0 {
return Ok(Err(Failed(-1, EINVAL)));
}
match self.stream(file)? {
Stream::File(file) => {
self.opened.close(memory, file);
Ok(Ok(0))
}
_ => Err(RUNTIME_LIMIT),
}
}
/// `fgets`. Returns `buffer`, or null at end of file or on an error.
pub(super) fn get_line(
&mut self,
memory: &mut GuestMemory,
drive: &ObjectState,
buffer: u64,
count: i32,
file: u64,
) -> Outcome<u64> {
if buffer == 0 || file == 0 || count <= 0 {
return Ok(Err(Failed(0, EINVAL)));
}
let file = match self.stream(file)? {
Stream::File(file) => file,
// Reading the standard input is not modelled.
Stream::Input => return Err(RUNTIME_LIMIT),
// The output streams cannot be read.
Stream::Output | Stream::Error => return Ok(Err(Failed(0, EBADF))),
};
// Up to count - 1 characters, and then the terminator.
let limit = ((count - 1) as u64).min(MAX_TRANSFER) as usize;
let mut line = match self.opened.read_line(drive, file, limit) {
Ok(Some(line)) => line,
// End of file with nothing read: null, and the buffer is left
// alone.
Ok(None) => return Ok(Ok(0)),
Err(errno) => return Ok(Err(Failed(0, errno))),
};
line.push(0);
memory.write_bytes(buffer, &line).map_err(fault)?;
Ok(Ok(buffer))
}
/// `perror`: the message, a colon and a space when there is a message,
/// then the text for `errno` and a newline, to `stderr`.
pub(super) fn report(
&mut self,
memory: &GuestMemory,
drive: &mut ObjectState,
message: u64,
errno: u32,
) -> Result<(), ExitReason> {
let mut text = Vec::new();
if message != 0 {
text = c_string(memory, message, MAX_TRANSFER + 1).map_err(fault)?;
if text.len() as u64 > MAX_TRANSFER {
return Err(RUNTIME_LIMIT);
}
}
if !text.is_empty() {
text.extend_from_slice(b": ");
}
text.extend_from_slice(crt_files::error_text(errno).as_bytes());
text.push(b'\n');
self.write(drive, Stream::Error, &text).map(|_| ())
}
}
+86
View File
@@ -625,3 +625,89 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
}
}
/// What a path names on the drive, for the C runtime's file streams.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum DriveEntry {
File,
Directory,
/// Nothing has this name. `parent` says whether its directory exists.
Missing {
parent: bool,
},
}
/// The drive as the C runtime's file streams (`crt_files.rs`) use it. They read
/// and write the same files as the handle services above. A stream is not a
/// handle: it takes no part in sharing, and a file it has open can be deleted
/// or moved, after which its operations fail.
impl super::ObjectState {
/// A narrow file name as the drive stores it: ASCII, either slash, any
/// case, with or without `C:\`. `None` for a name the drive rejects.
pub(super) fn drive_path(name: &[u8]) -> Option<String> {
if !name.is_ascii() {
return None;
}
let path = String::from_utf8_lossy(name)
.replace('/', "\\")
.to_ascii_lowercase();
let path = path.strip_prefix("c:\\").unwrap_or(&path).to_owned();
path.split('\\').all(valid_component).then_some(path)
}
pub(super) fn drive_entry(&self, path: &str) -> DriveEntry {
if self.files.contains_key(path) {
DriveEntry::File
} else if self.directories.contains(path) {
DriveEntry::Directory
} else {
let parent = parent(path);
DriveEntry::Missing {
parent: parent.is_empty() || self.directories.contains(parent),
}
}
}
/// Create an empty file. False when the drive already holds as many files
/// as it can.
pub(super) fn drive_create(&mut self, path: &str) -> bool {
if self.files.len() >= MAX_FILES {
return false;
}
self.files.insert(path.to_owned(), Vec::new());
true
}
pub(super) fn drive_file(&self, path: &str) -> Option<&[u8]> {
self.files.get(path).map(Vec::as_slice)
}
/// Empty a file. False when it does not exist.
pub(super) fn drive_truncate(&mut self, path: &str) -> bool {
self.files.get_mut(path).map(Vec::clear).is_some()
}
/// Write `bytes` at `position`, growing the file as needed. `None` when
/// the file does not exist; `Some(false)`, with nothing written, when the
/// write would pass the drive's size bound.
pub(super) fn drive_write(&mut self, path: &str, position: u64, bytes: &[u8]) -> Option<bool> {
let used: usize = self.files.values().map(Vec::len).sum();
let data = self.files.get_mut(path)?;
let Some(end) = position
.checked_add(bytes.len() as u64)
.filter(|end| *end <= MAX_BYTES as u64)
else {
return Some(false);
};
let (start, end) = (position as usize, end as usize);
let growth = end.saturating_sub(data.len());
if growth > MAX_BYTES - used {
return Some(false);
}
if growth != 0 {
data.resize(end, 0);
}
data[start..end].copy_from_slice(bytes);
Some(true)
}
}
+263
View File
@@ -0,0 +1,263 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! C runtime file streams and the Win32 file services on one drive (issue
//! #402). On Windows the C runtime's streams sit on Win32 files, so a file
//! written through one is the file read through the other.
//!
//! In text mode a C stream writes each line feed as a carriage return and a
//! line feed and reads the pair back as a line feed (Microsoft Learn, "fopen,
//! _wfopen"). `ReadFile` and `WriteFile` transfer bytes as they are. Expected
//! bytes are what each test wrote, with that translation applied by hand.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
const KERNEL32: &str = "kernel32.dll";
const UCRT: &str = "ucrtbase.dll";
const IMPORTS: &[(&str, &str)] = &[
(KERNEL32, "CreateFileW"),
(KERNEL32, "ReadFile"),
(KERNEL32, "WriteFile"),
(KERNEL32, "CloseHandle"),
(KERNEL32, "CreateDirectoryW"),
(KERNEL32, "DeleteFileW"),
(UCRT, "fopen"),
(UCRT, "fclose"),
(UCRT, "fgets"),
(UCRT, "fputs"),
(UCRT, "_errno"),
(UCRT, "malloc"),
(UCRT, "free"),
];
const GENERIC_READ: u64 = 0x8000_0000;
const GENERIC_WRITE: u64 = 0x4000_0000;
const CREATE_ALWAYS: u64 = 2;
const OPEN_EXISTING: u64 = 3;
const INVALID_HANDLE: u64 = u64::MAX;
const ENOENT: u32 = 2;
const EBADF: u32 = 9;
const ENOMEM: u32 = 12;
const EACCES: u32 = 13;
// Scratch layout: a wide name, a narrow name, a mode, a transfer buffer and a
// count.
const WIDE: u64 = SCRATCH;
const NARROW: u64 = SCRATCH + 0x200;
const MODE: u64 = SCRATCH + 0x300;
const BUFFER: u64 = SCRATCH + 0x400;
const COUNT: u64 = SCRATCH + 0x800;
fn guest() -> Guest {
Guest::new(IMPORTS, &[])
}
fn narrow(guest: &mut Guest, at: u64, text: &str) -> u64 {
guest.memory.write_bytes(at, text.as_bytes()).unwrap();
guest.memory.write_u8(at + text.len() as u64, 0).unwrap();
at
}
fn wide(guest: &mut Guest, text: &str) -> u64 {
let units: Vec<u8> = text
.encode_utf16()
.chain([0])
.flat_map(u16::to_le_bytes)
.collect();
guest.memory.write_bytes(WIDE, &units).unwrap();
WIDE
}
fn errno(guest: &mut Guest) -> u32 {
let address = guest.call("_errno", &[]);
guest.u32_at(address)
}
fn fopen(guest: &mut Guest, name: &str, mode: &str) -> u64 {
let name = narrow(guest, NARROW, name);
let mode = narrow(guest, MODE, mode);
guest.call("fopen", &[name, mode])
}
/// `CreateFileW` with no sharing restriction on later opens.
fn create_file(guest: &mut Guest, name: &str, access: u64, disposition: u64) -> u64 {
let name = wide(guest, name);
guest.call("CreateFileW", &[name, access, 3, 0, disposition, 0, 0])
}
/// Everything `ReadFile` returns for a file, up to 256 bytes.
fn read_through_win32(guest: &mut Guest, name: &str) -> Vec<u8> {
let handle = create_file(guest, name, GENERIC_READ, OPEN_EXISTING);
assert_ne!(handle, INVALID_HANDLE, "{name}");
assert_eq!(guest.call("ReadFile", &[handle, BUFFER, 256, COUNT, 0]), 1);
let count = guest.u32_at(COUNT) as usize;
let mut bytes = vec![0; count];
guest.memory.read_bytes(BUFFER, &mut bytes).unwrap();
assert_eq!(guest.call("CloseHandle", &[handle]), 1);
bytes
}
fn write_through_win32(guest: &mut Guest, name: &str, bytes: &[u8]) {
let handle = create_file(guest, name, GENERIC_WRITE, CREATE_ALWAYS);
assert_ne!(handle, INVALID_HANDLE, "{name}");
guest.memory.write_bytes(BUFFER, bytes).unwrap();
let count = bytes.len() as u64;
assert_eq!(
guest.call("WriteFile", &[handle, BUFFER, count, COUNT, 0]),
1
);
assert_eq!(u64::from(guest.u32_at(COUNT)), count);
assert_eq!(guest.call("CloseHandle", &[handle]), 1);
}
fn put(guest: &mut Guest, stream: u64, text: &str) -> u32 {
let text = narrow(guest, BUFFER, text);
guest.call("fputs", &[text, stream]) as u32
}
/// One `fgets` of up to 127 characters.
fn get(guest: &mut Guest, stream: u64) -> Option<Vec<u8>> {
if guest.call("fgets", &[BUFFER, 128, stream]) == 0 {
return None;
}
let mut bytes = vec![0; 128];
guest.memory.read_bytes(BUFFER, &mut bytes).unwrap();
let end = bytes.iter().position(|byte| *byte == 0).unwrap();
bytes.truncate(end);
Some(bytes)
}
#[test]
fn a_file_written_through_a_c_stream_is_read_through_win32() {
let mut guest = guest();
// Text mode stores a carriage return before each line feed.
let stream = fopen(&mut guest, "from-c.txt", "w");
assert_ne!(stream, 0);
assert_eq!(put(&mut guest, stream, "line one\nline two\n"), 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert_eq!(
read_through_win32(&mut guest, "C:\\from-c.txt"),
b"line one\r\nline two\r\n"
);
// Binary mode stores what was written.
let stream = fopen(&mut guest, "from-c.bin", "wb");
assert_eq!(put(&mut guest, stream, "raw\nbytes"), 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert_eq!(read_through_win32(&mut guest, "from-c.bin"), b"raw\nbytes");
// Nothing is held back: the bytes are on the drive before fclose.
let stream = fopen(&mut guest, "unflushed.bin", "wb");
assert_eq!(put(&mut guest, stream, "now"), 0);
assert_eq!(read_through_win32(&mut guest, "unflushed.bin"), b"now");
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
}
#[test]
fn a_file_written_through_win32_is_read_through_a_c_stream() {
let mut guest = guest();
write_through_win32(&mut guest, "C:\\from-win32.txt", b"win32\r\ndata\nlast");
// Text mode reads the pair as one line feed and leaves a lone one alone.
let stream = fopen(&mut guest, "from-win32.txt", "r");
assert_ne!(stream, 0);
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"win32\n"[..]));
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"data\n"[..]));
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"last"[..]));
assert_eq!(get(&mut guest, stream), None);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
// Binary mode reads the bytes as they are.
let stream = fopen(&mut guest, "from-win32.txt", "rb");
assert_eq!(get(&mut guest, stream).as_deref(), Some(&b"win32\r\n"[..]));
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
// A file Win32 created is there for "r", and "w" destroys its contents
// for Win32 too.
let stream = fopen(&mut guest, "from-win32.txt", "w");
assert_ne!(stream, 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert!(read_through_win32(&mut guest, "from-win32.txt").is_empty());
}
#[test]
fn directories_are_not_files_and_hold_files() {
let mut guest = guest();
let name = wide(&mut guest, "C:\\folder");
assert_eq!(guest.call("CreateDirectoryW", &[name, 0]), 1);
// A directory cannot be opened as a stream, for reading or writing.
for mode in ["r", "w", "a", "r+"] {
assert_eq!(fopen(&mut guest, "folder", mode), 0, "{mode}");
assert_eq!(errno(&mut guest), EACCES, "{mode}");
}
// A file inside it can, by either slash.
let stream = fopen(&mut guest, "folder/inside.txt", "wb");
assert_ne!(stream, 0);
assert_eq!(put(&mut guest, stream, "in"), 0);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
assert_eq!(
read_through_win32(&mut guest, "c:\\FOLDER\\inside.txt"),
b"in"
);
// A directory that does not exist has no files.
assert_eq!(fopen(&mut guest, "nowhere\\inside.txt", "w"), 0);
assert_eq!(errno(&mut guest), ENOENT);
}
/// A C stream is not a Win32 handle: it does not stop the file being deleted.
/// Once the file is gone the stream's operations fail with `EBADF`, and
/// closing it still succeeds. This is Xenora's behaviour, not Windows's,
/// where the open stream would keep the file from being deleted.
#[test]
fn a_stream_whose_file_was_deleted_fails_cleanly() {
let mut guest = guest();
let stream = fopen(&mut guest, "gone.txt", "w+b");
assert_ne!(stream, 0);
assert_eq!(put(&mut guest, stream, "data\n"), 0);
let name = wide(&mut guest, "C:\\gone.txt");
assert_eq!(guest.call("DeleteFileW", &[name]), 1);
assert_eq!(put(&mut guest, stream, "more"), u32::MAX);
assert_eq!(errno(&mut guest), EBADF);
assert_eq!(get(&mut guest, stream), None);
assert_eq!(errno(&mut guest), EBADF);
assert_eq!(guest.call("fclose", &[stream]) as u32, 0);
// The closed stream is no stream any more.
let exit = guest.fails("fclose", &[stream]);
assert_eq!(exit, RUNTIME_LIMIT);
assert!(matches!(exit, ExitReason::IllegalInstruction(0xFE)));
// And the name is free again.
assert_eq!(fopen(&mut guest, "gone.txt", "r"), 0);
assert_eq!(errno(&mut guest), ENOENT);
}
/// A `FILE` object comes from the process heap. When the heap has no room for
/// one, `fopen` fails with `ENOMEM` and has neither created the file nor
/// destroyed the contents of an existing one. The heap holds 4,096 blocks.
#[test]
fn an_fopen_that_cannot_allocate_leaves_the_drive_alone() {
let mut guest = guest();
write_through_win32(&mut guest, "kept.txt", b"keep me");
// Fill the heap one byte at a time until it refuses.
let mut blocks = Vec::new();
loop {
let block = guest.call("malloc", &[1]);
if block == 0 {
break;
}
blocks.push(block);
assert!(blocks.len() <= 4096, "the heap never filled");
}
for (name, mode) in [
("new.txt", "w"),
("new.txt", "a"),
("kept.txt", "w"),
("kept.txt", "r"),
] {
assert_eq!(fopen(&mut guest, name, mode), 0, "{name} {mode}");
assert_eq!(errno(&mut guest), ENOMEM, "{name} {mode}");
}
// With room for one block again: the new file was never created, and the
// existing one still has its contents.
guest.call("free", &[blocks.pop().unwrap()]);
assert_eq!(fopen(&mut guest, "new.txt", "r"), 0);
assert_eq!(errno(&mut guest), ENOENT);
assert_eq!(read_through_win32(&mut guest, "kept.txt"), b"keep me");
}
+232
View File
@@ -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
File diff suppressed because it is too large. Load diff
+106
View File
@@ -343,6 +343,112 @@ 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, a pointer that is no stream, writing `stdin`,
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.
### Files through the C runtime
`fopen`, `fclose` and `fgets` give a hosted C program files, and the output
services above (`__stdio_common_vfprintf`, `fwrite`, `fputs`, `fflush`,
`setvbuf`) accept a stream `fopen` returned as well as `stdout` and `stderr`.
The files are the ones on the in-memory `C:` drive described under
"Synthetic guest files": a file written through a C stream is the file
`ReadFile` reads, and the reverse.
| Service | Behaviour |
| --- | --- |
| `fopen(name, mode)` | Opens a file and returns its `FILE*`, or null with `errno` set. `r` needs the file to exist; `w` creates it or destroys its contents; `a` creates it and makes every write go to its end; `+` adds the other direction; `b` or `t` selects binary or text |
| `fclose(stream)` | Closes the stream and returns 0; `EOF` with `EINVAL` for a null stream |
| `fgets(buffer, count, stream)` | Reads up to `count - 1` characters, stopping after a newline, which it keeps, and adds a terminator. Returns the buffer, or null at end of file or on an error |
| `perror(message)` | Writes the message, `: `, the text for `errno` and a newline to `stderr`; only the text when the message is null or empty |
A stream is in text mode unless its mode has `b`: a line feed is stored as a
carriage return and a line feed, the pair is read back as a line feed, and
`CTRL+Z` ends the input. Names are ASCII, with either slash, in any case,
with or without `C:\`, as the drive accepts them.
`errno` after a failed `fopen`: `EINVAL` for a null or empty name or mode, a
mode this runtime does not open, and a name the drive rejects; `ENOENT` when
the file or its directory does not exist; `EACCES` for a directory; `EMFILE`
when 64 streams are already open; `ENOSPC` when the drive holds its 256
files; `ENOMEM` when the `FILE` object cannot be allocated. Output to a
stream that was not opened for writing, and reading one not opened for
reading, fail with `EBADF`; output the drive has no room for fails with
`ENOSPC`. A failed write writes nothing.
What is not provided, and what is Xenora's choice:
- **Not provided:** the mode characters `x`, `c`, `n`, `N`, `S`, `R`, `T`,
`D` and `ccs=`, which are refused; `fread`, `fseek`, `ftell`, `rewind`,
`feof`, `ferror`, `fscanf`; reading `stdin` and closing a standard stream,
which stop the guest.
- **No buffering.** A write reaches the drive at once, so the rule that a
`+` stream needs `fflush` or a seek between writing and reading does not
apply.
- **No sharing.** A C stream is not a Win32 handle. It does not stop
`DeleteFileW` or `MoveFileW`, and ignores a handle's sharing mode. After
its file is deleted a stream's reads and writes fail with `EBADF`.
- **Choices:** the `errno` values above other than `EINVAL` for a null or
empty argument, which is documented; an `a+` stream reads from the start;
every `perror` text except "No such file or directory", which is the one
Microsoft's page shows.
All four 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
+16 -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 | 37 |
| Generated adapters | 37 |
| Unique handler implementations | 37 |
| Services with a declared ABI | 47 |
| Generated adapters | 47 |
| Unique handler implementations | 47 |
| Implemented | 7 |
| Partial | 27 |
| Partial | 37 |
| Stub | 3 |
| Conformance-tested through guest dispatch | 37 |
| API-set aliases (not services) | 37 |
| Conformance-tested through guest dispatch | 47 |
| API-set aliases (not services) | 47 |
| Independently accepted | 0 |
| Service | Signature | Status | Failure |
@@ -30,6 +30,16 @@ 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, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream |
| `ucrtbase.dll!fputs` | `(text: ptr, stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null string or stream, or EBADF or ENOSPC for a file; stops the guest for stdin or a pointer that is no stream |
| `ucrtbase.dll!fflush` | `(stream: ptr) -> i32` | partial | stops the guest for a pointer that is no 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 pointer that is no stream |
| `ucrtbase.dll!fopen` | `(name: ptr, mode: ptr) -> ptr` | partial | null with errno EINVAL, ENOENT, EACCES, EMFILE, ENOSPC or ENOMEM |
| `ucrtbase.dll!fclose` | `(stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null stream; stops the guest for a standard stream or a pointer that is no stream |
| `ucrtbase.dll!fgets` | `(buffer: ptr, count: i32, stream: ptr) -> ptr` | partial | null at end of file; null with errno EINVAL or EBADF; stops the guest for stdin or a pointer that is no stream |
| `ucrtbase.dll!perror` | `(message: ptr) -> void` | partial | never |
| `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 |