Linux guest CRT stdio boundary
The stdio layer uses real 32-bit guest _iobuf objects and guest buffers.
A table containing only native FILE * values is insufficient: translated
MSVCP60 streambuf methods read and modify the guest buffer pointer and count
without calling a CRT adapter. Host descriptors and host pointers must remain
in host-only bookkeeping keyed by the guest FILE address.
The output implementation in runtime/guest_stdio.c now supports opening,
reopening, writing, flushing and closing local files. Input, seeking, wide stdio
and descriptor interoperation remain unimplemented. The initial analysis and
the implemented/verified output subset are recorded below.
Observed ABI and initialization
The x86 layout is eight 4-byte fields, total 32 bytes:
| Offset | Field | Guest representation |
|---|---|---|
| 0 | _ptr |
32-bit guest buffer address |
| 4 | _cnt |
Signed 32-bit remaining count |
| 8 | _base |
32-bit guest buffer start |
| 12 | _flag |
32-bit CRT flags |
| 16 | _file |
32-bit guest CRT descriptor number |
| 20 | _charbuf |
Inline 32-bit character-buffer storage |
| 24 | _bufsiz |
Signed 32-bit buffer size |
| 28 | _tmpfname |
32-bit guest filename address or zero |
The local MinGW compatibility declaration is in
toolchains/llvm-mingw-20261006-ucrt-x86_64/include/corecrt_wstdio.h,
struct _iobuf, non-UCRT branch. Do not use the host compiler's native FILE
definition: the UCRT declaration is opaque and Linux glibc has a different ABI.
MSVCP60's actual instructions corroborate offsets 0, 4 and 8, and its standard
stream initialization uses _iob, _iob + 32 and _iob + 64.
The temporary probe local/client/stdio/tmp_iob.c loads the system
x86 MSVCRT, obtains _iob with GetProcAddress, and snapshots all 20 entries
before printing through its separate UCRT. MSVCRT was not already loaded.
local/client/stdio/initial-iob.log records:
| Entries | _ptr, _base |
_cnt |
_flag |
_file |
_charbuf |
_bufsiz |
_tmpfname |
|---|---|---|---|---|---|---|---|
| 0, stdin | Same nonnull address | 0 | 0x101 |
0 | 0 | 4096 | 0 |
| 1, stdout | Both zero | 0 | 0x2 |
1 | 0 | 0 | 0 |
| 2, stderr | Both zero | 0 | 0x2 |
2 | 0 | 0 | 0 |
| 3 through 19 | Both zero | 0 | 0 | 0 | 0 | 0 | 0 |
In particular, vacant slots do not start with _file == -1. Neither stdout nor
stderr starts with _IONBF set in this reference. The guest stdin pointer can
refer to a new mapped 4096-byte buffer; it must not retain the Windows address.
The existing 64-KiB CRT data page has room for the 640-byte array and that buffer.
The data export denotes the array itself, not a pointer-to-array variable.
The reference is Windows system MSVCRT 7.0.26100.9444, physical x86 file
C:/Windows/SysWOW64/msvcrt.dll, SHA-256
23a918921c545140d189ce6dc68590bacdeb0ab2f3e3a9a2d722c5aff45ce64f.
GetModuleFileName reports the redirected System32 path from the x86 process.
This is the system-CRT choice used by the current native Windows reconstruction;
it is not evidence of the original 2003 operating system's CRT initialization.
The probe used inherited handles from the command runner. Console attachment,
redirection and later I/O state still need distinct tests.
Reproduce from the repository root:
& toolchains/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe local/client/stdio/tmp_iob.c -o local/client/stdio/tmp_iob.exe
& local/client/stdio/tmp_iob.exe
Actual translated stream paths
MSVCP60 is the shipped x86 DLL with SHA-256
2b6b93c2d66969eb00258e2b5ad6172decebada096e3b1b077a3380c80e4a072.
Original base 0x780c0000 maps to generated base 0x46000000; RVAs remain the
same. References below name generated symbols, so they remain searchable if
source line positions change.
lifted-0000.c:sub_46001703constructs cin/cout/cerr/clog and three filebufs from the first three_iobentries. This alone does not perform useful I/O.lifted-0000.c:sub_46001C27(basic_filebuf<char>::_Init) stores FILE at object+0x50. For a nonnull FILE when the Init flag is not 1, it aliases streambuf+0x1c and +0x20 to FILE+0 (_ptr), +0x0c and +0x10 to FILE+8 (_base), and +0x2c and +0x30 to FILE+4 (_cnt). These are addresses of fields, not copied values. Freshly opened filebufs use Init flag 1 and do not take this alias branch; standard streams constructed from an existing FILE do.lifted-0001.c:sub_4600282D(overflow) first uses the aliased pointer/count when space exists. Otherwise, the no-conversion path callsfputc. A locale conversion path also callsfwrite.lifted-0020.c:sub_460159FB(uflow) likewise consumes an available guest buffer byte through the aliases, otherwise callsfgetc. Its return is an unsigned byte or -1. The conversion branch repeatedly callsfgetc.lifted-0002.c:sub_460029C6(sync) callsfflushand returns -1 on a negative result.ostream::flushpropagates streambuf failure into stream state.lifted-0020.c:sub_46015924(pbackfail) can decrement the guest buffer pointer and restore count directly; otherwise it callsungetc.lifted-0020.c:sub_460157C3(open) calls__Fiopen,_Initand_Initcvt.lifted-0028.c:sub_4602304B(__Fiopen) maps openmode to a mode string, callsfopen, optionally seeks to end, and closes on failed seek.lifted-0020.c:sub_46015B08andsub_46015B79usefseek,fgetpos, andfsetpos. The CRTfpos_tpayload is 8 bytes; do not substitute Linux's native fpos_t representation. The larger C++ std::fpos return object includes additional state and is still managed by translated MSVCP code.lifted-0020.c:sub_46015C27(setbuf) callssetvbuf(FILE, buffer, 0, size).sub_4601580C(close) callsfclose, resetting its FILE only on success.
Static references establish reachable paths inside these methods, not that AO has exercised each one during Linux startup. This pass did not audit every AO direct FILE-field access.
Import boundary and minimal implementation sequence
The MSVCP imports are fclose, fwrite, fputc, ungetc, fgetc, fgetpos,
fseek, fsetpos, setvbuf, fopen, _iob, and fflush, plus wide-character
stdio variants. fread is used by AO modules and ACE but not imported by this
MSVCP DLL. The inventory contains no _filbuf or _flsbuf imports from any
listed module; their occurrences are MSVCRT exports. Thus these refill/flush
helpers are conceptual implementation machinery, not an immediate exported
facade requirement. Add their import adapters if actual callers appear.
local/client/game-14.9.1/inventory.json shows the relevant direct
CRT callers include br, bbr, Clientr, cr, ddr, hhr, kkr, kr, pr, sr, ACE and
ACEMFC. Several other modules import _iob without these file operations.
The full inventory also includes unused/vendor candidates, so import presence
alone must not be interpreted as a runtime trace.
Recommended narrow sequence:
- Bind
_iobto real guest data with the measured initialization above. Keep operational imports explicitly unsupported. Assert layout and alias identity through the translated filebuf constructor. - Implement a host-only file record keyed by guest FILE address, owning a host
descriptor and guest buffering state. Guest
_fileremains a guest CRT descriptor identifier; do not cast it to a host handle or pointer. Binary open/read/write/flush/close is the smallest coherent operational milestone. - Preserve guest
_ptr, signed_cnt,_base,_bufsizand flags as the authoritative visible state. On adapter entry, account for direct translated reads/writes since the previous call. Never overwrite that progress with a stale host copy. Avoid a second independent buffering layer in a host FILE. - Route fgetc/fputc and fread/fwrite through that same state. fgetc/fputc return an unsigned byte or EOF (-1); fread/fwrite return complete element counts, not byte counts. fclose must flush pending output and report failure. fflush must include output written only through streambuf pointer aliases.
- Add seeking, pushback and caller-supplied buffers together with corresponding
differential cases. Text mode requires Windows CRLF/control-Z behavior and
logical-position handling; passing
"rt"to glibc does not implement it. Preserve an explicit unsupported path until these semantics are implemented if the first slice supports only binary files.
All imported CRT calls here are x86 cdecl: read arguments from guest stack,
return 32-bit scalar/guest pointer in EAX, consume only the 4-byte return slot,
and preserve guest callee-saved registers. For _filbuf/_flsbuf if later
needed, validate their low-level entry contract against the Windows CRT rather
than treating them as aliases of fgetc/fputc. Macro callers may already have
decremented _cnt before entering them.
Do not broaden this into an entire CRT rewrite. Formatted output, locale
conversion, descriptor APIs used by ACE, thread locking and wide stdio remain
separate boundaries. The eventual descriptor layer needs shared ownership
rules for _fdopen/_open_osfhandle; this pass does not establish those rules.
High-value differential checks
Use the same pattern as test_msvcp_strings.py: an x86 Windows reference calls
actual MSVCRT/MSVCP exports, and native64 Linux invokes the translated code and
facade. Normalize buffer addresses to nullness, offsets and alias relationships.
Compare exact return values, bytes, flags/counts and field changes, with hardcoded
expected values for small cases.
- Initial 20-entry
_iobsnapshot, plus filebuf pointers aliasing actual fields. - Binary byte round trip containing 0, 0x7f, 0x80 and 0xff; EOF must remain distinguishable from byte 0xff. Exercise buffer exhaustion, not just one byte.
- Mix a CRT call with a direct translated streambuf read/write and then another CRT call. Flush must emit each byte exactly once; reads must not repeat bytes.
- fread of elements larger than one byte where EOF leaves a partial element; zero-size requests; fwrite and flush failure on a read-only stream. Check bytes transferred separately from returned whole-element count.
ungetc, read-after-seek, and caller-ownedsetvbufmemory with surrounding canaries. fgetpos/fsetpos must write/read exactly 8 guest bytes.- Text CRLF across a buffer boundary, control-Z, append and update modes before claiming general AO file compatibility. Verify actual output file bytes.
- Translated cout/cerr flushing, tie ordering and error propagation, including stdout redirected to a file. Successful constructors alone are insufficient.
The list above includes outstanding input, seeking and translated-iostream checks. The output checks actually executed are described below.
Implemented output and verification
guest_stdio.c owns native descriptors in a host-only table keyed by guest FILE
addresses. Standard descriptors are duplicated, so redirecting the game's stderr
does not redirect the host's diagnostic stream. The first twenty FILE records
use _iob; additional records use the guest heap, up to the CRT's 512-stream
limit. Guest descriptor numbers and native descriptor numbers are separate.
Implemented calls are fopen, freopen, fclose, fflush, fputc, fwrite, fputs, fprintf, vfprintf, setvbuf and _fileno. Output buffers remain in guest memory; flush uses the current guest pointer/base, including direct translated writes. Text output expands LF to CRLF without dropping an existing CR. Binary output preserves all bytes. Append uses the native append flag. Caller-owned buffers are not freed; odd sizes round down to an even byte count as observed in MSVCRT.
test_portable_stdio.py compares Windows x86 MSVCRT with the Linux adapters in
fresh temporary directories. It checks physical file contents, representative
FILE fields, stack/register preservation, direct FILE-buffer writes, text and
binary output, embedded NUL/0xff, formatted guest arguments, buffer exhaustion,
caller-buffer canaries, unbuffered visibility, fflush(NULL), append, element
counts, failed reopen, directory/open errors and write attempts on read-only
streams. Twenty-four simultaneous streams exercise allocation past _iob and
independent buffers/descriptors. All cases pass. The shared string-format engine
also still passes its separate 288-case Windows comparison.
The tested system MSVCRT _cexit leaves an explicitly opened stream's pending
bytes buffered; fclose subsequently writes them. This was also observed after
calling __getmainargs. The fixture checks this behavior, and no extra implicit
flush was added to the guest _cexit adapter. It differs from the general
current CRT documentation,
so complete application/DLL shutdown remains an outstanding validation step.
Input and seeking APIs still fail at unresolved imports. Flushing nonempty input buffers and switching buffered input to output fail explicitly. Unicode stdio, multibyte locales, Windows drive/UNC paths, sharing/locking semantics, descriptor APIs and nonstandard mode suffixes are unsupported. Formatted output inherits the existing formatter's explicit rejection of floats, wide strings and percent-n. This is working file output, not complete CRT equivalence.
REA evidence ledger
REA Ghidra 12.1.4, immutable-source analysis of the MSVCP DLL identified above. The session was closed after inspection. Pseudocode is decompiler output; the generated instruction comments corroborate addresses and guest field widths.
| Observation | Original entry | Evidence ID |
|---|---|---|
| Standard stream initialization | 0x780c1703 |
ev_b3c80a89bbff85178a963d58cf1d115dc154b26b658fa8b5856e332e1c9f6da6 |
| FILE field aliases | 0x780c1c27 |
ev_f226ccbe7c48df4dc6884357f90c0498a502ee1b777e12cefac6cadd3ef85297 |
| Output fast path and CRT fallback | 0x780c282d |
ev_4341214845c9a26e0303bd8a89547b150b6671fda226c16bf3b734dcf39dae97 |
| Flush result propagation | 0x780c29c6 |
ev_20288b7e512c09d16d3f840cd264b7df5bc9c7d424b11c987b07f32faa88f5fd |
| Input fast path and CRT fallback | 0x780d59fb |
ev_43781adbc782b8e20b62c4a51c39e0b4c729b7a1f42870abd1717cc9418ab7c5 |
| Putback behavior | 0x780d5924 |
ev_6e4142b4b6c01e64602bdef86615de8396dfc23ac83af0e09a04bf450279f472 |
| Seek and position payload | 0x780d5b08 |
ev_51b11cedc1b5513e0fcd52e07ab0713a5e2edb28e09a06c26a1d76aba5f856fd |
| Caller buffer | 0x780d5c27 |
ev_12d689fdbf55b41f3a6de788f9cf44fc7deb393a3472ccece85ca15f90dbc7fc |
| Close and reset | 0x780d580c |
ev_adf48414f0d349afd00155dd71e2c54e6d31e7dfcf262f24c11d16fe523a8031 |
| Open and conversion setup | 0x780d57c3, 0x780d5c57 |
ev_ef1b234c4f11bdc6d6d70548077e6bf27f07598745f4e0c2b56ec14cab5eeb33, ev_80edd864ac734068f7499aa4a83c365ececca899aacf0620828f700e0549ef1b |
| CRT fopen mapping and seek-to-end | 0x780e304b |
ev_97fd5f75259de137ed9058573cdebef0820bae907a7ea08477798975208a5622 |