Windows (experimental)
--os=windows (or its other name --os=nt) writes a Windows x64 console
executable (PE32+) from Pascal, C or Nil Python. It is EXPERIMENTAL, like every target except Linux.
./pxx --os=windows hello.pas hello.exe # run it on Windows, or: wine64 hello.exe
The program imports kernel32.dll and ws2_32.dll (sockets), and only
functions that every Windows since XP and Server 2003 exports, so it needs
no C runtime (msvcrt or ucrt) and no installer. The few newer functions it
uses are looked up when it starts, with a fallback for each one a system
lacks (see below), so the same .exe is meant for Windows 8 and later,
Windows 7, and ReactOS.
Older Windows and ReactOS
| Newer function | Missing on | Stand-in |
|---|---|---|
GetSystemTimePreciseAsFileTime |
Windows 7, ReactOS | GetSystemTimeAsFileTime (a coarser wall clock) |
QueryUnbiasedInterruptTime |
ReactOS | QueryPerformanceCounter (also counts time asleep) |
GetTickCount64 |
ReactOS | GetTickCount (wraps after 49.7 days) |
WaitOnAddress, WakeByAddress* |
Windows 7, ReactOS | the waiting thread re-reads the word, yielding and then sleeping 1 ms |
The translator's own lock is a spinlock, so SRW locks are not needed. The
last fallback makes a contended lock or a thread join take up to a
millisecond longer. Set PXX_WINABI_PRE8=1 to use every fallback on a
newer system; make test-windows runs a few time, socket and thread tests
that way under Wine.
Tested on ReactOS
The make test-windows programs were also run inside the ReactOS x64
nightly live CD (kernel "0.4.16-amd64-dev", Build 20260429, under qemu with
no network adapter): 78 of 83 give the same output as on Linux. The
harness is in tools/vm/reactos/: rossnap.sh boots the live CD once and
saves a qemu snapshot, rosbatch.sh test... then runs a batch from it in
about ten seconds plus the programs' own time. The translator works around
three ReactOS behaviours:
- Its loader ignores the TLS directory's
SizeOfZeroFilland allocates only the raw template, so the image now carries the whole thread-local block as zero bytes of raw data, as MSVC's linker does. - A non-blocking
acceptwith nothing pending returnsINVALID_SOCKETzero-extended to0x00000000FFFFFFFFand sets no error; the translator reads that asEAGAIN. - A refused non-blocking
connectshows in Winsock's except set but leavesSO_ERRORat 0; the translator reportsECONNREFUSED.
The compiler itself builds for Windows (--os=windows compiler/compiler.pas)
and works there: under Wine and inside ReactOS it compiled hello.pas to a
Windows .exe that runs. A compiler built this way makes Windows
programs by default (pascal26 hello.pas writes hello.exe; --os=linux
still gives a Linux ELF), and --version reports host: x86-64 nt (NT, whichever
system provides it: Windows, ReactOS or Wine).
It finds lib/ and compiler/builtin/ (where winabi lives) the usual
way: installed as <root>/compiler/pascal26.exe beside <root>/lib, or
through PXX_HOME.
It also compiles itself there: on 2026-11-15, under Wine, the Windows build
compiled compiler/compiler.pas in 42 s to an .exe byte-identical to the
one the Linux compiler makes with --os=windows. The guard that refuses an
output naming an input also works there: g/sub/../t.pas and G/T.PAS
(Windows names ignore case) both count as g/t.pas.
Known differences there:
- ReactOS has no IPv6: the IPv6 tests report that and skip.
- A TCP listener bound to
0.0.0.0does not get connections made to127.0.0.1(seen with no network adapter); bind the listener to127.0.0.1for local use.test_asyncudpwaits for ever on this and is left out. - A stack overflow ends the program (exit 128) instead of raising an exception; see "Not supported yet".
- With no page file,
sysinforeports no swap.
How it works
The design is the same as the BSD targets (see
FreeBSD and the BSDs). The runtime is written against the
Linux system-call interface, and under --os=windows every system call goes
to a small translator compiled into the program
(compiler/builtin/winabi.pas). The translator answers it with kernel32
calls. Windows has no stable system-call numbers (they change between
builds), so kernel32 is the bottom layer rather than the kernel.
Five things differ from the BSD ports:
- The file format.
compiler/pewriter.incwrites the PE image. It is laid out like the ELF one, with the code at RVA0x1000and the data after it. Imports go through the Import Address Table, which takes the place of the GOT slots the x86-64 external call already reads. The image prefers the base0x400000and carries a.relocsection that lists every absolute address in it (method slots, data pointers, C initialisers, the TLS directory, the code's 64-bit immediates), so it is markedDYNAMIC_BASEand Windows may load it anywhere below 4 GiB (ASLR, without high-entropy addresses).--image-base=0x7ffe0000gives a base the loader has to move, which is howmake test-windowschecks the relocations. - The calling convention. pxx code keeps the System V convention
internally. Each call to a DLL function converts at the call site: the
first four arguments move to
rcx,rdx,r8andr9, the fifth and sixth go to the stack above 32 bytes of shadow space, and stacked arguments already land where Windows expects them. A call with a floating-point argument is rebuilt argument by argument instead, because Windows gives argument n the n-th slot whatever its type (rcxorxmm0,rdxorxmm1, and so on, then the stack), where System V counts integers and floats apart. A float among the first four also goes into its integer register, which is what a variadic Windows function such assprintfreads. Float results come back inxmm0under both. - Thread-local storage. A Windows program cannot point
fsorgsat its own block, becausegsis the thread environment block. The block is the image's PE TLS data instead, which the loader allocates for every thread. Code reaches it through the TEB (gs:[0x58], then index 0), which costs two loads where Linux needs none. - Threads.
clonebecomesCreateThread. The new thread moves onto the stack the runtime gave it, so it starts exactly where a Linux clone child would.futexbecomesWaitOnAddressandWakeByAddress*, and a thread's exit wakes its joiner as Linux'sCLONE_CHILD_CLEARTIDdoes. Threads need--threadsafe, as on Linux. - The stack. The image commits its whole 8 MiB stack at load time. Windows grows a stack one guard page at a time, and pxx functions do not probe their frames, so a frame larger than 4 KiB would otherwise skip the guard page and crash.
What works
Each item is checked against the Linux build of the same test by make test-windows (run under Wine through tools/vm/wine.sh):
-
console output and input; UTF-8 text written to a console window is shown as UTF-8 (converted for
WriteConsoleW, also when a character is split across two writes), while output to a file or a pipe is left as the bytes the program wrote -
the heap
-
exceptions
-
time and
Sleep -
command-line arguments (
ParamCount/ParamStr, split by the Microsoft C runtime's quoting rules, and converted to UTF-8) -
environment variables
-
exit codes and runtime errors
-
files: open/create/truncate/append, read and write, seek,
pread/pwriteand their vector forms,stat/fstat, rename, delete,ftruncate,fsync,dup/dup2, and pipes -
directories: create, remove, list (
getdents64overFindFirstFileW), the current directory, and the*atcalls relative to a directory fd -
Nil Python's
os.pathon Windows paths:basename,dirname,split,splitext,isabs,abspathandnormpathtake\as a separator and keep a drive (Z:) in front, as CPython'sntpathdoes. Unlike CPython,join,abspathandnormpathwrite/(Windows accepts it), so a program prints the same paths as on Linux:Z:/dir/prog.exe -
select,polland theirpforms, on the console, pipes, files and sockets -
sockets (TCP and UDP, IPv4 and IPv6) over Winsock:
connect,bind,listen,accept, the send and receive calls,shutdown, the socket options the runtime uses, non-blocking mode (O_NONBLOCK,SOCK_NONBLOCK,MSG_DONTWAIT),socketpair, and the runtime's sockets, net, HTTP and async DNS units -
epoll,timerfdandeventfd, emulated, so the coroutine scheduler and its reactor run (the async echo, UDP and timer tests) -
non-blocking pipes (
pipe2withO_NONBLOCK,fcntl), andSIGPIPEon a write to a pipe or socket whose reader has gone, as on Linux -
starting programs:
ExecuteProcessand the other SysUtils process calls, and Nil Python'ssubprocess(run,Popen, pipes in both directions, return codes,FileNotFoundError), withwait4andkill
Windows has no fork, so the runtime's one spawn routine
(PalBackendVforkAndExec3) passes the whole request to the translator,
which calls CreateProcessW instead of forking and execing. The argument
list is quoted so that the child's C runtime splits it back into the same
strings. A program named without a path is looked up on PATH (separated by
;, with or without .exe), then by CreateProcessW itself. A child ended
by kill reports that signal to wait, as on Linux. A C program's own
fork() answers ENOSYS.
select, poll and epoll_wait check each fd, then wait in Winsock's
select on the sockets among them, which wakes as soon as one is ready.
Windows has no one call that also covers consoles and pipes, so when one of
those is in the set the wait is cut to a few milliseconds and the check
repeats.
Sockets keep Linux's defaults where Windows differs: an IPv6 socket also
takes IPv4 (IPV6_V6ONLY off), a UDP socket ignores the ICMP "port
unreachable" that Windows would report on the next receive, and an accepted
socket does not inherit the listener's non-blocking mode. SO_REUSEADDR and
SO_REUSEPORT are recorded but not passed on: Windows already lets a server
rebind a port that is in TIME_WAIT, and its own SO_REUSEADDR would let a
second socket take a port that is in use. socketpair is a connected pair
of loopback TCP (or UDP) sockets.
Signals:
- Hardware faults (access violation, division by zero, floating-point
traps, illegal instruction) reach the program's handler as
SIGSEGV,SIGFPEand so on, with the samesiginfoand register context as on Linux. So a nil access or a call through a bad pointer becomes a Pascal exception where it does on Linux. A fault with no handler ends the process with exit code 128 + the signal number. killandraiseto the program itself run the handler at once, or apply the default action (end the process, or ignore forSIGCHLDand the other signals Linux ignores).sigprocmaskblocks for real, per thread, and a new thread inherits its creator's mask. Blocked signals stay pending forsigtimedwait,sigwait,sigsuspendandsigpending.- A signal sent to another thread (
tkill,pthread_kill) runs on that thread when it next unblocks the signal or makes a system call. Windows has no way to interrupt a thread with a handler, so a thread that loops without system calls, or waits inside one, sees it late. - Ctrl-C is
SIGINT, Ctrl-BreakSIGQUITand closing the consoleSIGHUP, once the program sets a handler (orSIG_IGN) for one of them. Windows runs that handler on a thread of its own, so it really is asynchronous. Checked by hand under Wine, not in the test target.
/proc has six files: /proc/self/environ, /proc/self/exe (the
program's own file), /proc/self/fdinfo/N (the volume serial number as
mnt_id and the file index as ino, which the compiler's output guard
compares), /proc/mounts (one line per local drive, C: / ntfs rw 0 0,
with the current drive on / and the others on D:/ and so on) and the
aggregate cpu line of /proc/stat (GetSystemTimes), and
/proc/net/dev (the interface names, every counter 0).
Every other /proc path is ENOENT, also under Wine, whose drive Z: would
otherwise show Linux's own /proc.
The runtime's DNS resolver reads /etc/hosts and /etc/resolv.conf. On
Windows /etc/hosts is the system's own hosts file
(<system directory>\drivers\etc\hosts), and /etc/resolv.conf is made
up when it is opened: a nameserver line for each DNS server Windows is set
to use, and a search line for its domain, from GetNetworkParams in
iphlpapi.dll (loaded only then, so the image still imports kernel32 and
ws2_32 alone).
Network interfaces (if_nameindex, if_nametoindex, getifaddrs) come
from GetAdaptersAddresses, from the same DLL loaded the same way. They
are IPv4 adapters only, as Linux's SIOCGIFCONF lists them. The runtime
answers the Linux SIOCGIFCONF, SIOCGIFFLAGS, SIOCGIFADDR,
SIOCGIFNETMASK, SIOCGIFBRDADDR, SIOCGIFINDEX and SIOCGIFNAME
ioctls itself. A name is Windows' own (loopback_0, ethernet_32768,
from ConvertInterfaceLuidToNameA). Where Windows has no such name
(ReactOS and XP), a loopback is lo and any other adapter if<index>.
ReactOS reports index 0 for its loopback, which would end
if_nameindex's list, so such an adapter gets the next free index.
Paths are converted from UTF-8 to UTF-16, and / works as a separator.
/dev/null becomes NUL. An absolute Unix path such as /tmp/x is taken
on the current drive. Under Wine that is drive Z:, the Unix root, so the
path means what it means on Linux.
Not supported yet
- Refused at compile time:
-g,--emit-obj,--rtl-libc, and CPUs other than x86-64. - DLLs:
--shared(or an output name ending in.dll) writes a DLL. A Pascallibraryexports itscdeclroutines and the ones itsexportsclause names. A C file exports its functions that are notstatic, and none of lib/crtl's. Loading the DLL runs its initialisation: the global initialisers, the units'initializationsections and the library's main body, as a Linux.sodoes.finalizationdoes not run at unload. Each export is a stub that jumps to an adapter, which takes the Microsoft convention and calls the routine (the callback adapters, built by DllMain). Threadvars work, through the TLS index the loader gives the DLL; build with--threadsafewhen threads call in. The DLL prefers the base0x10000000and carries.reloc. Refused at compile time: an export with more than 14 parameters, or with a record parameter or result by value. Tested with pxx executables calling pxx DLLs (test/test_nt_dll_built_by_pxx.pas) under Wine inmake test-windows, and once by hand on ReactOS (tools/vm/reactos/rosbatch.sh -f <dll>...). NOT TESTED: a DLL loaded by a program another compiler made. - Loading a library at run time: C's
dlopen,dlsym,dlcloseanddlerror, and Pascal'sdynlibs(LoadLibrary,GetProcedureAddress,UnloadLibrary), use Windows' loader (LoadLibraryA,GetProcAddress,FreeLibrary).dlsymreturnsGetProcAddress's address unchanged; see the next item for how a call through it works.dlopen(NULL)is refused, as on Linux. Tested under Wine (test/c_nt_dlopen.c,test/test_nt_dynlibs.pas). - Calls through a function pointer: a call through a C function
pointer, or a
cdeclorstdcallprocedure type, first compares the address with the program's code (two compares and a branch, on NT only). Inside it is pxx code and is called with pxx's convention. Outside it is taken to be Microsoft-convention code (a DLL's routine, a pxx DLL's export, a callback adapter) and the call is converted as a call to anexternal 'x.dll'routine is, with the full signature the pointer type gives: integer, pointer and floating-point arguments, mixed, on the stack past the fourth. Not converted on that path: a record passed by value, and a record result larger than 8 bytes. Misjudged: the raw address of a routine in another pxx image handed over by hand (not its export, which is fine). Tested intest/test_nt_dynlibs.pasandtest/c_nt_dlopen.c. - Not supported: C's
fork()and process groups. - Symbolic links are Windows' own (
CreateSymbolicLinkW). Making one needs the privilege, or Windows 10's developer mode; without itsymlinksaysEPERM.readlinkandlstatread the reparse point of a symbolic link or a junction, andstatfollows it. Any other reparse point, such as a cloud placeholder, counts as a plain file, sostatdoes not fetch its contents. NOT TESTED where it can work: Wine'sCreateSymbolicLinkWsucceeds without making anything (the translator checks, and saysEPERM), Wine shows a Unix link as its target, and the ReactOS live CD cannot make links.test/c_os_symlink.cchecks it on a Windows that can. - File modes: Windows keeps one permission bit, the read-only attribute.
chmodwith no write bit sets it, and with any write bit clears it;statreads it back as0444or0644. The other bits are dropped.fchmodsucceeds and changes nothing. mmapof a file is a view of a file mapping (CreateFileMappingW,MapViewOfFile):MAP_SHAREDwithPROT_WRITEwrites through to the file,MAP_PRIVATEis copy-on-write, andmsyncflushes the view. Not supported:PROT_EXEC(the view is not executable) andMAP_FIXED. Windows cannot map past a file's end, so the view stops there, and touching the rest faults (Linux faults past the last page). An empty file maps as zeroed private memory.- Signals between processes:
killon another program ends it (TerminateProcess) whatever the signal; it cannot run that program's handler. There is no alternate signal stack, and a stack overflow has no room left to run a handler in. - Sockets: no control messages (
SCM_RIGHTScannot pass an fd to another process), andMSG_TRUNCdoes not report a truncated datagram's full length. A blocking socket call cannot be interrupted by a signal. - Calling other libraries:
external 'libc.so.6'and other Linux libraries cannot work on Windows.external 'user32.dll'and other DLLs do work, with integer, pointer, floating-point and record arguments. A record passed by value follows the Microsoft rule: one of 1, 2, 4 or 8 bytes travels as an integer, any other size as a pointer to a copy the caller makes. A record result of 1, 2, 4 or 8 bytes comes back inrax, and a larger one through a hidden first argument. - Callbacks: a routine of the program passed straight to a DLL routine
(
qsort(@v[0], n, 4, @Cmp),EnumWindows(@Cb, 0)) is handed over as an adapter that takes the Microsoft convention and calls the routine, floating-point and stack arguments included (up to 14 parameters). The program's own calls to the routine are unchanged. Declare a callbackstdcall, as Delphi and Free Pascal code does, and every address taken of it is the adapter, so one stored first also works: a variable, or a record field such as a window class'slpfnWndProc. Withoutstdcall, only an address passed straight into the call is adapted, and one stored first is the routine itself, which crashes when Windows calls it. Astdcallroutine called through a procedural variable from Pascal works: the variable holds the adapter, which lies outside the program's code, so the call takes the Microsoft convention (above). A record passed by value to a callback is not converted.
A system call the translator does not map returns ENOSYS. Set
PXX_WINABI_TRACE=1 in the environment to have each one named on stderr.
The work log is in devdocs/progress/working/feature-port-windows-pe.md.