MS-DOS and 16-bit Windows¶
This directory has DOS support for picolibc on the i8086 target of the
clang-dos LLVM toolchain. It is built
into libc.a itself, together with crt0.obj, so a program needs
nothing else from picolibc.
Building¶
One build per memory model (tiny makes .COM programs, small makes
.EXE programs), with clang, llvm-ar and a Watcom-style linker (wlink or
JWlink) on PATH:
meson setup build-small \
--cross-file scripts/cross-clang-i8086-msdos-small.txt \
-Dos-msdos=true -Dmultilib=false -Dpicocrt=false -Dsemihost=false \
-Dtests=false -Dposix-console=true -Dsingle-thread=true \
-Dthread-local-storage=false -Dspecsdir=none \
--prefix=$PWD/install-small
ninja -C build-small install
Copy include/ to <sysroot>/include and lib/crt0.obj and lib/libc.a
to <sysroot>/lib/small. clang --target=i8086-pc-msdos --sysroot=<sysroot>
then links them, with libclang_rt.builtins.a, by default.
What the startup code does¶
crt0.S sets DS, ES and SS to DGROUP (an .EXE starts with SS at its
STACK segment), clears BSS (and with far data pointers the far BSS after
the stack) and calls __msdos_start in start.c, which:
- sets up the heap. In a small or medium model .EXE it is the rest of DGROUP after the stack, up to 64 KiB or the end of the program's memory. In compact and large it is a segment of its own after the program (after far BSS), up to 64 KiB; in huge it runs from there to the end of the program's memory. In a .COM it ends 2 KiB below the stack, which DOS puts at the top of the segment.
- splits the command tail at PSP:80h into
argv. Double quotes group words, and\"is a quote, as in the Microsoft C runtime. - copies the environment block into
environand takesargv[0]from the program path after it (DOS 3 and later). - runs the constructors (the XI segment) and calls
exit(main(...)).exitrunsatexithandlers and destructors (the YI segment).
The stack of an .EXE is 4 KiB; build with
-D__MSDOS_STACK_SIZE=<bytes> in c_args to change it, or link a
program with the linker's option stack=<bytes>, which makes the STACK
segment larger. In the small and medium models crt0 records the top of the
stack in __msdos_stack_top, and the heap starts there when that is after
__heap_start.
In every model but tiny, DGROUP starts with 16 bytes that nothing uses (in Windows, the bytes that Windows keeps), so that no variable or string is at offset 0, where a near pointer to it would be null.
System calls¶
File I/O, stat, directories, rename, dup/dup2, isatty, the clock
(time, gettimeofday, clock_gettime, times, nanosleep) and _exit
use INT 21h. DOS error codes become errno values in error.c.
- Handles are in text or binary mode, as with DOS C compilers. In text mode, writes turn LF into CR LF, and reads turn CR LF into LF and stop at Ctrl-Z (a CR with no LF after it is kept). Binary mode reads and writes bytes as they are.
fopenopens a file in binary mode withbin the mode ("rb","w+b"), and in text mode otherwise (t, as in"wt", also asks for text).opentakesO_TEXTorO_BINARY; with neither, it uses_fmode, which starts asO_TEXT.setmode(fd, O_TEXT or O_BINARY)(also_setmode, declared in<io.h>and<fcntl.h>) changes a handle's mode and returns the old one.- The standard handles 0 to 4 start in text mode.
ftellandfseekon a text stream use file offsets, softellcounts each line end as 2 bytes. It assumes each LF still in the stdio buffer came from a CR LF.- After a read stops at Ctrl-Z, the file stays at the Ctrl-Z and further reads return 0 until the program seeks.
- Creating a file with
O_TRUNC(fopen(..., "w")) also writes 0 bytes at its start, which truncates it on emulators (emu2) that don't empty an existing file on INT 21h function 3Ch. O_APPENDseeks to the end before each write.opendir,readdir,rewinddirandclosediruse find first and find next (INT 21h functions 4Eh and 4Fh), with hidden and system entries;dirfdandfdopendirfail.statalso finds directories named with a trailing\,.or..and the root of a drive, through the canonical name (function 60h), which is alsorealpath.lstatisstat.removedeletes a file, or an empty directory withrmdir.chmodsets or clears the read-only attribute from the owner write bit (function 43h);fchmodfails withENOSYS.truncateandftruncatewrite 0 bytes at the new size.utime,utimes,utimensatandfutimensset a file's date and time (function 5701h), to 2 seconds.statvfsandfstatvfsreport the drive's clusters (function 36h).linkandsymlinkfail withENOSYS, andreadlinkwithEINVAL.- The DOS clock is local time; it is treated as UTC. It ticks about 18 times a second.
fork,execve,pipeandwaitpidfail withENOSYS(waitpidwithECHILD); terminal attributes withENOTTY.getentropy(getentropy.c), which seedsarc4random, mixes timing noise into a sponge built on the ChaCha permutation: the DOS date and time, the BIOS tick count, the PSP and the stack pointer (on Windows, the tick count, task and instance instead of the BIOS ticks and the PSP), then a few hundred readings of timer channel 0 (1.19 MHz), each after a delay loop that depends on the last reading. On a CPU with a time stamp counter (CPUID says so) each reading also takes RDTSC. With RDTSC, or in an emulator whose timer follows the host clock, the seed is hard to guess; on an 8088 PC, whose CPU and timer share one crystal, mostly gives the moment the program started, which an attacker who knows it well can guess.- Signals,
raiseandsysconfcome fromlibos/fallback. halloc(n, size)andhfree(halloc.c, declared in<malloc.h>for every model but tiny) allocate zeroed blocks of up to 1 MiB with INT 21h function 48h, last fit, and free them with function 49h. DOS gives an .EXE all of its memory, so when no free memory is left the firsthallocshrinks the program's block with function 4Ah: to the end of the heap, or in the huge models by the size of the block, lowering the end of the heap.dosmem.cgets memory from DOS forhallocand the far heap; the tiny model gives up all but its 64 KiB segment.farstring.chas the far string functions (_fmemcpy,_fstrlenand the rest),farheap.cthe far heap (_fmalloc: arenas ofarena.hin segments from DOS orGlobalAllocwith near data,mallocwith far data), andnearheap.cthe near heap (_nmalloc:mallocwith near data, the Windows local heap, or an arena in__msdos_near_heapin DGROUP,nearheapsize.c).
Interrupt handlers and resident programs¶
<dos.h> and <i86.h> (in libc/machine/i8086) have what Open Watcom
and Microsoft C have for interrupt handlers and TSRs, for DOS programs:
_dos_getvect(n)and_dos_setvect(n, handler)(dosvect.c) read and set interrupt vectornwith INT 21h functions 35h and 25h. Handlers arevoid (__interrupt __far *)()._dos_keep(status, paras)(dosvect.c) ends the program and keepsparasparagraphs of it, from the PSP, resident (INT 21h function 31h). With 0 it keeps the program up to the end of its heap (the break ofsbrk), which covers the code, the data and anything allocated so far; the stack of a .COM, at the top of its segment, is given back, since interrupt handlers run on the stack of the program they interrupt. Other DOS blocks (halloc, the far heap) stay allocated.atexitfunctions and destructors do not run._chain_intr(handler)(chainintr.S), from an__interruptfunction, restores the registers it saved, with any changes made to them, and jumps tohandleras if the interrupt had gone there. It finds the saved registers at the interrupt function's BP.union INTPACK(<i86.h>) is the layout of the saved registers that an__interruptfunction can take as its parameter._disable()and_enable()are CLI and STI;MK_FP,FP_SEGandFP_OFFmake and split far pointers._pspis the PSP segment.
The console and Turbo C helpers¶
<conio.h> (in libc/machine/i8086) has the text console functions of
Turbo C and Microsoft C, for DOS programs:
conio.ckeeps the text window, the attribute and the cursor instruct __conio(conio-local.h), which it reads from the BIOS data area on first use and aftertextmode. Output (putch,cputs,clrscr,clreol,insline,delline) writes straight to video memory at B800h (B000h in mode 7), wraps at the window's edge and scrolls the window unless_wscrollis 0; it moves the BIOS cursor to match after each call.\a,\b,\rand\nact as on a terminal.cprintf.chascprintfandvcprintf, through a tinystdio stream (FDEV_SETUP_STREAM) that writes withputch.context.chasgettextinfo,textmode(C4350loads the 8x8 font for 43 or 50 lines),_setcursortype,gettext,puttextandmovetext.conin.creads the keyboard with INT 21h function 07h (getch, without echo or Ctrl+C checks; extended keys come as 0 and the scan code) and 0Bh (kbhit), and hasungetch,cgets,cscanfand the line editing ofgetpass, whichgetpass.cuses in place of the POSIX one so the password is read from the console without echo.
<i86.h> and <dos.h> also have:
int86,int86x,intdos,intdosxandsegread(int86.c) withunion REGSandstruct SREGS. They call__msdos_intr(intr.S), which loads the registers from a block, calls the interrupt through its vector with an IRET frame (so any interrupt number works without self-modifying code), and stores the registers and flags back.delay(ms)(delay.c) counts down the PIT's channel 0, so it is accurate to the millisecond without calibration;sound(hz)andnosound()drive the speaker through channel 2.inportb,inport,outportb,outport,peek,peekb,poke,pokeb,getvect,setvect,disableandenable, the Turbo C names of the port, memory and interrupt helpers.
16-bit Windows¶
The same code builds for i8086-pc-win16 (the cross files
scripts/cross-clang-i8086-win16-<model>.txt, for small, medium, compact
and large), where __WINDOWS__ is defined. Windows programs call DOS for
files and the clock, so the system calls above work unchanged; the
startup code and the heap differ:
crt0.ScallsInitTask, which sets up the program (DS is DGROUP and SS is DS), clears BSS, saves the instance handles andnCmdShow, callsWaitEventandInitAppand goes on to__msdos_startas on DOS. The first 16 bytes of DGROUP are left free for Windows. There is no stack of the program's own; the linker'soption stacksets its size.- The heap (
win16.c) is oneGlobalAllocblock of up to 64 KiB in the compact and large models, or aLocalAllocblock in DGROUP in small and medium. argv[0]comes fromGetModuleFileName. The command line is the PSP tail, as on DOS.winmain.chas amainthat callsWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow), for programs without amainof their own.libentry.Sis a DLL's startup code (libentry.obj): it sets up the local heap withLocalInit, clears BSS and calls__win16_libstart, which runs the constructors and callsLibMain(a default one returning 1 is inlibmain.c).WEP(wep.c) runs the destructors._exitis INT 21h function 4Ch, which Windows handles for programs.