Merge pull request #282 from MacosPorters/archive/pull/418/head

loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
This commit is contained in:
atharvranjan authored and GitHub committed 2026-11-24 22:11:50 -06:00
commit b6ebaaad5e
11 files changed
+1678 -81

No files matched your search

+2
View File
@@ -133,6 +133,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.
+41 -6
View File
@@ -117,8 +117,9 @@ service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
test system_time_comes_from_the_injected_clock
# Standard streams and formatted output for a hosted C program. Output to
# stdout and stderr is captured; any other stream, input, floating-point and
# wide conversions stop the guest with the runtime-limit fault.
# 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
@@ -140,7 +141,7 @@ service ucrtbase.dll fwrite(buffer: ptr, size: u64, count: u64, stream: ptr) ->
handler fwrite
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr
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
@@ -148,7 +149,7 @@ service ucrtbase.dll fputs(text: ptr, stream: ptr) -> i32
handler fputs
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr
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
@@ -156,7 +157,7 @@ service ucrtbase.dll fflush(stream: ptr) -> i32
handler fflush
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails stops the guest for a stream that is not a standard stream
fails stops the guest for a pointer that is no stream
ref stdio.h fflush
test fflush_and_setvbuf_return_their_documented_results
@@ -164,10 +165,44 @@ service ucrtbase.dll setvbuf(stream: ptr, buffer: ptr, mode: i32, size: u64) ->
handler setvbuf
status partial
alias api-ms-win-crt-stdio-l1-1-0.dll
fails -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream
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
+84 -5
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; 43] = [
pub static SERVICES: [ServiceMetadata; 47] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
@@ -170,7 +170,7 @@ pub static SERVICES: [ServiceMetadata; 43] = [
result: "u64",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr",
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"],
},
@@ -181,7 +181,7 @@ pub static SERVICES: [ServiceMetadata; 43] = [
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr",
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"],
},
@@ -192,7 +192,7 @@ pub static SERVICES: [ServiceMetadata; 43] = [
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "stops the guest for a stream that is not a standard stream",
failure: "stops the guest for a pointer that is no stream",
reference: "stdio.h fflush",
tests: &["fflush_and_setvbuf_return_their_documented_results"],
},
@@ -203,10 +203,54 @@ pub static SERVICES: [ServiceMetadata; 43] = [
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"],
failure: "-1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream",
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",
@@ -643,6 +687,41 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
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 };
+76 -26
View File
@@ -12,6 +12,7 @@
mod crt;
mod crt_arguments;
mod crt_callbacks;
mod crt_files;
mod crt_format;
mod crt_startup;
mod crt_streams;
@@ -937,17 +938,18 @@ pub(crate) mod handlers {
.map_err(ExitReason::MemoryFault)
}
// Standard streams and formatted output (#400). `crt_streams.rs` holds
// the rules; a documented failure sets errno to EINVAL here.
// 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_einval<T>(
fn or_errno<T>(
context: &mut ServiceContext<'_>,
outcome: crt_streams::Outcome<T>,
) -> Outcome<T> {
match outcome? {
Ok(value) => Ok(value),
Err(crt_streams::Invalid(value)) => {
crt::set_errno(context.memory, context.teb, crt::EINVAL)?;
Err(crt_streams::Failed(value, errno)) => {
crt::set_errno(context.memory, context.teb, errno)?;
Ok(value)
}
}
@@ -965,15 +967,20 @@ pub(crate) mod handlers {
locale: u64,
arguments: u64,
) -> Outcome<i32> {
let outcome = context.state.crt_streams().print(
context.memory,
options,
stream,
format,
locale,
arguments,
);
or_einval(context, outcome)
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(
@@ -983,20 +990,21 @@ pub(crate) mod handlers {
count: u64,
stream: u64,
) -> Outcome<u64> {
let outcome =
context
.state
.crt_streams()
.write_items(context.memory, buffer, size, count, stream);
or_einval(context, outcome)
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 = context
.state
.crt_streams()
.put_string(context.memory, text, stream);
or_einval(context, outcome)
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> {
@@ -1011,7 +1019,49 @@ pub(crate) mod handlers {
size: u64,
) -> Outcome<i32> {
let outcome = context.state.crt_streams().set_buffer(stream, mode, size);
or_einval(context, outcome)
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> {
+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:?}");
}
}
}
+161 -31
View File
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The standard streams of a hosted C program, and where their output goes.
//! 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
@@ -12,10 +12,15 @@
//! 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.
//! Any other stream, and input, are not modelled, and using one stops the
//! guest with the runtime-limit fault.
//! 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};
@@ -26,6 +31,8 @@ const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
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;
@@ -45,6 +52,8 @@ enum Stream {
Input,
Output,
Error,
/// A stream `fopen` returned, by the address of its `FILE` object.
File(u64),
}
#[derive(Default)]
@@ -53,13 +62,15 @@ pub(super) struct StandardStreams {
files: Option<u64>,
output: Vec<u8>,
error: Vec<u8>,
/// The streams `fopen` has open.
opened: FileStreams,
}
/// What a service returns when its documentation gives a failure result and
/// an `errno` value: the handler sets `errno` to `EINVAL` and returns this.
pub(super) struct Invalid<T>(pub T);
/// 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, Invalid<T>>, ExitReason>;
pub(super) type Outcome<T> = Result<Result<T, Failed<T>>, ExitReason>;
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
@@ -125,19 +136,19 @@ impl StandardStreams {
Ok(base + FILE_BYTES * u64::from(index))
}
/// Which standard stream a non-null `FILE*` is. Any other pointer is a
/// stream this runtime does not have.
/// 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> {
let base = self.files.ok_or(RUNTIME_LIMIT)?;
match file.wrapping_sub(base) {
0 => Ok(Stream::Input),
8 => Ok(Stream::Output),
16 => Ok(Stream::Error),
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 can be written: `stdout` or `stderr`.
/// 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),
@@ -145,13 +156,20 @@ impl StandardStreams {
}
}
/// Append to a captured stream, in text mode: each line feed becomes a
/// carriage return and a line feed.
fn write(&mut self, stream: Stream, bytes: &[u8]) -> Result<(), ExitReason> {
/// 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() {
@@ -163,14 +181,16 @@ impl StandardStreams {
}
captured.push(byte);
}
Ok(())
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,
@@ -179,7 +199,7 @@ impl StandardStreams {
) -> Outcome<i32> {
// A null stream or format: the function returns -1 and sets errno.
if file == 0 || format == 0 {
return Ok(Err(Invalid(-1)));
return Ok(Err(Failed(-1, EINVAL)));
}
if options & !IGNORED_OPTIONS != 0 || locale != 0 {
return Err(RUNTIME_LIMIT);
@@ -198,25 +218,29 @@ impl StandardStreams {
// Windows calls the invalid parameter handler for an invalid
// format. Xenora's choice for when execution continues: nothing
// is written and the result is that of a null format.
Err(FormatError::Invalid) => return Ok(Err(Invalid(-1))),
Err(FormatError::Invalid) => return Ok(Err(Failed(-1, EINVAL))),
Err(FormatError::Unsupported | FormatError::TooLong) => return Err(RUNTIME_LIMIT),
Err(FormatError::Fault(error)) => return Err(fault(error)),
};
self.write(stream, &text)?;
Ok(Ok(text.len() as i32))
// "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(Invalid(0)));
return Ok(Err(Failed(0, EINVAL)));
}
let stream = self.writable(file)?;
let Some(length) = size
@@ -230,8 +254,12 @@ impl StandardStreams {
}
let mut bytes = vec![0; length as usize];
memory.read_bytes(buffer, &mut bytes).map_err(fault)?;
self.write(stream, &bytes)?;
Ok(Ok(count))
// 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
@@ -239,19 +267,22 @@ impl StandardStreams {
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(Invalid(-1)));
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);
}
self.write(stream, &bytes)?;
Ok(Ok(0))
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
@@ -267,7 +298,7 @@ impl StandardStreams {
/// no effect.
pub(super) fn set_buffer(&self, file: u64, mode: i32, size: u64) -> Outcome<i32> {
if file == 0 {
return Ok(Err(Invalid(-1)));
return Ok(Err(Failed(-1, EINVAL)));
}
self.stream(file)?;
let valid = match mode {
@@ -277,6 +308,105 @@ impl StandardStreams {
IOFBF | IOLBF => (2..=i32::MAX as u64).contains(&size),
_ => false,
};
Ok(if valid { Ok(0) } else { Err(Invalid(-1)) })
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");
}
+551
View File
@@ -1031,6 +1031,557 @@ fn captured_output_is_bounded() {
assert_eq!(guest.state.standard_error(), b"xx");
}
const ENOENT: u32 = 2;
const EBADF: u32 = 9;
const EMFILE: u32 = 24;
const ENOSPC: u32 = 28;
/// Where the file tests put a name, a mode and the buffer `fgets` fills.
const NAME: u64 = TEXT + 0x1000;
const MODE: u64 = TEXT + 0x1200;
const LINE: u64 = TEXT + 0x2000;
/// What the buffer holds before `fgets` is called.
const UNTOUCHED: u8 = 0xEE;
/// `fopen(name, mode)`, with both strings placed in guest memory.
fn open(guest: &mut Guest, name: &str, mode: &str) -> u64 {
let name = place(guest, NAME, name.as_bytes());
let mode = place(guest, MODE, mode.as_bytes());
guest.call("fopen", &[name, mode])
}
/// `fopen` that must succeed.
fn opened(guest: &mut Guest, name: &str, mode: &str) -> u64 {
let stream = open(guest, name, mode);
assert_ne!(stream, 0, "fopen({name:?}, {mode:?})");
stream
}
fn close(guest: &mut Guest, stream: u64) {
assert_eq!(guest.call("fclose", &[stream]) & 0xFFFF_FFFF, 0);
}
/// Write `text` to a stream with `fwrite`, one item per byte.
fn write(guest: &mut Guest, stream: u64, text: &[u8]) {
guest.memory.write_bytes(TEXT + 0x4000, text).unwrap();
let count = text.len() as u64;
assert_eq!(
guest.call("fwrite", &[TEXT + 0x4000, 1, count, stream]),
count
);
}
/// Create or replace a file with exactly these bytes.
fn store(guest: &mut Guest, name: &str, bytes: &[u8]) {
let stream = opened(guest, name, "wb");
write(guest, stream, bytes);
close(guest, stream);
}
/// `fgets(LINE, count, stream)`: the string it stored, or `None` for a null
/// result. Either way, the bytes it had no reason to write must be untouched.
fn line(guest: &mut Guest, stream: u64, count: u64) -> Option<Vec<u8>> {
let room = (count as usize).min(0x400) + 16;
guest
.memory
.write_bytes(LINE, &vec![UNTOUCHED; room])
.unwrap();
let result = guest.call("fgets", &[LINE, count, stream]);
let mut after = vec![0; room];
guest.memory.read_bytes(LINE, &mut after).unwrap();
if result == 0 {
assert!(
after.iter().all(|byte| *byte == UNTOUCHED),
"buffer written"
);
return None;
}
assert_eq!(result, LINE, "fgets returns its buffer");
let end = after
.iter()
.position(|byte| *byte == 0)
.expect("terminator");
assert!(end < count as usize, "more than count - 1 characters");
assert!(after[end + 1..].iter().all(|byte| *byte == UNTOUCHED));
Some(after[..end].to_vec())
}
/// Every line of a file, read with `fgets` in the given mode.
fn lines(guest: &mut Guest, name: &str, mode: &str) -> Vec<Vec<u8>> {
let stream = opened(guest, name, mode);
let mut all = Vec::new();
while let Some(text) = line(guest, stream, 96) {
all.push(text);
// A read that does not advance must fail, not loop for ever.
assert!(all.len() <= 64, "{name}: fgets never reaches the end");
}
close(guest, stream);
all
}
/// What the Gate A2 program does with a file: `fopen` for writing, `fprintf`,
/// `fclose`, `fopen` for reading, `fgets`, `fclose`. `fgets` reads "to and
/// including the first newline character, to the end of the stream, or until
/// the number of characters read is equal to numChars - 1", and returns null
/// at end of file (Microsoft Learn). Expected text is what the test wrote.
#[test]
fn a_file_written_through_a_stream_reads_back_line_by_line() {
let (mut guest, streams) = stdio_guest();
let file = opened(&mut guest, "gate-a2.txt", "w");
assert!(!streams.contains(&file));
let one = place(&mut guest, STRINGS, b"one");
let first: &[u8] = b"sum 12345 hex a2 text one\n";
let count = print(
&mut guest,
file,
b"sum %llu hex %x text %s\n",
&[12345, 0xa2, one],
);
assert_eq!(count, first.len() as u64);
let second = place(&mut guest, STRINGS + 0x40, b"second line\n");
assert_eq!(guest.call("fputs", &[second, file]) & 0xFFFF_FFFF, 0);
write(&mut guest, file, b"third");
assert_eq!(guest.call("fflush", &[file]) & 0xFFFF_FFFF, 0);
close(&mut guest, file);
// File output is not standard output.
assert!(guest.state.standard_output().is_empty());
assert!(guest.state.standard_error().is_empty());
let file = opened(&mut guest, "gate-a2.txt", "r");
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(first));
assert_eq!(
line(&mut guest, file, 96).as_deref(),
Some(&b"second line\n"[..])
);
// The last line has no newline: it ends at the end of the stream.
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(&b"third"[..]));
assert_eq!(line(&mut guest, file, 96), None);
assert_eq!(line(&mut guest, file, 96), None);
close(&mut guest, file);
assert_eq!(guest.errno(), 0);
}
/// The access types of the `fopen` page: "r" fails "if the file doesn't
/// exist"; with "w", "if the given file exists, its contents are destroyed";
/// "a" "creates the file if it doesn't exist" and "all write operations occur
/// at the end of the file"; "r+" needs the file to exist; "w+" and "a+" also
/// read. A null or empty name or mode returns null with `EINVAL`.
#[test]
fn fopen_modes_follow_the_documentation() {
let (mut guest, _) = stdio_guest();
guest.set_errno(0);
for mode in ["r", "r+", "rb", "rt"] {
assert_eq!(open(&mut guest, "missing.txt", mode), 0, "{mode}");
assert_eq!(guest.errno(), ENOENT, "{mode}");
guest.set_errno(0);
}
// "w" creates the file, and opening it again destroys what it held.
store(&mut guest, "w.txt", b"old contents\n");
assert_eq!(lines(&mut guest, "w.txt", "rb"), [b"old contents\n"]);
let file = opened(&mut guest, "w.txt", "w");
close(&mut guest, file);
assert!(lines(&mut guest, "w.txt", "rb").is_empty());
// "a" creates the file, keeps what it holds and writes at its end.
for text in [&b"1\n"[..], b"2\n"] {
let file = opened(&mut guest, "a.txt", "ab");
write(&mut guest, file, text);
close(&mut guest, file);
}
assert_eq!(lines(&mut guest, "a.txt", "rb"), [b"1\n", b"2\n"]);
// "r+" keeps the contents and writes from the start.
store(&mut guest, "plus.txt", b"abcdef\n");
let file = opened(&mut guest, "plus.txt", "r+b");
write(&mut guest, file, b"XY");
// Reading continues where the write left off.
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(&b"cdef\n"[..]));
close(&mut guest, file);
assert_eq!(lines(&mut guest, "plus.txt", "rb"), [b"XYcdef\n"]);
// "w+" may be read; right after a write it is at the end of the file. A
// "w" stream may not be read at all.
let file = opened(&mut guest, "wplus.txt", "w+b");
write(&mut guest, file, b"data\n");
assert_eq!(line(&mut guest, file, 96), None);
assert_eq!(guest.errno(), 0);
close(&mut guest, file);
let file = opened(&mut guest, "wplus.txt", "w");
assert_eq!(line(&mut guest, file, 96), None);
assert_eq!(guest.errno(), EBADF);
guest.set_errno(0);
close(&mut guest, file);
// "a+" reads from the start (Xenora's choice; ISO C leaves the initial
// position to the implementation) and still writes at the end.
store(&mut guest, "aplus.txt", b"one\ntwo\n");
let file = opened(&mut guest, "aplus.txt", "a+b");
assert_eq!(line(&mut guest, file, 96).as_deref(), Some(&b"one\n"[..]));
write(&mut guest, file, b"three\n");
close(&mut guest, file);
assert_eq!(
lines(&mut guest, "aplus.txt", "rb"),
[&b"one\n"[..], b"two\n", b"three\n"]
);
// One file by any spelling the drive accepts: either slash, any case,
// with or without the drive.
store(&mut guest, "Name.TXT", b"same\n");
for name in ["name.txt", "NAME.txt", "C:\\name.txt", "c:/Name.Txt"] {
assert_eq!(lines(&mut guest, name, "r"), [b"same\n"], "{name}");
}
// Null and empty names and modes, modes that are not modes, a name the
// drive rejects, and a name that is too long.
guest.set_errno(0);
let name = place(&mut guest, NAME, b"w.txt");
let mode = place(&mut guest, MODE, b"r");
for args in [[0, mode], [name, 0]] {
assert_eq!(guest.call("fopen", &args), 0, "{args:x?}");
assert_eq!(guest.errno(), STDIO_EINVAL, "{args:x?}");
guest.set_errno(0);
}
let long = "x".repeat(261);
for (name, mode) in [
("", "r"),
("w.txt", ""),
("w.txt", "tr"),
("w.txt", "br"),
("w.txt", "rw"),
("w.txt", "rbt"),
("w.txt", "r++"),
("w.txt", "wx"),
("w.txt", "r,ccs=UTF-8"),
("w.txt", "R"),
("bad*name", "w"),
("a\\..\\b", "w"),
("con", "w"),
(long.as_str(), "w"),
] {
assert_eq!(open(&mut guest, name, mode), 0, "{name:?} {mode:?}");
assert_eq!(guest.errno(), STDIO_EINVAL, "{name:?} {mode:?}");
guest.set_errno(0);
}
// A refused "w" destroyed nothing.
assert_eq!(lines(&mut guest, "plus.txt", "rb"), [b"XYcdef\n"]);
// A directory that does not exist.
for mode in ["w", "a", "r"] {
assert_eq!(open(&mut guest, "nodir\\file.txt", mode), 0, "{mode}");
assert_eq!(guest.errno(), ENOENT, "{mode}");
guest.set_errno(0);
}
}
/// "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" in text mode; binary
/// mode suppresses the translations. Without `t` or `b` the mode is text,
/// the initial `_fmode` (Microsoft Learn, fopen).
#[test]
fn text_and_binary_streams_translate_as_documented() {
let (mut guest, _) = stdio_guest();
for mode in ["w", "wt"] {
let file = opened(&mut guest, "text.txt", mode);
write(&mut guest, file, b"a\nb\n");
// fwrite's result did not count the carriage returns.
close(&mut guest, file);
// Read back untranslated, the file holds CR-LF pairs.
assert_eq!(
lines(&mut guest, "text.txt", "rb"),
[b"a\r\n", b"b\r\n"],
"{mode}"
);
for read in ["r", "rt"] {
assert_eq!(lines(&mut guest, "text.txt", read), [b"a\n", b"b\n"]);
}
}
// Formatted output and fputs are translated like fwrite.
let file = opened(&mut guest, "text.txt", "w");
assert_eq!(print(&mut guest, file, b"%d\n", &[7]), 2);
let text = place(&mut guest, STRINGS, b"s\n");
assert_eq!(guest.call("fputs", &[text, file]) & 0xFFFF_FFFF, 0);
close(&mut guest, file);
assert_eq!(lines(&mut guest, "text.txt", "rb"), [b"7\r\n", b"s\r\n"]);
// Binary output is stored as written.
store(&mut guest, "binary.bin", b"x\ny");
assert_eq!(lines(&mut guest, "binary.bin", "rb"), [&b"x\n"[..], b"y"]);
// CTRL+Z ends a text stream and is data to a binary one. A carriage
// return that no line feed follows is kept.
store(&mut guest, "ctrlz.bin", b"one\r\ntw\ro\x1Athree\n");
assert_eq!(
lines(&mut guest, "ctrlz.bin", "r"),
[&b"one\n"[..], b"tw\ro"]
);
assert_eq!(
lines(&mut guest, "ctrlz.bin", "rb"),
[&b"one\r\n"[..], b"tw\ro\x1Athree\n"]
);
// A text stream that begins with CTRL+Z has nothing to read.
store(&mut guest, "empty.bin", b"\x1Arest");
assert!(lines(&mut guest, "empty.bin", "r").is_empty());
}
/// `fgets` stores at most `numChars - 1` characters and a terminator, and
/// "if str or stream is a null pointer, or numChars is less than or equal to
/// zero", sets `errno` to `EINVAL` and returns null (Microsoft Learn).
#[test]
fn fgets_reads_lines_within_its_count() {
let (mut guest, [input, out, _]) = stdio_guest();
store(&mut guest, "lines.bin", b"abcdefgh\nxy");
let file = opened(&mut guest, "lines.bin", "rb");
assert_eq!(line(&mut guest, file, 4).as_deref(), Some(&b"abc"[..]));
assert_eq!(line(&mut guest, file, 4).as_deref(), Some(&b"def"[..]));
assert_eq!(line(&mut guest, file, 2).as_deref(), Some(&b"g"[..]));
// A count of 1 has room for the terminator only and reads nothing.
assert_eq!(line(&mut guest, file, 1).as_deref(), Some(&b""[..]));
// The newline is kept, and reading stops after it. The count is an int.
let count = 0xFFFF_FFFF_0000_0060;
assert_eq!(
line(&mut guest, file, count & 0xFFFF_FFFF).as_deref(),
Some(&b"h\n"[..])
);
guest.memory.write_bytes(LINE, &[UNTOUCHED; 8]).unwrap();
assert_eq!(guest.call("fgets", &[LINE, count, file]), LINE);
assert_eq!(
guest.memory.read_u32(LINE).unwrap(),
u32::from_le_bytes(*b"xy\0\xEE")
);
// At the end of the file every count returns null.
for count in [96, 2, 1] {
assert_eq!(line(&mut guest, file, count), None, "{count}");
}
assert_eq!(guest.errno(), 0);
guest.set_errno(0);
for args in [
[0, 96, file],
[LINE, 96, 0],
[LINE, 0, file],
[LINE, 0xFFFF_FFFF, file],
[LINE, 0x8000_0000, file],
] {
assert_eq!(guest.call("fgets", &args), 0, "{args:x?}");
assert_eq!(guest.errno(), STDIO_EINVAL, "{args:x?}");
guest.set_errno(0);
}
close(&mut guest, file);
// A stream that was not opened for reading, and standard output.
let writer = opened(&mut guest, "lines.bin", "ab");
for stream in [writer, out] {
assert_eq!(guest.call("fgets", &[LINE, 96, stream]), 0);
assert_eq!(guest.errno(), EBADF);
guest.set_errno(0);
}
close(&mut guest, writer);
// Standard input, a closed stream and a pointer that never was one.
for stream in [input, writer, TEXT] {
assert_eq!(
guest.run("fgets", &[LINE, 96, stream]).1,
LIMIT,
"{stream:#x}"
);
}
// A buffer that cannot be written is a fault.
let file = opened(&mut guest, "lines.bin", "rb");
let exit = guest.run("fgets", &[0x9_0000_0000, 96, file]).1;
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
}
/// Output to a stream that was opened only for reading fails with the error
/// result of each function, and so does output the drive has no room for.
/// The `errno` values are Xenora's choice: `EBADF` and `ENOSPC`.
#[test]
fn file_output_that_cannot_be_written_fails_and_writes_nothing() {
let (mut guest, _) = stdio_guest();
store(&mut guest, "fixed.bin", b"keep\n");
let file = opened(&mut guest, "fixed.bin", "rb");
guest.set_errno(0);
let (count, exit) = print_with(&mut guest, MINGW_OPTIONS, file, b"%d", &[1]);
assert_eq!((count, exit), (STDIO_MINUS_ONE, ExitReason::Halt));
assert_eq!(guest.errno(), EBADF);
guest.set_errno(0);
let text = place(&mut guest, STRINGS, b"text");
assert_eq!(guest.call("fwrite", &[text, 1, 4, file]), 0);
assert_eq!(guest.errno(), EBADF);
guest.set_errno(0);
assert_eq!(
guest.call("fputs", &[text, file]) & 0xFFFF_FFFF,
STDIO_MINUS_ONE
);
assert_eq!(guest.errno(), EBADF);
guest.set_errno(0);
close(&mut guest, file);
assert_eq!(lines(&mut guest, "fixed.bin", "rb"), [b"keep\n"]);
// The drive holds 16 MiB in all. Fifteen whole megabytes and most of the
// sixteenth fit beside the five bytes above.
const CHUNK: u64 = 1 << 20;
guest
.memory
.write_bytes(TEXT, &vec![b'x'; CHUNK as usize])
.unwrap();
let file = opened(&mut guest, "big.bin", "wb");
for _ in 0..15 {
assert_eq!(guest.call("fwrite", &[TEXT, 1, CHUNK, file]), CHUNK);
}
assert_eq!(guest.call("fwrite", &[TEXT, 1, CHUNK - 5, file]), CHUNK - 5);
assert_eq!(guest.errno(), 0);
// Not one more byte, through any of the three.
assert_eq!(guest.call("fwrite", &[TEXT, 1, 1, file]), 0);
assert_eq!(guest.errno(), ENOSPC);
guest.set_errno(0);
let (count, _) = print_with(&mut guest, MINGW_OPTIONS, file, b"y", &[]);
assert_eq!(count, STDIO_MINUS_ONE);
assert_eq!(guest.errno(), ENOSPC);
guest.set_errno(0);
close(&mut guest, file);
// Emptying the big file makes room again.
let file = opened(&mut guest, "big.bin", "wb");
assert_eq!(guest.call("fwrite", &[TEXT, 1, 1, file]), 1);
close(&mut guest, file);
}
/// `fclose` "returns 0 if the stream is successfully closed" and, for a null
/// stream, sets `errno` to `EINVAL` and returns `EOF` (Microsoft Learn). At
/// most 64 streams are open at once (Xenora's bound), and the 65th `fopen`
/// fails with `EMFILE`.
#[test]
fn open_streams_are_bounded_and_fclose_releases_them() {
let (mut guest, [input, out, err]) = stdio_guest();
store(&mut guest, "shared.bin", b"x\n");
let mut open_streams: Vec<u64> = (0..64)
.map(|_| opened(&mut guest, "shared.bin", "rb"))
.collect();
let mut distinct = open_streams.clone();
distinct.sort_unstable();
distinct.dedup();
assert_eq!(distinct.len(), 64, "each stream has its own FILE object");
guest.set_errno(0);
for mode in ["rb", "wb", "ab"] {
assert_eq!(open(&mut guest, "shared.bin", mode), 0, "{mode}");
assert_eq!(guest.errno(), EMFILE, "{mode}");
guest.set_errno(0);
}
// The refused "wb" destroyed nothing, and each stream has its own
// position.
assert_eq!(
line(&mut guest, open_streams[0], 96).as_deref(),
Some(&b"x\n"[..])
);
assert_eq!(line(&mut guest, open_streams[0], 96), None);
assert_eq!(
line(&mut guest, open_streams[1], 96).as_deref(),
Some(&b"x\n"[..])
);
// Closing one makes room for one.
let last = open_streams.pop().unwrap();
close(&mut guest, last);
let again = opened(&mut guest, "shared.bin", "rb");
assert_eq!(open(&mut guest, "shared.bin", "rb"), 0);
assert_eq!(guest.errno(), EMFILE);
guest.set_errno(0);
// fflush and setvbuf accept an open file stream.
assert_eq!(guest.call("fflush", &[again]) & 0xFFFF_FFFF, 0);
assert_eq!(guest.call("setvbuf", &[again, 0, 4, 0]) & 0xFFFF_FFFF, 0);
assert_eq!(guest.call("fclose", &[0]) & 0xFFFF_FFFF, STDIO_MINUS_ONE);
assert_eq!(guest.errno(), STDIO_EINVAL);
guest.set_errno(0);
// A closed stream is no stream to any function, and closing a standard
// stream is not modelled.
close(&mut guest, again);
for symbol in ["fclose", "fflush"] {
assert_eq!(guest.run(symbol, &[again]).1, LIMIT, "{symbol}");
}
let (_, exit) = print_with(&mut guest, MINGW_OPTIONS, again, b"x", &[]);
assert_eq!(exit, LIMIT);
for stream in [input, out, err, TEXT] {
assert_eq!(guest.run("fclose", &[stream]).1, LIMIT, "{stream:#x}");
}
for stream in open_streams {
close(&mut guest, stream);
}
assert_eq!(guest.errno(), 0);
}
/// `perror` "prints an error message to stderr": the message "followed by a
/// colon, then by the system error message for the last library call that
/// produced the error, and finally by a newline character"; "if message is a
/// null pointer or a pointer to a null string, perror prints only the system
/// error message". The page's example prints "No such file or directory"
/// for a missing file; the other texts are Xenora's.
#[test]
fn perror_writes_the_message_and_the_error_text_to_stderr() {
let (mut guest, _) = stdio_guest();
guest.set_errno(0);
// The failure the Gate A2 program would report.
assert_eq!(open(&mut guest, "nosuchf.ile", "r"), 0);
let message = place(&mut guest, STRINGS, b"perror says open failed");
guest.call("perror", &[message]);
assert_eq!(
guest.state.standard_error(),
b"perror says open failed: No such file or directory\r\n"
);
// perror does not change errno.
assert_eq!(guest.errno(), ENOENT);
assert!(guest.state.standard_output().is_empty());
let empty = place(&mut guest, STRINGS + 0x80, b"");
let mut expected = guest.state.standard_error();
for (errno, message, text) in [
(ENOENT, 0, &b"No such file or directory\r\n"[..]),
(ENOENT, empty, b"No such file or directory\r\n"),
(0, message, b"perror says open failed: No error\r\n"),
(STDIO_EINVAL, 0, b"Invalid argument\r\n"),
(EBADF, 0, b"Bad file descriptor\r\n"),
(EMFILE, 0, b"Too many open files\r\n"),
(ENOSPC, 0, b"No space left on device\r\n"),
(13, 0, b"Permission denied\r\n"),
(12, 0, b"Not enough space\r\n"),
(999, 0, b"Unknown error\r\n"),
] {
guest.set_errno(errno);
guest.call("perror", &[message]);
expected.extend_from_slice(text);
assert_eq!(guest.state.standard_error(), expected, "errno {errno}");
assert_eq!(guest.errno(), errno);
}
// An unreadable message is a fault and prints nothing.
let exit = guest.run("perror", &[0x9_0000_0000]).1;
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
assert_eq!(guest.state.standard_error(), expected);
}
/// The module and symbol pairs a program built with mingw-w64 14.0.0 (UCRT)
/// imports the four file services by.
#[test]
fn file_services_resolve_as_mingw_w64_imports_them() {
let (registry, _) = standard(0);
let named = |name: &str| ImportName::Name(name.to_owned());
const STDIO: &str = "api-ms-win-crt-stdio-l1-1-0.dll";
const RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
for (module, symbol) in [
(STDIO, "fopen"),
(STDIO, "fclose"),
(STDIO, "fgets"),
(RUNTIME, "perror"),
] {
let service = registry
.resolve(module, &named(symbol))
.unwrap_or_else(|| panic!("{module}!{symbol}"));
let target = registry.resolve("ucrtbase.dll", &named(symbol)).unwrap();
assert!(std::ptr::eq(service, target), "{symbol}");
assert_eq!(service.status, ServiceStatus::Partial, "{symbol}");
}
assert!(registry.resolve(RUNTIME, &named("fopen")).is_none());
assert!(registry.resolve(STDIO, &named("perror")).is_none());
}
/// The module and symbol pairs a program built with mingw-w64 14.0.0 (UCRT)
/// imports these six services by, read from such a program's import table.
#[test]
+53 -3
View File
@@ -389,9 +389,9 @@ Everything else that is not modelled stops the guest with the runtime-limit
fault and writes nothing, so that nothing is printed wrongly: the
floating-point types (`e`, `f`, `g`, `a`), wide characters and strings (`C`,
`S`, `lc`, `ls`), a locale object, option bits other than the three that do
not affect these conversions, any stream other than `stdout` and `stderr`
(files do not exist yet, and `stdin` cannot be written), an index above 2,
more than 1 MiB in one call, and output past the 16 MiB bound.
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
@@ -399,6 +399,56 @@ 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
+14 -10
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 | 43 |
| Generated adapters | 43 |
| Unique handler implementations | 43 |
| Services with a declared ABI | 47 |
| Generated adapters | 47 |
| Unique handler implementations | 47 |
| Implemented | 7 |
| Partial | 33 |
| Partial | 37 |
| Stub | 3 |
| Conformance-tested through guest dispatch | 43 |
| API-set aliases (not services) | 43 |
| Conformance-tested through guest dispatch | 47 |
| API-set aliases (not services) | 47 |
| Independently accepted | 0 |
| Service | Signature | Status | Failure |
@@ -32,10 +32,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
| `ucrtbase.dll!__acrt_iob_func` | `(index: u32) -> ptr` | partial | stops the guest for an index above 2 or when the streams cannot be allocated |
| `ucrtbase.dll!__stdio_common_vfprintf` | `(options: u64, stream: ptr, format: ptr, locale: ptr, arguments: ptr) -> i32` | partial | -1 with errno EINVAL for a null stream or format or an invalid format; stops the guest for what is not modelled |
| `ucrtbase.dll!fwrite` | `(buffer: ptr, size: u64, count: u64, stream: ptr) -> u64` | partial | 0 with errno EINVAL for a null buffer or stream; stops the guest for a stream other than stdout or stderr |
| `ucrtbase.dll!fputs` | `(text: ptr, stream: ptr) -> i32` | partial | EOF with errno EINVAL for a null string or stream; stops the guest for a stream other than stdout or stderr |
| `ucrtbase.dll!fflush` | `(stream: ptr) -> i32` | partial | stops the guest for a stream that is not a standard stream |
| `ucrtbase.dll!setvbuf` | `(stream: ptr, buffer: ptr, mode: i32, size: u64) -> i32` | partial | -1 with errno EINVAL for a null stream, an unknown mode or a size outside 2 to INT_MAX; stops the guest for a stream that is not a standard stream |
| `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 |