Просмотр исходного кода

Add setjmp, stdio, math and time to the ring-3 libc

Extend the libc.a archive beyond malloc and strings with the runtime a
JavaScript engine needs:

- setjmp/longjmp, errno/strerror, atoi/atol and the compiler 64-bit
  division helpers (__udivdi3, __moddi3, __divmoddi4, shifts).
- printf/snprintf/sprintf/fprintf with integer, string and pointer
  conversions, and exact %f/%e/%g float formatting through the new
  dtoa.c binary-double decomposition.
- A read-only whole-file FILE layer: fopen("rb"), fread, fseek, ftell,
  fclose; stdout/stderr are console streams and stdin is EOF.  The
  stdio_file.c TODO records the SYS_OPEN/READ/WRITE/LSEEK/CLOSE fd
  layer that writable files and streaming will need.
- The x87 math set (sqrt, pow, exp, log, trig, rounding, fmod, ldexp,
  frexp, modf, fmin/fmax/copysign and the IEEE predicates).
- UTC time from SYS_RTC_GET/SYS_RTC_SET: time, gmtime/localtime,
  mktime, strftime, gettimeofday/settimeofday and clock_gettime, with
  a 64-bit time_t so the RTC's 1970-2069 range fits.

The 64-bit dtoa keeps output exact to the requested precision and was
fuzzed against the host libc over 200k random doubles and 13 formats
with no mismatches.  make test-libc now also runs format, math, div64
and 32-bit setjmp host tests, and the ring-3 smoke test covered printf,
math, fopen/fread/fseek and RTC mktime on target.  make all passes; the
pack is 359027 bytes.
Johannes Zellner 1 неделя назад
Родитель
Сommit
a53dc94855

+ 4 - 0
.gitignore

@@ -17,4 +17,8 @@ ufont_test
 ufont_test_asan
 libc.a
 malloc_test
+format_test
+math_test
+div64_test
+setjmp_test
 mkrootfs

+ 26 - 6
AGENTS.md

@@ -74,7 +74,7 @@ make kernel-net-dev
 make flash      # write the dual-boot image (legacy BIOS + UEFI) to a USB stick
 make test-usb   # headless USB mouse/keyboard regression tests (QEMU + python3)
 make test-images  # host image-decoder + blit tests (ASan variant: test-images-asan)
-make test-libc  # host stress test for the ring-3 malloc
+make test-libc  # host tests for ring-3 malloc, stdio, math, div64 and setjmp
 make test-font  # host TrueType parser/rasterizer specimen test
 make test-font-asan  # ASan/UBSan variant
 make fonts      # regenerate fonts/*.ttf with pyftsubset + system fonts
@@ -613,18 +613,27 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   are not called by application code.  The canvas mapping at
   `USER_GFX_BASE` (`0x50000000`) and the WM mappings are separate.
 - **Ring-3 libc**: `libc/include/` (stddef/stdint/stdarg/stdlib/string/ctype/
-  assert/ucmd_heap), `libc/malloc.c`, `libc/string.c`, `libc/strdup.c`,
-  `libc/stdlib.c`, `libc/ucmd_mem.c`, linked as `libc.a` only into commands
-  that reference it.  `malloc` is a boundary-tag first-fit allocator with
+  assert/ucmd_heap, setjmp/errno/stdio/math/time/sys/time/sys/types, float/
+  limits/inttypes/alloca), `libc/malloc.c`, `libc/string.c`, `libc/strdup.c`,
+  `libc/stdlib.c`, `libc/ucmd_mem.c`, `libc/setjmp.S`, `libc/errno.c`,
+  `libc/div64.c`, `libc/dtoa.c`, `libc/stdio.c`, `libc/stdio_file.c`,
+  `libc/math.c`, `libc/time.c`, linked as `libc.a` only into commands that
+  reference it.  `malloc` is a boundary-tag first-fit allocator with
   immediate coalescing: 16-byte aligned, `calloc` zeroes, `realloc` grows in
   place when the next block is free, and the heap maps 64 KB lazily then
   grows in page-rounded steps with 64 KB slack up to the 32 MB arena cap.
   `heap_reset()` (`ucmd_heap.h`) discards every allocation and unmaps the
   arena for page-scoped apps such as the browser.  There are no threads, so
   there is no lock; application code uses this heap, and the libc backend is
-  the only caller of `SYS_MEM_*`.  The archive plus
+  the only caller of `SYS_MEM_*`.  `stdio` provides integer/string/float
+  `printf`/`snprintf`/`sprintf` formatting and a read-only whole-file `FILE`
+  (`fopen("rb")`, `fread`, `fseek`, `ftell`, `fclose`; stdout/stderr are
+  console streams; stdin is EOF).  `time` uses `SYS_RTC_GET`/`SYS_RTC_SET`
+  with UTC-only `gmtime`/`localtime` and 64-bit `time_t`; `math` is the x87
+  double set used by MuJS.  The archive plus
   `-ffunction-sections`/`--gc-sections` keeps unused code out of the legacy
-  pack.  Host test: `make test-libc` (`libc/test_malloc.c`).
+  pack.  Host tests: `make test-libc` (malloc, format/dtoa, math, div64,
+  setjmp).
 - **Ring-3 commands**: `ucmd_*.c`, `ucmd_lib.h`, `ucmd.ld`, `mkpack.c`,
   `rootfs.h`, `mkrootfs.c`, `ramfs.c/h` — static ELFs linked at
   `USER_BASE` (`0x40000000`), packed by `mkpack` into `cmds.pack` (as
@@ -1382,3 +1391,14 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     evicted glyphs.  The browser must detach/re-attach its font arena around
     `heap_reset()`; terminal/editor cell grids stay on the 8×16 bitmap font,
     while ngui text fields use the proportional face.
+
+27. Ring-3 stdio/time/math limits: `FILE` is read-only and whole-file
+    (4 MB cap); there is no `open/read/write/lseek`/fd layer yet, and
+    `stdin` is EOF.  The TODO is in `libc/stdio_file.c`; writable files and
+    streaming need kernel `SYS_OPEN/READ/WRITE/LSEEK/CLOSE` plus offset
+    `fs_ops`.  `time` is UTC-only, `time_t` is 64-bit, and the RTC range is
+    1970-2069; there is no timezone database.  `math` is an x87
+    double-rounding implementation, not a full fdlibm; `long double`, `%a`
+    and some exact edge cases are not supported.  Float printf supports
+    `%f/%e/%g` with a 900-digit precision cap.  These are sufficient for
+    MuJS but are not a complete POSIX libc.

+ 45 - 4
Makefile

@@ -21,9 +21,17 @@ LIBC_CFLAGS = $(CFLAGS) -Os $(SECTION_CFLAGS) -fno-builtin \
 LIBC_HEADERS = libc/include/stddef.h libc/include/stdint.h \
                libc/include/stdarg.h libc/include/stdlib.h \
                libc/include/string.h libc/include/ctype.h \
-               libc/include/assert.h libc/include/ucmd_heap.h
+               libc/include/assert.h libc/include/ucmd_heap.h \
+               libc/include/setjmp.h libc/include/errno.h \
+               libc/include/stdio.h libc/include/math.h \
+               libc/include/time.h libc/include/sys/time.h \
+               libc/include/sys/types.h libc/include/float.h \
+               libc/include/limits.h libc/include/inttypes.h \
+               libc/include/alloca.h libc/dtoa.h
 LIBC_OBJS = libc/malloc.o libc/string.o libc/strdup.o \
-            libc/stdlib.o libc/ucmd_mem.o
+            libc/stdlib.o libc/ucmd_mem.o libc/setjmp.o \
+            libc/errno.o libc/div64.o libc/dtoa.o libc/stdio.o \
+            libc/stdio_file.o libc/math.o libc/time.o
 
 # Fixed-point TrueType text engine, linked only into GUI commands.
 UFONT_OBJS = ufont.o ufont_ttf.o ufont_draw.o ufont_file.o
@@ -562,6 +570,9 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
 libc/%.o: libc/%.c $(LIBC_HEADERS) ucmd_lib.h syscall.h
 	$(CC) $(LIBC_CFLAGS) -o $@ $<
 
+libc/setjmp.o: libc/setjmp.S
+	$(AS) $(ASFLAGS) -o $@ $<
+
 libc.a: $(LIBC_OBJS)
 	rm -f $@
 	ar rcs $@ $^
@@ -781,8 +792,38 @@ malloc_test: libc/test_malloc.c libc/malloc_host.o libc/test_host_mem.o
 	gcc -O2 -Wall -Wextra -o $@ libc/test_malloc.c \
 	    libc/malloc_host.o libc/test_host_mem.o
 
-test-libc: malloc_test
+libc/stdio_host.o: libc/stdio.c libc/dtoa.h $(LIBC_HEADERS)
+	gcc -O2 -Wall -Wextra -Ilibc/include -fno-builtin -c -o $@ $<
+
+libc/dtoa_host.o: libc/dtoa.c libc/dtoa.h
+	gcc -O2 -Wall -Wextra -Ilibc/include -fno-builtin -c -o $@ $<
+
+libc/math_host.o: libc/math.c $(LIBC_HEADERS)
+	gcc -O2 -Wall -Wextra -Ilibc/include -fno-builtin -c -o $@ $<
+
+libc/div64_host.o: libc/div64.c
+	gcc -O2 -Wall -Wextra -c -o $@ $<
+
+format_test: libc/test_format.c libc/stdio_host.o libc/dtoa_host.o
+	gcc -O2 -Wall -Wextra -Wno-format-truncation -Ilibc/include -o $@ \
+	    libc/test_format.c libc/stdio_host.o libc/dtoa_host.o
+
+math_test: libc/test_math.c libc/math_host.o
+	gcc -O2 -Wall -Wextra -o $@ libc/test_math.c libc/math_host.o -lm
+
+div64_test: libc/test_div64.c libc/div64_host.o
+	gcc -O2 -Wall -Wextra -o $@ libc/test_div64.c libc/div64_host.o
+
+setjmp_test: libc/test_setjmp.c libc/setjmp.o
+	gcc -m32 -O2 -Wall -Wextra -Ilibc/include -o $@ \
+	    libc/test_setjmp.c libc/setjmp.o
+
+test-libc: malloc_test format_test math_test div64_test setjmp_test
 	./malloc_test
+	./format_test
+	./math_test
+	./div64_test
+	./setjmp_test
 
 mkpack: mkpack.c
 	gcc -O2 -o $@ $<
@@ -1076,4 +1117,4 @@ kernel-net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan

+ 2 - 2
docs/development.html

@@ -177,7 +177,7 @@
 					<tr><td><code>make test-usb</code></td><td>Headless QEMU mouse/keyboard regression tests using QMP and screen dumps.</td></tr>
 					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
 					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
-					<tr><td><code>make test-libc</code></td><td>Host stress test for the ring-3 <code>malloc</code>, realloc, calloc and <code>heap_reset</code>.</td></tr>
+					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>
 					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
 					<tr><td><code>make fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
@@ -261,7 +261,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>USB regression.</strong> <code>make test-usb</code> runs QMP cursor and keyboard tests against UHCI, OHCI, EHCI and xHCI, including hotplug.</li>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
-			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs a deterministic allocation/free/realloc stress test and a browser-like large-buffer sequence; the backend simulates the fixed 32 MB arena and poisons new pages.</li>
+			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (32 MB simulated arena with poisoned pages), exact <code>snprintf</code> float/string checks against the host, x87 math values, the 64-bit division helpers and a 32-bit setjmp/longjmp test.</li>
 			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
 			<li><strong>UEFI.</strong> <code>make test-uefi</code> boots the dual image under OVMF headless and greps the serial log for the boot line.</li>
 			<li><strong>Compositor stats.</strong> The ring-3 WM overwrites <code>/share/wmstats</code> every two seconds with <code>frames</code>, total and worst compositing time in milliseconds, and the pixels drawn in the interval. Read it in a terminal or fetch it over WebDAV to measure a target.</li>

+ 35 - 9
docs/userland.html

@@ -98,7 +98,11 @@
 			<span class="file">libc/include/</span> and cover
 			<code>stddef</code>, <code>stdint</code>, <code>stdarg</code>,
 			<code>stdlib</code>, <code>string</code>, <code>ctype</code>,
-			<code>assert</code> and the OS-specific <code>ucmd_heap.h</code>.
+			<code>assert</code>, <code>setjmp</code>, <code>errno</code>,
+			<code>stdio</code>, <code>math</code>, <code>time</code>,
+			<code>sys/time</code>, <code>sys/types</code>, <code>float</code>,
+			<code>limits</code>, <code>inttypes</code>, <code>alloca</code>
+			and the OS-specific <code>ucmd_heap.h</code>.
 		</p>
 		<ul>
 			<li><strong>malloc.</strong> Boundary-tag blocks, first-fit free
@@ -114,15 +118,37 @@
 			<code>malloc</code>; the <code>SYS_MEM_ALLOC/GROW/FREE</code>
 			syscalls are the backend in <span class="file">libc/ucmd_mem.c</span>
 			and are not called by application code.</li>
+			<li><strong>stdio.</strong> <code>printf</code>,
+			<code>snprintf</code>, <code>sprintf</code> and
+			<code>vfprintf</code> share an exact decimal float formatter
+			(<code>%f/%e/%g</code>, width/precision), and
+			<code>fopen("rb")</code> provides read-only whole-file
+			<code>FILE</code> objects with <code>fread</code>/<code>fseek</code>/
+			<code>ftell</code>/<code>fclose</code>. stdout and stderr are
+			console streams; stdin is EOF. There is no kernel fd layer yet: the
+			<code>stdio_file.c</code> TODO records the future
+			<code>SYS_OPEN/READ/WRITE/LSEEK/CLOSE</code> replacement.</li>
+			<li><strong>time.</strong> <code>time</code>, <code>gmtime</code>,
+			<code>localtime</code>, <code>mktime</code>, <code>strftime</code>,
+			<code>gettimeofday</code>/<code>settimeofday</code> and
+			<code>clock_gettime</code> use <code>SYS_RTC_GET</code>/<code>SET</code>.
+			<code>time_t</code> is 64-bit, local time is UTC-only, and the RTC's
+			1970-2069 range is enforced.</li>
+			<li><strong>math.</strong> The full MuJS set is provided with x87
+			double arithmetic: <code>sqrt</code>, <code>pow</code>,
+			<code>exp</code>/<code>log</code>, trig, <code>floor</code>/<code>ceil</code>/
+			<code>round</code>, <code>fmod</code>, <code>ldexp</code>/
+			<code>frexp</code> and the IEEE predicates. It is a compact
+			double-rounding implementation, not a full fdlibm.</li>
 			<li><strong>Limits.</strong> No threads or locking, no
 			<code>free()</code>-to-page unmap, and requests near 32 MB fail
-			because headers are charged against the same arena. Console
-			<code>printf</code>/<code>FILE</code> I/O is not part of this layer;
-			file access still uses the whole-file syscalls.</li>
-			<li><strong>Test.</strong> <code>make test-libc</code> runs a host
-			stress test over a simulated 32 MB arena, checking alignment,
-			coalescing, <code>realloc</code>/<code>calloc</code>, growth and
-			<code>heap_reset</code>.</li>
+			because headers are charged against the same arena. The file layer
+			is read-only and whole-file (4 MB cap); writable files and streaming
+			need the kernel fd layer. There is no timezone database and no
+			<code>long double</code>/<code>%a</code> support.</li>
+			<li><strong>Tests.</strong> <code>make test-libc</code> covers the
+			malloc arena, format/dtoa, math, 64-bit division helpers and
+			<code>setjmp</code>/<code>longjmp</code> on the host.</li>
 		</ul>
 	</section>
 
@@ -354,7 +380,7 @@
 			<li><code>ucmd_term.c</code> — windowed shell, scrollback, PATH</li>
 			<li><code>terminal.c</code> — privileged kernel command registry</li>
 			<li><code>ucmd_lib.h</code> — user shim</li>
-			<li><code>libc/</code> — headers, malloc, string/stdlib support and the <code>SYS_MEM_*</code> backend</li>
+			<li><code>libc/</code> — headers, malloc, string/stdlib, setjmp/errno, stdio/dtoa, math, time and the <code>SYS_MEM_*</code> backend</li>
 			<li><code>libc.a</code> — optional static ring-3 libc</li>
 			<li><code>ucmd.ld</code> — ring-3 link address</li>
 			<li><code>Makefile</code> — <code>UCMDS</code> and pack rules</li>

+ 114 - 0
libc/div64.c

@@ -0,0 +1,114 @@
+/* Compiler runtime helpers used by MuJS and printf on i386.
+ *
+ * GCC emits these for 64-bit division/modulo when no libgcc is linked. */
+
+typedef unsigned long long u64;
+typedef long long s64;
+
+static u64 udivmod(u64 n, u64 d, u64 *rem)
+{
+	u64 q = 0;
+	int shift = 0;
+	u64 dd = d;
+
+	if (d == 0) {
+		if (rem)
+			*rem = n;
+		return 0;
+	}
+	if (n < d) {
+		if (rem)
+			*rem = n;
+		return 0;
+	}
+
+	while (!(dd & 0x8000000000000000ULL)) {
+		if (dd > n)
+			break;
+		dd <<= 1;
+		shift++;
+	}
+	for (;;) {
+		if (n >= dd) {
+			n -= dd;
+			q |= 1ULL << shift;
+		}
+		if (shift == 0)
+			break;
+		dd >>= 1;
+		shift--;
+	}
+	if (rem)
+		*rem = n;
+	return q;
+}
+
+u64 __udivmoddi4(u64 n, u64 d, u64 *rem)
+{
+	return udivmod(n, d, rem);
+}
+
+u64 __udivdi3(u64 n, u64 d)
+{
+	return udivmod(n, d, 0);
+}
+
+u64 __umoddi3(u64 n, u64 d)
+{
+	u64 r;
+
+	udivmod(n, d, &r);
+	return r;
+}
+
+static u64 absu(s64 v)
+{
+	return v < 0 ? (u64)(-(v + 1)) + 1 : (u64)v;
+}
+
+s64 __divdi3(s64 n, s64 d)
+{
+	u64 q = udivmod(absu(n), absu(d), 0);
+
+	if ((n < 0) != (d < 0))
+		return -(s64)q;
+	return (s64)q;
+}
+
+s64 __moddi3(s64 n, s64 d)
+{
+	u64 r;
+
+	udivmod(absu(n), absu(d), &r);
+	return n < 0 ? -(s64)r : (s64)r;
+}
+
+s64 __divmoddi4(s64 n, s64 d, s64 *rem)
+{
+	u64 r;
+	u64 q = udivmod(absu(n), absu(d), &r);
+
+	if (rem)
+		*rem = n < 0 ? -(s64)r : (s64)r;
+	if ((n < 0) != (d < 0))
+		return -(s64)q;
+	return (s64)q;
+}
+
+/* A few shifts that older/less clever i386 code paths may still call. */
+u64 __ashldi3(u64 v, int n)
+{
+	return n >= 64 ? 0 : v << n;
+}
+
+u64 __lshrdi3(u64 v, int n)
+{
+	return n >= 64 ? 0 : v >> n;
+}
+
+s64 __ashrdi3(s64 v, int n)
+{
+	if (n >= 64)
+		return v < 0 ? -1 : 0;
+	return v >> n;
+}

+ 161 - 0
libc/dtoa.c

@@ -0,0 +1,161 @@
+/* Exact binary-double to decimal decomposition.
+ *
+ * A finite double is m * 2^e.  For e >= 0 it is an integer; for e < 0 we
+ * compute m * 5^(-e) / 10^(-e), so the decimal expansion is exact.  The
+ * result is a digit string plus the decimal-point position.  stdio.c does
+ * precision rounding and the %f/%e/%g layout from this representation. */
+
+#include <string.h>
+#include "dtoa.h"
+
+#define DTOA_LIMBS 128
+
+static void big_zero(unsigned int *a, int *n)
+{
+	int i;
+
+	for (i = 0; i < DTOA_LIMBS; i++)
+		a[i] = 0;
+	*n = 0;
+}
+
+static void big_set_u64(unsigned int *a, int *n, unsigned long long v)
+{
+	big_zero(a, n);
+	a[0] = (unsigned int)v;
+	a[1] = (unsigned int)(v >> 32);
+	*n = a[1] ? 2 : (a[0] ? 1 : 0);
+}
+
+static void big_shl(unsigned int *a, int *n, unsigned int bits)
+{
+	unsigned int words = bits / 32u;
+	unsigned int shift = bits % 32u;
+	int i;
+
+	if (words) {
+		for (i = *n - 1; i >= 0; i--)
+			a[i + words] = a[i];
+		for (i = 0; i < (int)words; i++)
+			a[i] = 0;
+		*n += (int)words;
+	}
+	if (shift) {
+		unsigned long long carry = 0;
+
+		for (i = 0; i < *n; i++) {
+			unsigned long long v =
+				((unsigned long long)a[i] << shift) | carry;
+
+			a[i] = (unsigned int)v;
+			carry = v >> 32;
+		}
+		if (carry && *n < DTOA_LIMBS)
+			a[(*n)++] = (unsigned int)carry;
+	}
+}
+
+static void big_mul5(unsigned int *a, int *n)
+{
+	unsigned long long carry = 0;
+	int i;
+
+	for (i = 0; i < *n; i++) {
+		unsigned long long v = (unsigned long long)a[i] * 5u + carry;
+		a[i] = (unsigned int)v;
+		carry = v >> 32;
+	}
+	if (carry && *n < DTOA_LIMBS)
+		a[(*n)++] = (unsigned int)carry;
+}
+
+/* Divide by 10 in place; returns the remainder. */
+static unsigned int big_div10(unsigned int *a, int *n)
+{
+	unsigned long long rem = 0;
+	int i;
+
+	for (i = *n - 1; i >= 0; i--) {
+		unsigned long long cur = (rem << 32) | a[i];
+		a[i] = (unsigned int)(cur / 10u);
+		rem = cur % 10u;
+	}
+	while (*n > 0 && a[*n - 1] == 0)
+		(*n)--;
+	return (unsigned int)rem;
+}
+
+static int big_to_digits(unsigned int *a, int *n, char *digits, int *point)
+{
+	char rev[LIBC_DTOA_MAX];
+	int len = 0;
+	int i;
+
+	while (*n > 0) {
+		unsigned int d = big_div10(a, n);
+		if (len >= LIBC_DTOA_MAX)
+			break;
+		rev[len++] = (char)('0' + d);
+	}
+	if (len == 0) {
+		digits[0] = '0';
+		*point = 1;
+		return 1;
+	}
+	for (i = 0; i < len; i++)
+		digits[i] = rev[len - 1 - i];
+	*point = len;
+	return len;
+}
+
+int libc_dtoa(double value, struct libc_dtoa *out)
+{
+	union {
+		double d;
+		unsigned long long u;
+	} v;
+	unsigned long long bits;
+	unsigned int exp;
+	unsigned long long mant;
+	int e2;
+	unsigned int a[DTOA_LIMBS];
+	int n;
+	int len;
+
+	v.d = value;
+	bits = v.u;
+	out->neg = (int)(bits >> 63);
+	exp = (unsigned int)((bits >> 52) & 0x7ffu);
+	mant = bits & 0x000fffffffffffffULL;
+
+	if (exp == 0x7ffu)
+		return mant ? 2 : 1;
+
+	if (exp == 0 && mant == 0) {
+		out->digits[0] = '0';
+		out->ndigits = 1;
+		out->point = 1;
+		return 0;
+	}
+
+	if (exp == 0) {
+		e2 = -1074;
+	} else {
+		mant |= 1ULL << 52;
+		e2 = (int)exp - 1023 - 52;
+	}
+
+	big_set_u64(a, &n, mant);
+	if (e2 >= 0) {
+		big_shl(a, &n, (unsigned int)e2);
+		len = big_to_digits(a, &n, out->digits, &out->point);
+	} else {
+		int k = -e2;
+		while (k-- > 0)
+			big_mul5(a, &n);
+		len = big_to_digits(a, &n, out->digits, &out->point);
+		out->point = len + e2;
+	}
+	out->ndigits = len;
+	return 0;
+}

+ 17 - 0
libc/dtoa.h

@@ -0,0 +1,17 @@
+/* Internal exact decimal decomposition for stdio float formatting. */
+#ifndef LIBC_DTOA_H
+#define LIBC_DTOA_H
+
+#define LIBC_DTOA_MAX 1200
+
+struct libc_dtoa {
+	char digits[LIBC_DTOA_MAX];
+	int ndigits;
+	int point;      /* digits to the left of the decimal point */
+	int neg;        /* sign bit, including negative zero */
+};
+
+/* Returns 0 for finite, 1 for infinity and 2 for NaN. */
+int libc_dtoa(double value, struct libc_dtoa *out);
+
+#endif

+ 48 - 0
libc/errno.c

@@ -0,0 +1,48 @@
+/* Global errno and strerror for single-threaded ring-3 commands. */
+
+#include <errno.h>
+
+int errno;
+
+const char *strerror(int err)
+{
+	switch (err) {
+	case 0:            return "Success";
+	case EPERM:        return "Operation not permitted";
+	case ENOENT:       return "No such file or directory";
+	case ESRCH:        return "No such process";
+	case EINTR:        return "Interrupted system call";
+	case EIO:          return "I/O error";
+	case ENXIO:        return "No such device or address";
+	case E2BIG:        return "Argument list too long";
+	case ENOEXEC:      return "Exec format error";
+	case EBADF:        return "Bad file descriptor";
+	case ECHILD:       return "No child processes";
+	case EAGAIN:       return "Resource temporarily unavailable";
+	case ENOMEM:       return "Cannot allocate memory";
+	case EACCES:       return "Permission denied";
+	case EFAULT:       return "Bad address";
+	case EBUSY:        return "Device or resource busy";
+	case EEXIST:       return "File exists";
+	case EXDEV:        return "Invalid cross-device link";
+	case ENODEV:       return "No such device";
+	case ENOTDIR:      return "Not a directory";
+	case EISDIR:       return "Is a directory";
+	case EINVAL:       return "Invalid argument";
+	case ENFILE:       return "Too many open files in system";
+	case EMFILE:       return "Too many open files";
+	case ENOTTY:       return "Inappropriate ioctl for device";
+	case EFBIG:        return "File too large";
+	case ENOSPC:       return "No space left on device";
+	case ESPIPE:       return "Illegal seek";
+	case EROFS:        return "Read-only file system";
+	case EPIPE:        return "Broken pipe";
+	case EDOM:         return "Numerical argument out of domain";
+	case ERANGE:       return "Numerical result out of range";
+	case ENOSYS:       return "Function not implemented";
+	case EOVERFLOW:    return "Value too large for defined data type";
+	case EOPNOTSUPP:   return "Operation not supported";
+	case ENAMETOOLONG: return "File name too long";
+	default:           return "Unknown error";
+	}
+}

+ 6 - 0
libc/include/alloca.h

@@ -0,0 +1,6 @@
+#ifndef LIBC_ALLOCA_H
+#define LIBC_ALLOCA_H
+
+#define alloca(size) __builtin_alloca(size)
+
+#endif

+ 43 - 0
libc/include/errno.h

@@ -0,0 +1,43 @@
+/* Linux-compatible errno values for ring-3 commands. */
+#ifndef LIBC_ERRNO_H
+#define LIBC_ERRNO_H
+
+extern int errno;
+
+#define EPERM            1
+#define ENOENT           2
+#define ESRCH            3
+#define EINTR            4
+#define EIO              5
+#define ENXIO            6
+#define E2BIG            7
+#define ENOEXEC          8
+#define EBADF            9
+#define ECHILD          10
+#define EAGAIN          11
+#define ENOMEM          12
+#define EACCES          13
+#define EFAULT          14
+#define EBUSY           16
+#define EEXIST          17
+#define EXDEV           18
+#define ENODEV          19
+#define ENOTDIR         20
+#define EISDIR          21
+#define EINVAL          22
+#define ENFILE          23
+#define EMFILE          24
+#define ENOTTY          25
+#define EFBIG           27
+#define ENOSPC          28
+#define ESPIPE          29
+#define EROFS           30
+#define EPIPE           32
+#define EDOM            33
+#define ERANGE          34
+#define ENOSYS          38
+#define EOVERFLOW       75
+#define EOPNOTSUPP      95
+#define ENAMETOOLONG    36
+
+#endif

+ 26 - 0
libc/include/float.h

@@ -0,0 +1,26 @@
+/* Minimal float.h for the ring-3 libc (i386 double). */
+#ifndef LIBC_FLOAT_H
+#define LIBC_FLOAT_H
+
+#define DBL_MANT_DIG     53
+#define DBL_DIG          15
+#define DBL_MIN_EXP      (-1021)
+#define DBL_MAX_EXP      1024
+#define DBL_MIN_10_EXP   (-307)
+#define DBL_MAX_10_EXP   308
+#define DBL_MAX          1.7976931348623157e+308
+#define DBL_MIN          2.2250738585072014e-308
+#define DBL_EPSILON      2.2204460492503131e-16
+#define DBL_TRUE_MIN     4.9406564584124654e-324
+
+#define FLT_MANT_DIG     24
+#define FLT_DIG          6
+#define FLT_MIN_EXP      (-125)
+#define FLT_MAX_EXP      128
+#define FLT_MIN_10_EXP   (-37)
+#define FLT_MAX_10_EXP   38
+#define FLT_MAX          3.402823466e+38F
+#define FLT_MIN          1.175494351e-38F
+#define FLT_EPSILON      1.192092896e-07F
+
+#endif

+ 35 - 0
libc/include/inttypes.h

@@ -0,0 +1,35 @@
+/* Minimal inttypes.h for ring-3 commands. */
+#ifndef LIBC_INTTYPES_H
+#define LIBC_INTTYPES_H
+
+#include <stdint.h>
+
+#define PRId8  "d"
+#define PRIi8  "i"
+#define PRIu8  "u"
+#define PRIx8  "x"
+#define PRIX8  "X"
+#define PRId16 "d"
+#define PRIi16 "i"
+#define PRIu16 "u"
+#define PRIx16 "x"
+#define PRIX16 "X"
+#define PRId32 "d"
+#define PRIi32 "i"
+#define PRIu32 "u"
+#define PRIx32 "x"
+#define PRIX32 "X"
+#define PRId64 "lld"
+#define PRIi64 "lli"
+#define PRIu64 "llu"
+#define PRIx64 "llx"
+#define PRIX64 "llX"
+#define PRIdPTR "d"
+#define PRIuPTR "u"
+#define PRIxPTR "x"
+
+intmax_t imaxabs(intmax_t value);
+intmax_t strtoimax(const char *str, char **endptr, int base);
+uintmax_t strtoumax(const char *str, char **endptr, int base);
+
+#endif

+ 28 - 0
libc/include/limits.h

@@ -0,0 +1,28 @@
+/* Minimal limits.h for the ring-3 libc (i386). */
+#ifndef LIBC_LIMITS_H
+#define LIBC_LIMITS_H
+
+#define CHAR_BIT         8
+#define SCHAR_MIN        (-128)
+#define SCHAR_MAX        127
+#define UCHAR_MAX        255
+#define CHAR_MIN        SCHAR_MIN
+#define CHAR_MAX        SCHAR_MAX
+#define SHRT_MIN         (-32768)
+#define SHRT_MAX         32767
+#define USHRT_MAX        65535
+#define INT_MIN          (-2147483647 - 1)
+#define INT_MAX          2147483647
+#define UINT_MAX         4294967295u
+#define LONG_MIN         (-2147483647L - 1L)
+#define LONG_MAX         2147483647L
+#define ULONG_MAX        4294967295uL
+#define LLONG_MIN        (-9223372036854775807LL - 1LL)
+#define LLONG_MAX        9223372036854775807LL
+#define ULLONG_MAX       18446744073709551615ULL
+
+#define PATH_MAX         64
+#define NAME_MAX         63
+#define OPEN_MAX         32
+
+#endif

+ 54 - 0
libc/include/math.h

@@ -0,0 +1,54 @@
+/* Minimal C99 math interface for the ring-3 libc. */
+#ifndef LIBC_MATH_H
+#define LIBC_MATH_H
+
+#include <float.h>
+
+#define INFINITY  (__builtin_inf())
+#define NAN       (__builtin_nan(""))
+#define HUGE_VAL  (__builtin_huge_val())
+
+#define isnan(x)    __builtin_isnan(x)
+#define isinf(x)    __builtin_isinf(x)
+#define isfinite(x) __builtin_isfinite(x)
+#define signbit(x)  __builtin_signbit(x)
+
+#define fpclassify(x) \
+	(__builtin_isnan(x) ? 0 : __builtin_isinf(x) ? 1 : \
+	 (x) == 0 ? 2 : __builtin_isnormal(x) ? 4 : 3)
+#define FP_NAN       0
+#define FP_INFINITE  1
+#define FP_ZERO      2
+#define FP_SUBNORMAL 3
+#define FP_NORMAL    4
+#define isnormal(x)  __builtin_isnormal(x)
+
+double fabs(double x);
+double floor(double x);
+double ceil(double x);
+double trunc(double x);
+double round(double x);
+double fmod(double x, double y);
+double sqrt(double x);
+
+double pow(double x, double y);
+double exp(double x);
+double log(double x);
+double log10(double x);
+
+double sin(double x);
+double cos(double x);
+double tan(double x);
+double asin(double x);
+double acos(double x);
+double atan(double x);
+double atan2(double y, double x);
+
+double fmin(double x, double y);
+double fmax(double x, double y);
+double copysign(double x, double y);
+double ldexp(double x, int exp);
+double frexp(double x, int *exp);
+double modf(double x, double *iptr);
+
+#endif

+ 11 - 0
libc/include/setjmp.h

@@ -0,0 +1,11 @@
+/* Minimal i386 setjmp/longjmp for the ring-3 libc. */
+#ifndef LIBC_SETJMP_H
+#define LIBC_SETJMP_H
+
+/* ebx, esi, edi, ebp, esp, eip */
+typedef unsigned int jmp_buf[6];
+
+int setjmp(jmp_buf env) __attribute__((returns_twice));
+void longjmp(jmp_buf env, int value) __attribute__((noreturn));
+
+#endif

+ 1 - 0
libc/include/stddef.h

@@ -5,6 +5,7 @@
 typedef __SIZE_TYPE__ size_t;
 typedef __PTRDIFF_TYPE__ ptrdiff_t;
 typedef __WCHAR_TYPE__ wchar_t;
+typedef long double max_align_t;
 
 #ifndef NULL
 #define NULL ((void *)0)

+ 60 - 0
libc/include/stdio.h

@@ -0,0 +1,60 @@
+/* Minimal stdio for ring-3 commands.
+ *
+ * The file layer is read-only and whole-file for now; see libc/stdio_file.c
+ * for the fd-layer TODO.  stdout/stderr are console streams.
+ */
+#ifndef LIBC_STDIO_H
+#define LIBC_STDIO_H
+
+#include <stddef.h>
+#include <stdarg.h>
+
+typedef struct __libc_file FILE;
+
+extern FILE *stdin;
+extern FILE *stdout;
+extern FILE *stderr;
+
+#define EOF (-1)
+
+#define SEEK_SET 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+
+#define _IOFBF 0
+#define _IOLBF 1
+#define _IONBF 2
+
+int printf(const char *format, ...);
+int vprintf(const char *format, va_list ap);
+int fprintf(FILE *stream, const char *format, ...);
+int vfprintf(FILE *stream, const char *format, va_list ap);
+int sprintf(char *buf, const char *format, ...);
+int snprintf(char *buf, size_t size, const char *format, ...);
+int vsprintf(char *buf, const char *format, va_list ap);
+int vsnprintf(char *buf, size_t size, const char *format, va_list ap);
+
+int puts(const char *s);
+int fputs(const char *s, FILE *stream);
+int putchar(int c);
+int fputc(int c, FILE *stream);
+int fgetc(FILE *stream);
+int getchar(void);
+char *fgets(char *s, int size, FILE *stream);
+
+FILE *fopen(const char *path, const char *mode);
+int fclose(FILE *stream);
+size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
+size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
+int fseek(FILE *stream, long offset, int whence);
+long ftell(FILE *stream);
+void rewind(FILE *stream);
+int fflush(FILE *stream);
+int feof(FILE *stream);
+int ferror(FILE *stream);
+void clearerr(FILE *stream);
+int fileno(FILE *stream);
+
+void perror(const char *s);
+
+#endif

+ 2 - 0
libc/include/stdlib.h

@@ -10,6 +10,8 @@ void *calloc(size_t nmemb, size_t size);
 void *realloc(void *ptr, size_t size);
 
 int abs(int value);
+int atoi(const char *str);
+long atol(const char *str);
 long strtol(const char *str, char **endptr, int base);
 void qsort(void *base, size_t nmemb, size_t size,
 	   int (*compar)(const void *, const void *));

+ 1 - 0
libc/include/string.h

@@ -19,5 +19,6 @@ char *strchr(const char *s, int c);
 char *strrchr(const char *s, int c);
 char *strstr(const char *haystack, const char *needle);
 char *strdup(const char *s);
+const char *strerror(int errnum);
 
 #endif

+ 14 - 0
libc/include/sys/time.h

@@ -0,0 +1,14 @@
+#ifndef LIBC_SYS_TIME_H
+#define LIBC_SYS_TIME_H
+
+#include <sys/types.h>
+
+struct timeval {
+	time_t tv_sec;
+	suseconds_t tv_usec;
+};
+
+int gettimeofday(struct timeval *tv, void *tz);
+int settimeofday(const struct timeval *tv, const void *tz);
+
+#endif

+ 22 - 0
libc/include/sys/types.h

@@ -0,0 +1,22 @@
+/* Basic POSIX types for the ring-3 libc. */
+#ifndef LIBC_SYS_TYPES_H
+#define LIBC_SYS_TYPES_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+typedef int ssize_t;
+typedef long off_t;
+typedef long long time_t;
+typedef int pid_t;
+typedef unsigned int uid_t;
+typedef unsigned int gid_t;
+typedef unsigned int mode_t;
+typedef unsigned int dev_t;
+typedef unsigned int ino_t;
+typedef unsigned int nlink_t;
+typedef long blksize_t;
+typedef long blkcnt_t;
+typedef long suseconds_t;
+
+#endif

+ 45 - 0
libc/include/time.h

@@ -0,0 +1,45 @@
+/* Wall-clock time for ring-3 commands (UTC only). */
+#ifndef LIBC_TIME_H
+#define LIBC_TIME_H
+
+#include <stddef.h>
+#include <sys/types.h>
+
+struct tm {
+	int tm_sec;
+	int tm_min;
+	int tm_hour;
+	int tm_mday;
+	int tm_mon;
+	int tm_year;
+	int tm_wday;
+	int tm_yday;
+	int tm_isdst;
+};
+
+#define CLOCKS_PER_SEC 1000
+typedef long clock_t;
+
+#define CLOCK_REALTIME  0
+#define CLOCK_MONOTONIC 1
+
+struct timespec {
+	time_t tv_sec;
+	long tv_nsec;
+};
+
+time_t time(time_t *tloc);
+struct tm *gmtime(const time_t *timer);
+struct tm *localtime(const time_t *timer);
+time_t mktime(struct tm *tm);
+size_t strftime(char *s, size_t max, const char *format,
+		const struct tm *tm);
+char *ctime(const time_t *timer);
+char *asctime(const struct tm *tm);
+double difftime(time_t time1, time_t time0);
+
+int clock_gettime(int clock_id, struct timespec *tp);
+int clock_settime(int clock_id, const struct timespec *tp);
+int nanosleep(const struct timespec *req, struct timespec *rem);
+
+#endif

+ 320 - 0
libc/math.c

@@ -0,0 +1,320 @@
+/* x87-backed math for the ring-3 libc.
+ *
+ * The target is i586 with -mno-sse, so double arithmetic is x87 anyway.  The
+ * transcendental routines use the x87 instructions with an explicit range
+ * reduction for the trigonometric functions.  Accuracy is a double-rounding
+ * compromise, not a full fdlibm port. */
+
+#include <math.h>
+#include <float.h>
+
+#define PI      3.14159265358979323846
+#define LOG2E   1.44269504088896340736
+#define LN2     0.69314718055994530942
+
+static double round_mode(double x, unsigned int mode)
+{
+	unsigned short cw, old;
+	double r;
+
+	if (__builtin_isnan(x) || __builtin_isinf(x) || x == 0.0)
+		return x;
+	__asm__ volatile ("fnstcw %0" : "=m"(cw));
+	old = cw;
+	cw = (unsigned short)((cw & ~0x0C00u) | (mode << 10));
+	__asm__ volatile ("fldcw %0" : : "m"(cw));
+	__asm__ volatile ("fldl %1; frndint; fstpl %0" : "=m"(r) : "m"(x));
+	__asm__ volatile ("fldcw %0" : : "m"(old));
+	return r;
+}
+
+double fabs(double x)
+{
+	union {
+		double d;
+		unsigned long long u;
+	} v;
+
+	v.d = x;
+	v.u &= 0x7fffffffffffffffULL;
+	return v.d;
+}
+
+double floor(double x)
+{
+	return round_mode(x, 1);
+}
+
+double ceil(double x)
+{
+	return round_mode(x, 2);
+}
+
+double trunc(double x)
+{
+	return round_mode(x, 3);
+}
+
+double round(double x)
+{
+	if (__builtin_isnan(x) || __builtin_isinf(x))
+		return x;
+	/* Above 2^52 every double is already an integer. */
+	if (fabs(x) >= 4503599627370496.0)
+		return x;
+	if (x >= 0.0)
+		return floor(x + 0.5);
+	return ceil(x - 0.5);
+}
+
+double sqrt(double x)
+{
+	double r;
+
+	__asm__ volatile ("fldl %1; fsqrt; fstpl %0" : "=m"(r) : "m"(x));
+	return r;
+}
+
+double fmod(double x, double y)
+{
+	double r;
+
+	__asm__ volatile (
+		"fldl %2\n\t"
+		"fldl %1\n\t"
+		"1:\n\t"
+		"fprem\n\t"
+		"fnstsw %%ax\n\t"
+		"testw $0x400, %%ax\n\t"
+		"jnz 1b\n\t"
+		"fstp %%st(1)\n\t"
+		"fstpl %0"
+		: "=m"(r) : "m"(x), "m"(y) : "ax");
+	return r;
+}
+
+double log(double x)
+{
+	double r;
+
+	__asm__ volatile ("fldln2; fldl %1; fyl2x; fstpl %0"
+			  : "=m"(r) : "m"(x));
+	return r;
+}
+
+double log10(double x)
+{
+	double r;
+
+	__asm__ volatile ("fldlg2; fldl %1; fyl2x; fstpl %0"
+			  : "=m"(r) : "m"(x));
+	return r;
+}
+
+double ldexp(double x, int exp)
+{
+	double r;
+
+	__asm__ volatile (
+		"fildl %1\n\t"
+		"fldl %2\n\t"
+		"fscale\n\t"
+		"fstp %%st(1)\n\t"
+		"fstpl %0"
+		: "=m"(r) : "m"(exp), "m"(x));
+	return r;
+}
+
+double exp(double x)
+{
+	double y, n, f, p;
+
+	if (__builtin_isnan(x))
+		return x;
+	if (x > 709.782712893384)
+		return INFINITY;
+	if (x < -745.133219101941)
+		return 0.0;
+
+	y = x * LOG2E;
+	n = floor(y);
+	f = y - n;
+	__asm__ volatile ("fldl %1; f2xm1; fld1; faddp; fstpl %0"
+			  : "=m"(p) : "m"(f));
+	return ldexp(p, (int)n);
+}
+
+double pow(double x, double y)
+{
+	int neg = 0;
+	double r;
+
+	if (y == 0.0)
+		return 1.0;
+	if (x == 1.0)
+		return 1.0;
+	if (__builtin_isnan(x) || __builtin_isnan(y))
+		return NAN;
+	if (x == 0.0) {
+		if (y < 0.0)
+			return INFINITY;
+		return 0.0;
+	}
+	if (x < 0.0) {
+		double yi = floor(y);
+
+		if (yi != y)
+			return NAN;
+		x = -x;
+		if (fmod(yi, 2.0) != 0.0)
+			neg = 1;
+	}
+
+	/* Small integer powers are common in JavaScript and stay exact. */
+	if (y == floor(y) && y >= -64.0 && y <= 64.0) {
+		int n = (int)y;
+		int e = n < 0 ? -n : n;
+
+		r = 1.0;
+		while (e) {
+			if (e & 1)
+				r *= x;
+			x *= x;
+			e >>= 1;
+		}
+		if (n < 0)
+			r = 1.0 / r;
+	} else {
+		r = exp(y * log(x));
+	}
+	return neg ? -r : r;
+}
+
+double sin(double x)
+{
+	double r;
+
+	/* The x87 reduction uses a 66-bit pi internally; pre-reducing with a
+	 * double 2*pi would lose more phase for large arguments. */
+	__asm__ volatile ("fldl %1; fsin; fstpl %0" : "=m"(r) : "m"(x));
+	return r;
+}
+
+double cos(double x)
+{
+	double r;
+
+	__asm__ volatile ("fldl %1; fcos; fstpl %0" : "=m"(r) : "m"(x));
+	return r;
+}
+
+double tan(double x)
+{
+	double r;
+
+	__asm__ volatile ("fldl %1; fptan; fstp %%st(0); fstpl %0"
+			  : "=m"(r) : "m"(x));
+	return r;
+}
+
+double atan(double x)
+{
+	double r;
+
+	__asm__ volatile ("fldl %1; fld1; fpatan; fstpl %0"
+			  : "=m"(r) : "m"(x));
+	return r;
+}
+
+double atan2(double y, double x)
+{
+	double r;
+
+	__asm__ volatile ("fldl %1; fldl %2; fpatan; fstpl %0"
+			  : "=m"(r) : "m"(y), "m"(x));
+	return r;
+}
+
+double asin(double x)
+{
+	if (x > 1.0 || x < -1.0)
+		return NAN;
+	return atan2(x, sqrt(1.0 - x * x));
+}
+
+double acos(double x)
+{
+	if (x > 1.0 || x < -1.0)
+		return NAN;
+	return atan2(sqrt(1.0 - x * x), x);
+}
+
+double fmin(double x, double y)
+{
+	if (__builtin_isnan(x))
+		return y;
+	if (__builtin_isnan(y))
+		return x;
+	return x < y ? x : y;
+}
+
+double fmax(double x, double y)
+{
+	if (__builtin_isnan(x))
+		return y;
+	if (__builtin_isnan(y))
+		return x;
+	return x > y ? x : y;
+}
+
+double copysign(double x, double y)
+{
+	union {
+		double d;
+		unsigned long long u;
+	} a, b;
+
+	a.d = x;
+	b.d = y;
+	a.u = (a.u & 0x7fffffffffffffffULL) |
+	      (b.u & 0x8000000000000000ULL);
+	return a.d;
+}
+
+double frexp(double x, int *exp)
+{
+	union {
+		double d;
+		unsigned long long u;
+	} v;
+	unsigned long long bits;
+	unsigned int e;
+	int extra = 0;
+
+	if (__builtin_isnan(x) || __builtin_isinf(x) || x == 0.0) {
+		if (exp)
+			*exp = 0;
+		return x;
+	}
+	if (fabs(x) < DBL_MIN) {
+		x *= 18446744073709551616.0; /* 2^64 */
+		extra = 64;
+	}
+	v.d = x;
+	bits = v.u;
+	e = (unsigned int)((bits >> 52) & 0x7ffu);
+	if (exp)
+		*exp = (int)e - 1022 - extra;
+	bits = (bits & 0x800fffffffffffffULL) | (1022ULL << 52);
+	v.u = bits;
+	return v.d;
+}
+
+double modf(double x, double *iptr)
+{
+	double ip = trunc(x);
+
+	if (iptr)
+		*iptr = ip;
+	return x - ip;
+}

+ 41 - 0
libc/setjmp.S

@@ -0,0 +1,41 @@
+/* i386 setjmp/longjmp for the ring-3 libc.
+ *
+ * jmp_buf layout: ebx, esi, edi, ebp, esp, eip.
+ * setjmp saves the stack pointer after its own return address, so longjmp
+ * resumes as if setjmp had returned with a nonzero value. */
+
+	.text
+	.globl setjmp
+	.type setjmp, @function
+setjmp:
+	movl	4(%esp), %eax
+	movl	%ebx, 0(%eax)
+	movl	%esi, 4(%eax)
+	movl	%edi, 8(%eax)
+	movl	%ebp, 12(%eax)
+	leal	4(%esp), %ecx
+	movl	%ecx, 16(%eax)
+	movl	0(%esp), %ecx
+	movl	%ecx, 20(%eax)
+	xorl	%eax, %eax
+	ret
+	.size setjmp, .-setjmp
+
+	.globl longjmp
+	.type longjmp, @function
+longjmp:
+	movl	4(%esp), %edx
+	movl	8(%esp), %eax
+	testl	%eax, %eax
+	jne	1f
+	movl	$1, %eax
+1:
+	movl	0(%edx), %ebx
+	movl	4(%edx), %esi
+	movl	8(%edx), %edi
+	movl	12(%edx), %ebp
+	movl	16(%edx), %esp
+	jmp	*20(%edx)
+	.size longjmp, .-longjmp
+
+	.section .note.GNU-stack,"",@progbits

+ 730 - 0
libc/stdio.c

@@ -0,0 +1,730 @@
+/* Formatted output for the ring-3 libc.
+ *
+ * The formatting core is syscall-free; stdio_file.c supplies console streams
+ * and read-only whole-file FILE objects.  Float formatting uses the exact
+ * decimal decomposition in dtoa.c, then rounds at the requested precision. */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <math.h>
+#include "dtoa.h"
+
+#define F_LEFT  0x01
+#define F_PLUS  0x02
+#define F_SPACE 0x04
+#define F_HASH  0x08
+#define F_ZERO  0x10
+
+struct out {
+	char *buf;
+	size_t cap;
+	size_t len;
+};
+
+static void out_char(struct out *o, char c)
+{
+	if (o->buf && o->len < o->cap)
+		o->buf[o->len] = c;
+	o->len++;
+}
+
+static void out_mem(struct out *o, const char *s, size_t n)
+{
+	size_t i;
+
+	for (i = 0; i < n; i++)
+		out_char(o, s[i]);
+}
+
+static int utoa_base(unsigned long long v, unsigned int base, int upper,
+		     char *buf)
+{
+	static const char low[] = "0123456789abcdef";
+	static const char up[] = "0123456789ABCDEF";
+	const char *digits = upper ? up : low;
+	char tmp[66];
+	int n = 0;
+	int i;
+
+	do {
+		tmp[n++] = digits[v % base];
+		v /= base;
+	} while (v);
+	for (i = 0; i < n; i++)
+		buf[i] = tmp[n - 1 - i];
+	buf[n] = '\0';
+	return n;
+}
+
+static void emit_padded(struct out *o, const char *s, int len, int width,
+			int flags, int numeric)
+{
+	int pad = width > len ? width - len : 0;
+	int i;
+	int sign = 0;
+
+	if (numeric && len > 0 && (s[0] == '-' || s[0] == '+' || s[0] == ' '))
+		sign = 1;
+
+	if (!(flags & F_LEFT)) {
+		if ((flags & F_ZERO) && numeric) {
+			for (i = 0; i < sign; i++)
+				out_char(o, s[i]);
+			for (i = 0; i < pad; i++)
+				out_char(o, '0');
+			out_mem(o, s + sign, (size_t)(len - sign));
+			return;
+		}
+		for (i = 0; i < pad; i++)
+			out_char(o, ' ');
+	}
+	out_mem(o, s, (size_t)len);
+	if (flags & F_LEFT) {
+		for (i = 0; i < pad; i++)
+			out_char(o, ' ');
+	}
+}
+
+/* Round a digit string to `keep` digits.  Returns the new length and sets
+ * *carry when a leading '1' was inserted. */
+static int round_digits(char *d, int n, int keep, int *carry)
+{
+	int next;
+	int up = 0;
+	int i;
+
+	*carry = 0;
+	if (keep >= n)
+		return n;
+	if (keep < 0)
+		keep = 0;
+
+	next = d[keep];
+	if (next > '5') {
+		up = 1;
+	} else if (next == '5') {
+		int nonzero = 0;
+
+		for (i = keep + 1; i < n; i++) {
+			if (d[i] != '0') {
+				nonzero = 1;
+				break;
+			}
+		}
+		if (nonzero)
+			up = 1;
+		else if (keep > 0 && ((d[keep - 1] - '0') & 1))
+			up = 1;
+	}
+
+	n = keep;
+	if (!up)
+		return n;
+	i = n - 1;
+	while (i >= 0 && d[i] == '9') {
+		d[i] = '0';
+		i--;
+	}
+	if (i >= 0) {
+		d[i]++;
+	} else {
+		memmove(d + 1, d, (size_t)n);
+		d[0] = '1';
+		n++;
+		*carry = 1;
+	}
+	return n;
+}
+
+static void prepend_zeros(char *d, int *n, int count)
+{
+	if (count <= 0)
+		return;
+	if (*n + count > LIBC_DTOA_MAX)
+		count = LIBC_DTOA_MAX - *n;
+	if (count <= 0)
+		return;
+	memmove(d + count, d, (size_t)*n);
+	memset(d, '0', (size_t)count);
+	*n += count;
+}
+
+static void format_fixed(const struct libc_dtoa *dt, int prec, int hash,
+			 char *body, int *blen)
+{
+	char d[LIBC_DTOA_MAX];
+	int n = dt->ndigits;
+	int point = dt->point;
+	int keep;
+	int carry = 0;
+
+	if (prec > LIBC_DTOA_MAX - 8)
+		prec = LIBC_DTOA_MAX - 8;
+	memcpy(d, dt->digits, (size_t)n);
+
+	if (point < 0) {
+		prepend_zeros(d, &n, -point);
+		point = 0;
+	}
+	if (point > n) {
+		if (point + prec > LIBC_DTOA_MAX)
+			point = LIBC_DTOA_MAX - prec - 1;
+		while (n < point)
+			d[n++] = '0';
+	}
+	keep = point + prec;
+	if (keep > LIBC_DTOA_MAX - 2)
+		keep = LIBC_DTOA_MAX - 2;
+	while (n < keep)
+		d[n++] = '0';
+	if (keep < n)
+		n = round_digits(d, n, keep, &carry);
+	if (carry)
+		point++;
+
+	{
+		int i = 0;
+
+		if (point == 0) {
+			body[i++] = '0';
+		} else {
+			int j;
+
+			for (j = 0; j < point; j++)
+				body[i++] = (j < n) ? d[j] : '0';
+		}
+		if (prec > 0 || hash) {
+			body[i++] = '.';
+			for (int j = 0; j < prec; j++)
+				body[i++] = (point + j < n) ? d[point + j] : '0';
+		}
+		body[i] = '\0';
+		*blen = i;
+	}
+}
+
+static void format_exp(const struct libc_dtoa *dt, int prec, int hash,
+		       char *body, int *blen)
+{
+	char d[LIBC_DTOA_MAX];
+	int n = dt->ndigits;
+	int point = dt->point;
+	int keep;
+	int carry;
+	int exp10 = point - 1;
+	int i;
+	char *p = body;
+
+	if (prec < 0)
+		prec = 0;
+	if (prec > 900)
+		prec = 900;
+	keep = prec + 1;
+	if (keep > LIBC_DTOA_MAX - 2)
+		keep = LIBC_DTOA_MAX - 2;
+	memcpy(d, dt->digits, (size_t)n);
+	while (n < keep)
+		d[n++] = '0';
+	if (keep < n)
+		n = round_digits(d, n, keep, &carry);
+	else
+		carry = 0;
+	if (carry) {
+		exp10++;
+		n = keep;
+	}
+
+	*p++ = d[0];
+	if (prec > 0 || hash) {
+		*p++ = '.';
+		for (i = 1; i <= prec; i++)
+			*p++ = (i < n) ? d[i] : '0';
+	}
+	*p++ = 'e';
+	{
+		int e = exp10;
+		if (e < 0) {
+			*p++ = '-';
+			e = -e;
+		} else {
+			*p++ = '+';
+		}
+		if (e >= 100) {
+			*p++ = (char)('0' + (e / 100) % 10);
+			*p++ = (char)('0' + (e / 10) % 10);
+			*p++ = (char)('0' + e % 10);
+		} else {
+			*p++ = (char)('0' + (e / 10) % 10);
+			*p++ = (char)('0' + e % 10);
+		}
+	}
+	*p = '\0';
+	*blen = (int)(p - body);
+}
+
+static void strip_float_zeros(char *body, int *len)
+{
+	char *e = strchr(body, 'e');
+	char *dot = strchr(body, '.');
+	char *end = e ? e : body + *len;
+
+	if (!dot)
+		return;
+	while (end > dot && end[-1] == '0')
+		end--;
+	if (end > body && end[-1] == '.')
+		end--;
+	if (e) {
+		int tail = (int)(*len - (e - body));
+
+		if (end != e)
+			memmove(end, e, (size_t)tail + 1);
+		*len = (int)(end - body) + tail;
+	} else {
+		*len = (int)(end - body);
+		body[*len] = '\0';
+	}
+}
+
+static int significant_exp10(const struct libc_dtoa *dt, int prec)
+{
+	char d[LIBC_DTOA_MAX];
+	int n = dt->ndigits;
+	int carry;
+
+	if (prec < 1)
+		prec = 1;
+	if (n > prec) {
+		memcpy(d, dt->digits, (size_t)n);
+		n = round_digits(d, n, prec, &carry);
+		if (carry)
+			return dt->point;
+	}
+	return dt->point - 1;
+}
+
+static void format_double(struct out *o, double value, char conv,
+			  int prec, int flags, int width)
+{
+	struct libc_dtoa dt;
+	char body[LIBC_DTOA_MAX + 96];
+	char num[LIBC_DTOA_MAX + 100];
+	int blen = 0;
+	int n;
+	int sign;
+	int cls;
+	int body_start;
+
+	cls = libc_dtoa(value, &dt);
+	if (cls == 1) {
+		blen = 3;
+		memcpy(body, "inf", 4);
+		sign = dt.neg;
+	} else if (cls == 2) {
+		blen = 3;
+		memcpy(body, "nan", 4);
+		sign = dt.neg;
+	} else {
+		sign = dt.neg;
+		if (prec < 0)
+			prec = 6;
+		if (prec > 900)
+			prec = 900;
+		if (conv == 'f' || conv == 'F') {
+			format_fixed(&dt, prec, (flags & F_HASH) != 0, body, &blen);
+		} else if (conv == 'e' || conv == 'E') {
+			format_exp(&dt, prec, (flags & F_HASH) != 0, body, &blen);
+		} else {
+			int p = prec;
+			int exp10;
+
+			if (p == 0)
+				p = 1;
+			exp10 = significant_exp10(&dt, p);
+			if (exp10 < -4 || exp10 >= p) {
+				format_exp(&dt, p - 1, (flags & F_HASH) != 0,
+					   body, &blen);
+			} else {
+				int fp = p - (exp10 + 1);
+				if (fp < 0)
+					fp = 0;
+				format_fixed(&dt, fp, (flags & F_HASH) != 0,
+					     body, &blen);
+			}
+			if (!(flags & F_HASH))
+				strip_float_zeros(body, &blen);
+		}
+	}
+
+	body_start = 0;
+	if (sign) {
+		num[0] = '-';
+		body_start = 1;
+	} else if (flags & F_PLUS) {
+		num[0] = '+';
+		body_start = 1;
+	} else if (flags & F_SPACE) {
+		num[0] = ' ';
+		body_start = 1;
+	}
+	memcpy(num + body_start, body, (size_t)blen + 1);
+	n = body_start + blen;
+
+	/* Uppercase E/Inf/NaN for the uppercase conversions. */
+	if (conv == 'E' || conv == 'F' || conv == 'G') {
+		for (int i = body_start; i < n; i++) {
+			if (num[i] == 'e')
+				num[i] = 'E';
+			else if (num[i] == 'n')
+				num[i] = 'N';
+			else if (num[i] == 'i')
+				num[i] = 'I';
+		}
+	}
+	emit_padded(o, num, n, width, flags, 1);
+}
+
+int vsnprintf(char *buf, size_t size, const char *format, va_list ap)
+{
+	struct out o;
+	const char *p;
+
+	o.buf = (buf && size) ? buf : 0;
+	o.cap = (buf && size) ? size : 0;
+	o.len = 0;
+
+	for (p = format; *p; p++) {
+		int flags = 0;
+		int width = 0;
+		int prec = -1;
+		int len = -1;
+		char conv;
+
+		if (*p != '%') {
+			out_char(&o, *p);
+			continue;
+		}
+		p++;
+		for (;;) {
+			if (*p == '-') flags |= F_LEFT;
+			else if (*p == '+') flags |= F_PLUS;
+			else if (*p == ' ') flags |= F_SPACE;
+			else if (*p == '#') flags |= F_HASH;
+			else if (*p == '0') flags |= F_ZERO;
+			else break;
+			p++;
+		}
+		if (*p == '*') {
+			width = va_arg(ap, int);
+			if (width < 0) {
+				flags |= F_LEFT;
+				width = -width;
+			}
+			p++;
+		} else {
+			while (*p >= '0' && *p <= '9') {
+				width = width * 10 + (*p - '0');
+				p++;
+			}
+		}
+		if (*p == '.') {
+			p++;
+			if (*p == '*') {
+				prec = va_arg(ap, int);
+				if (prec < 0)
+					prec = -1;
+				p++;
+			} else {
+				prec = 0;
+				while (*p >= '0' && *p <= '9') {
+					prec = prec * 10 + (*p - '0');
+					p++;
+				}
+			}
+		}
+		if (*p == 'h') {
+			p++;
+			if (*p == 'h') {
+				len = 0;
+				p++;
+			} else {
+				len = 1;
+			}
+		} else if (*p == 'l') {
+			p++;
+			if (*p == 'l') {
+				len = 3;
+				p++;
+			} else {
+				len = 2;
+			}
+		} else if (*p == 'z') {
+			len = 4;
+			p++;
+		} else if (*p == 't') {
+			len = 5;
+			p++;
+		} else if (*p == 'j') {
+			len = 6;
+			p++;
+		} else if (*p == 'L') {
+			len = 7;
+			p++;
+		}
+
+		conv = *p;
+		if (!conv)
+			break;
+
+		if (conv == '%') {
+			out_char(&o, '%');
+			continue;
+		}
+		if (conv == 'c') {
+			char c = (char)va_arg(ap, int);
+			char s[2];
+			s[0] = c;
+			s[1] = '\0';
+			emit_padded(&o, s, 1, width, flags & ~F_ZERO, 0);
+			continue;
+		}
+		if (conv == 's') {
+			const char *s = va_arg(ap, const char *);
+			int n = 0;
+			if (!s)
+				s = "(null)";
+			while (s[n] && (prec < 0 || n < prec))
+				n++;
+			emit_padded(&o, s, n, width, flags & ~F_ZERO, 0);
+			continue;
+		}
+		if (conv == 'n') {
+			int *ip = va_arg(ap, int *);
+
+			/* Do not write during vfprintf's sizing pass. */
+			if (ip && o.buf)
+				*ip = (int)o.len;
+			continue;
+		}
+		if (conv == 'f' || conv == 'F' || conv == 'e' ||
+		    conv == 'E' || conv == 'g' || conv == 'G') {
+			format_double(&o, va_arg(ap, double), conv, prec, flags,
+				      width);
+			continue;
+		}
+
+		{
+			int base = 10;
+			int upper = 0;
+			int is_signed = 0;
+			int is_ptr = 0;
+			long long sv = 0;
+			unsigned long long uv = 0;
+			char digits[80];
+			char body[96];
+			int nd;
+			int bn = 0;
+			int prefix = 0;
+			int neg = 0;
+
+			if (conv == 'd' || conv == 'i') {
+				is_signed = 1;
+			} else if (conv == 'u') {
+				base = 10;
+			} else if (conv == 'o') {
+				base = 8;
+			} else if (conv == 'x') {
+				base = 16;
+			} else if (conv == 'X') {
+				base = 16;
+				upper = 1;
+			} else if (conv == 'p') {
+				base = 16;
+				is_ptr = 1;
+			} else {
+				out_char(&o, '%');
+				out_char(&o, conv);
+				continue;
+			}
+
+			if (is_ptr) {
+				uv = (unsigned long)va_arg(ap, void *);
+			} else if (is_signed) {
+				switch (len) {
+				case 0: sv = (signed char)va_arg(ap, int); break;
+				case 1: sv = (short)va_arg(ap, int); break;
+				case 2: sv = va_arg(ap, long); break;
+				case 3: sv = va_arg(ap, long long); break;
+				case 4: sv = (long)va_arg(ap, size_t); break;
+				case 5: sv = (long)va_arg(ap, ptrdiff_t); break;
+				case 6: sv = va_arg(ap, long long); break;
+				default: sv = va_arg(ap, int); break;
+				}
+				if (sv < 0) {
+					neg = 1;
+					uv = (unsigned long long)(-(sv + 1)) + 1ULL;
+				} else {
+					uv = (unsigned long long)sv;
+				}
+			} else {
+				switch (len) {
+				case 0: uv = (unsigned char)va_arg(ap, unsigned int); break;
+				case 1: uv = (unsigned short)va_arg(ap, unsigned int); break;
+				case 2: uv = va_arg(ap, unsigned long); break;
+				case 3: uv = va_arg(ap, unsigned long long); break;
+				case 4: uv = va_arg(ap, size_t); break;
+				case 5: uv = (unsigned long)va_arg(ap, ptrdiff_t); break;
+				case 6: uv = va_arg(ap, unsigned long long); break;
+				default: uv = va_arg(ap, unsigned int); break;
+				}
+			}
+
+			if (prec > 64)
+				prec = 64;
+			if (is_ptr) {
+				prefix = 2;
+			} else if ((flags & F_HASH) && base == 16 && uv != 0) {
+				prefix = 2;
+			} else if ((flags & F_HASH) && base == 8) {
+				prefix = 1;
+			}
+
+			nd = utoa_base(uv, (unsigned int)base, upper, digits);
+			if (prec == 0 && uv == 0) {
+				nd = 0;
+				digits[0] = '\0';
+			}
+			while (nd < prec) {
+				memmove(digits + 1, digits, (size_t)nd + 1);
+				digits[0] = '0';
+				nd++;
+			}
+			if (neg) {
+				body[bn++] = '-';
+			} else if (flags & F_PLUS) {
+				body[bn++] = '+';
+			} else if (flags & F_SPACE) {
+				body[bn++] = ' ';
+			}
+			if (prefix == 2) {
+				body[bn++] = '0';
+				body[bn++] = upper ? 'X' : 'x';
+			} else if (prefix == 1 && (nd == 0 || digits[0] != '0')) {
+				body[bn++] = '0';
+			}
+			memcpy(body + bn, digits, (size_t)nd);
+			bn += nd;
+			body[bn] = '\0';
+			emit_padded(&o, body, bn, width, flags, 1);
+		}
+	}
+
+	if (o.cap) {
+		size_t end = o.len < o.cap ? o.len : o.cap - 1;
+		o.buf[end] = '\0';
+	}
+	if (o.len > INT_MAX)
+		return -1;
+	return (int)o.len;
+}
+
+int snprintf(char *buf, size_t size, const char *format, ...)
+{
+	va_list ap;
+	int n;
+
+	va_start(ap, format);
+	n = vsnprintf(buf, size, format, ap);
+	va_end(ap);
+	return n;
+}
+
+int vsprintf(char *buf, const char *format, va_list ap)
+{
+	return vsnprintf(buf, (size_t)-1, format, ap);
+}
+
+int sprintf(char *buf, const char *format, ...)
+{
+	va_list ap;
+	int n;
+
+	va_start(ap, format);
+	n = vsprintf(buf, format, ap);
+	va_end(ap);
+	return n;
+}
+
+int vfprintf(FILE *stream, const char *format, va_list ap)
+{
+	va_list cp;
+	int n;
+	char *buf;
+
+	va_copy(cp, ap);
+	n = vsnprintf(0, 0, format, cp);
+	va_end(cp);
+	if (n < 0)
+		return n;
+	buf = (char *)malloc((size_t)n + 1);
+	if (!buf) {
+		errno = ENOMEM;
+		return -1;
+	}
+	vsnprintf(buf, (size_t)n + 1, format, ap);
+	fwrite(buf, 1, (size_t)n, stream);
+	free(buf);
+	return n;
+}
+
+int fprintf(FILE *stream, const char *format, ...)
+{
+	va_list ap;
+	int n;
+
+	va_start(ap, format);
+	n = vfprintf(stream, format, ap);
+	va_end(ap);
+	return n;
+}
+
+int vprintf(const char *format, va_list ap)
+{
+	return vfprintf(stdout, format, ap);
+}
+
+int printf(const char *format, ...)
+{
+	va_list ap;
+	int n;
+
+	va_start(ap, format);
+	n = vfprintf(stdout, format, ap);
+	va_end(ap);
+	return n;
+}
+
+int puts(const char *s)
+{
+	if (fputs(s, stdout) < 0)
+		return EOF;
+	if (fputc('\n', stdout) < 0)
+		return EOF;
+	return 0;
+}
+
+int putchar(int c)
+{
+	return fputc(c, stdout);
+}
+
+void perror(const char *s)
+{
+	if (s && *s)
+		fprintf(stderr, "%s: %s\n", s, strerror(errno));
+	else
+		fprintf(stderr, "%s\n", strerror(errno));
+}

+ 343 - 0
libc/stdio_file.c

@@ -0,0 +1,343 @@
+/* Ring-3 FILE layer.
+ *
+ * Files are read-only and whole-file: fopen() stats the path, allocates one
+ * buffer and reads it through SYS_READ_FILE.  stdout/stderr are console
+ * streams.  This is enough for MuJS's js_dofile and default reporter.
+ *
+ * TODO(fd-layer): replace whole-file FILE with SYS_OPEN/READ/WRITE/LSEEK/
+ * CLOSE and offset-capable fs_ops when a real fd layer lands.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <ucmd_lib.h>
+
+#define FILE_MAX (4u * 1024u * 1024u)
+
+struct __libc_file {
+	int kind;       /* 0 = empty/stdin, 1 = console, 2 = whole-file */
+	int owned;
+	int eof;
+	int error;
+	unsigned char *data;
+	unsigned int size;
+	unsigned int pos;
+};
+
+static struct __libc_file console_out = { 1, 0, 0, 0, 0, 0, 0 };
+static struct __libc_file console_err = { 1, 0, 0, 0, 0, 0, 0 };
+static struct __libc_file stdin_file = { 0, 0, 0, 0, 0, 0, 0 };
+
+FILE *stdin = &stdin_file;
+FILE *stdout = &console_out;
+FILE *stderr = &console_err;
+
+static int map_sys_error(int r)
+{
+	switch (r) {
+	case SYS_ENOENT: return ENOENT;
+	case SYS_ENODEV: return ENODEV;
+	case SYS_ENOFS:  return ENODEV;
+	case SYS_EINVAL: return EINVAL;
+	case SYS_EROFS:  return EROFS;
+	case SYS_ENOSPC: return ENOSPC;
+	case SYS_EWRITE: return EIO;
+	case SYS_EIO:    return EIO;
+	default:         return EIO;
+	}
+}
+
+FILE *fopen(const char *path, const char *mode)
+{
+	struct sys_stat st;
+	struct __libc_file *f;
+	int r;
+
+	if (!path || !mode) {
+		errno = EINVAL;
+		return 0;
+	}
+	if (!(mode[0] == 'r' && (mode[1] == '\0' || mode[1] == 'b'))) {
+		/* TODO(fd-layer): writable FILE objects need the kernel fd layer. */
+		errno = EROFS;
+		return 0;
+	}
+
+	r = u_syscall2(SYS_FS_STAT, (int)path, (int)&st);
+	if (r != 0) {
+		errno = map_sys_error(r);
+		return 0;
+	}
+	if (st.is_dir) {
+		errno = EISDIR;
+		return 0;
+	}
+	if (st.size > FILE_MAX) {
+		errno = EFBIG;
+		return 0;
+	}
+
+	f = (struct __libc_file *)malloc(sizeof(*f));
+	if (!f) {
+		errno = ENOMEM;
+		return 0;
+	}
+	memset(f, 0, sizeof(*f));
+	f->kind = 2;
+	f->owned = 1;
+	f->data = (unsigned char *)malloc(st.size ? st.size : 1);
+	if (!f->data) {
+		free(f);
+		errno = ENOMEM;
+		return 0;
+	}
+	if (st.size) {
+		r = u_syscall3(SYS_READ_FILE, (int)path, (int)f->data,
+			       (int)st.size);
+		if (r < 0) {
+			free(f->data);
+			free(f);
+			errno = map_sys_error(r);
+			return 0;
+		}
+		f->size = (unsigned int)r;
+	}
+	return f;
+}
+
+int fclose(FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+
+	if (!f)
+		return EOF;
+	if (f->owned) {
+		free(f->data);
+		free(f);
+	}
+	return 0;
+}
+
+size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+	size_t total;
+	size_t avail;
+	size_t got;
+
+	if (!f || !ptr || size == 0 || nmemb == 0)
+		return 0;
+	if (size && nmemb > (size_t)-1 / size) {
+		errno = EOVERFLOW;
+		return 0;
+	}
+	if (f->kind == 0) {
+		f->eof = 1;
+		return 0;
+	}
+	if (f->kind != 2) {
+		errno = EBADF;
+		return 0;
+	}
+	total = size * nmemb;
+	avail = (size_t)f->size - f->pos;
+	if (total > avail)
+		total = avail;
+	got = total / size;
+	if (got) {
+		memcpy(ptr, f->data + f->pos, got * size);
+		f->pos += (unsigned int)(got * size);
+	}
+	if (got < nmemb)
+		f->eof = 1;
+	return got;
+}
+
+static int console_write(FILE *stream, const void *ptr, size_t len)
+{
+	const unsigned char *p = (const unsigned char *)ptr;
+	size_t i;
+
+	(void)stream;
+	for (i = 0; i < len; i++)
+		u_putc((char)p[i]);
+	return 0;
+}
+
+size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+
+	if (!f || !ptr || size == 0 || nmemb == 0)
+		return 0;
+	if (size && nmemb > (size_t)-1 / size) {
+		errno = EOVERFLOW;
+		return 0;
+	}
+	if (f->kind != 1) {
+		errno = EBADF;
+		return 0;
+	}
+	console_write(stream, ptr, size * nmemb);
+	return nmemb;
+}
+
+int fputc(int c, FILE *stream)
+{
+	unsigned char ch = (unsigned char)c;
+
+	if (fwrite(&ch, 1, 1, stream) != 1)
+		return EOF;
+	return ch;
+}
+
+int fgetc(FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+	int c;
+
+	if (!f || f->kind == 0) {
+		if (f)
+			f->eof = 1;
+		return EOF;
+	}
+	if (f->kind != 2) {
+		errno = EBADF;
+		return EOF;
+	}
+	if (f->pos >= f->size) {
+		f->eof = 1;
+		return EOF;
+	}
+	c = f->data[f->pos++];
+	return c;
+}
+
+int getchar(void)
+{
+	return fgetc(stdin);
+}
+
+char *fgets(char *s, int size, FILE *stream)
+{
+	int n = 0;
+
+	if (!s || size <= 0)
+		return 0;
+	while (n + 1 < size) {
+		int c = fgetc(stream);
+		if (c == EOF) {
+			if (n == 0)
+				return 0;
+			break;
+		}
+		s[n++] = (char)c;
+		if (c == '\n')
+			break;
+	}
+	s[n] = '\0';
+	return s;
+}
+
+int fputs(const char *s, FILE *stream)
+{
+	size_t n;
+
+	if (!s)
+		return EOF;
+	n = strlen(s);
+	if (fwrite(s, 1, n, stream) != n)
+		return EOF;
+	return 0;
+}
+
+int fseek(FILE *stream, long offset, int whence)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+	long base;
+	long target;
+
+	if (!f || f->kind != 2) {
+		errno = ESPIPE;
+		return -1;
+	}
+	if (whence == SEEK_SET)
+		base = 0;
+	else if (whence == SEEK_CUR)
+		base = (long)f->pos;
+	else if (whence == SEEK_END)
+		base = (long)f->size;
+	else {
+		errno = EINVAL;
+		return -1;
+	}
+	if (offset > LONG_MAX - base || offset < LONG_MIN + base) {
+		errno = EOVERFLOW;
+		return -1;
+	}
+	target = base + offset;
+	if (target < 0 || (unsigned long)target > f->size) {
+		errno = EINVAL;
+		return -1;
+	}
+	f->pos = (unsigned int)target;
+	f->eof = 0;
+	return 0;
+}
+
+long ftell(FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+
+	if (!f || f->kind != 2) {
+		errno = ESPIPE;
+		return -1;
+	}
+	return (long)f->pos;
+}
+
+void rewind(FILE *stream)
+{
+	(void)fseek(stream, 0, SEEK_SET);
+	clearerr(stream);
+}
+
+int fflush(FILE *stream)
+{
+	(void)stream;
+	return 0;
+}
+
+int feof(FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+
+	return f ? f->eof : 0;
+}
+
+int ferror(FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+
+	return f ? f->error : 0;
+}
+
+void clearerr(FILE *stream)
+{
+	struct __libc_file *f = (struct __libc_file *)stream;
+
+	if (f) {
+		f->eof = 0;
+		f->error = 0;
+	}
+}
+
+int fileno(FILE *stream)
+{
+	(void)stream;
+	errno = EBADF;
+	return -1;
+}

+ 10 - 0
libc/stdlib.c

@@ -9,6 +9,16 @@ int abs(int value)
 	return value < 0 ? -value : value;
 }
 
+int atoi(const char *str)
+{
+	return (int)strtol(str, 0, 10);
+}
+
+long atol(const char *str)
+{
+	return strtol(str, 0, 10);
+}
+
 long strtol(const char *str, char **endptr, int base)
 {
 	const char *p = str;

+ 45 - 0
libc/test_div64.c

@@ -0,0 +1,45 @@
+/* Host test for the compiler 64-bit division helpers. */
+#include <stdio.h>
+
+typedef unsigned long long u64;
+typedef long long s64;
+
+u64 __udivdi3(u64, u64);
+u64 __umoddi3(u64, u64);
+s64 __divdi3(s64, s64);
+s64 __moddi3(s64, s64);
+s64 __divmoddi4(s64, s64, s64 *);
+
+static int failures;
+
+static void ck(const char *name, u64 got, u64 want)
+{
+	if (got != want) {
+		printf("div64 mismatch %s: got %llu want %llu\n",
+		       name, got, want);
+		failures++;
+	}
+}
+
+int main(void)
+{
+	s64 r;
+
+	ck("udiv", __udivdi3(1000000000000ULL, 7ULL),
+	   1000000000000ULL / 7ULL);
+	ck("umod", __umoddi3(1000000000000ULL, 7ULL),
+	   1000000000000ULL % 7ULL);
+	ck("div", (u64)__divdi3(-1000000000000LL, 7LL),
+	   (u64)(-1000000000000LL / 7LL));
+	ck("mod", (u64)__moddi3(-1000000000000LL, 7LL),
+	   (u64)(-1000000000000LL % 7LL));
+	ck("divmodq", (u64)__divmoddi4(-1000000000000LL, 7LL, &r),
+	   (u64)(-1000000000000LL / 7LL));
+	ck("divmodr", (u64)r, (u64)(-1000000000000LL % 7LL));
+
+	if (failures)
+		printf("div64 test: %d failure(s)\n", failures);
+	else
+		printf("div64 test: OK\n");
+	return failures != 0;
+}

+ 72 - 0
libc/test_format.c

@@ -0,0 +1,72 @@
+/* Host test for the stdio formatting core. */
+#include <stdio.h>
+#include <string.h>
+#include <stddef.h>
+
+int errno;
+
+static int failures;
+
+static void check(const char *got, const char *want)
+{
+	if (strcmp(got, want)) {
+		printf("format mismatch: got [%s] want [%s]\n", got, want);
+		failures++;
+	}
+}
+
+int main(void)
+{
+	char b[2048];
+
+	snprintf(b, sizeof(b), "%d %u %x %s %c %%", -42, 42u,
+		 0xdeadbeefu, "hi", 'Z');
+	check(b, "-42 42 deadbeef hi Z %");
+
+	snprintf(b, sizeof(b), "%08d %-5s %.3s %+d % d",
+		 42, "ab", "abcdef", 7, 7);
+	check(b, "00000042 ab    abc +7  7");
+
+	snprintf(b, sizeof(b), "%lld %llu %llx", 1234567890123LL,
+		 18446744073709551615ULL, 0xdeadbeefcafebabeULL);
+	check(b, "1234567890123 18446744073709551615 deadbeefcafebabe");
+
+	snprintf(b, sizeof(b), "%f %.2f %.0f %e %.3e %g %.3g",
+		 1.5, 1.005, 2.5, 1234.5, 0.0012345, 1000000.0, 0.00012345);
+	check(b, "1.500000 1.00 2 1.234500e+03 1.234e-03 1e+06 0.000123");
+
+	snprintf(b, sizeof(b), "%.20f", 1.0 / 3.0);
+	check(b, "0.33333333333333331483");
+	snprintf(b, sizeof(b), "%.20f", 0.1);
+	check(b, "0.10000000000000000555");
+
+	snprintf(b, sizeof(b), "%.0f %.0f %.0f %.0f", 0.5, 1.5, 2.5, 3.5);
+	check(b, "0 2 2 4");
+	snprintf(b, sizeof(b), "%.2f %.2f %.2f", 1.005, 2.675, 9.999);
+	check(b, "1.00 2.67 10.00");
+
+	snprintf(b, sizeof(b), "%g %g %g %g", 100000.0, 1000000.0,
+		 0.0001, 0.00001);
+	check(b, "100000 1e+06 0.0001 1e-05");
+
+	snprintf(b, sizeof(b), "%f", -0.0);
+	check(b, "-0.000000");
+	{
+		char *nullp = 0;
+		const char *six = "abcdef";
+
+		snprintf(b, sizeof(b), "%s", nullp);
+		check(b, "(null)");
+		snprintf(b, 5, "%s", six);
+		check(b, "abcd");
+	}
+
+	snprintf(b, sizeof(b), "%p", (void *)0x1234);
+	check(b, "0x1234");
+
+	if (failures)
+		printf("format test: %d failure(s)\n", failures);
+	else
+		printf("format test: OK\n");
+	return failures != 0;
+}

+ 64 - 0
libc/test_math.c

@@ -0,0 +1,64 @@
+/* Host test for the x87 math functions. */
+#include <stdio.h>
+#include <math.h>
+
+static int failures;
+
+static void ck(const char *name, double got, double want)
+{
+	double d = got - want;
+
+	if (d < 0)
+		d = -d;
+	if (!(d < 1e-9)) {
+		printf("math mismatch %s: got %.17g want %.17g\n",
+		       name, got, want);
+		failures++;
+	}
+}
+
+int main(void)
+{
+	int e;
+	double ip;
+
+	ck("sqrt", sqrt(9.0), 3.0);
+	ck("fabs", fabs(-2.5), 2.5);
+	ck("floor", floor(-1.2), -2.0);
+	ck("ceil", ceil(-1.2), -1.0);
+	ck("trunc", trunc(-1.2), -1.0);
+	ck("round", round(2.5), 3.0);
+	ck("fmod", fmod(7.5, 2.0), 1.5);
+	ck("pow", pow(2.0, 10.0), 1024.0);
+	ck("powneg", pow(-2.0, 3.0), -8.0);
+	ck("powfrac", pow(9.0, 0.5), 3.0);
+	ck("exp0", exp(0.0), 1.0);
+	ck("exp1", exp(1.0), 2.718281828459045);
+	ck("log1", log(1.0), 0.0);
+	ck("logE", log(2.718281828459045), 1.0);
+	ck("log10", log10(100.0), 2.0);
+	ck("sin0", sin(0.0), 0.0);
+	ck("cos0", cos(0.0), 1.0);
+	ck("tan0", tan(0.0), 0.0);
+	ck("atan1", atan(1.0), 0.7853981633974483);
+	ck("atan2", atan2(1.0, 1.0), 0.7853981633974483);
+	ck("asin", asin(0.5), 0.5235987755982989);
+	ck("acos", acos(0.5), 1.0471975511965977);
+	ck("ldexp", ldexp(1.5, 3), 12.0);
+	ck("frexp", frexp(12.0, &e), 0.75);
+	if (e != 4) {
+		printf("math mismatch frexp exponent %d\n", e);
+		failures++;
+	}
+	ck("modf", modf(2.75, &ip), 0.75);
+	ck("modfip", ip, 2.0);
+	ck("fmin", fmin(2.0, 3.0), 2.0);
+	ck("fmax", fmax(2.0, 3.0), 3.0);
+	ck("copysign", copysign(2.0, -1.0), -2.0);
+
+	if (failures)
+		printf("math test: %d failure(s)\n", failures);
+	else
+		printf("math test: OK\n");
+	return failures != 0;
+}

+ 21 - 0
libc/test_setjmp.c

@@ -0,0 +1,21 @@
+/* 32-bit host test for libc/setjmp.S. */
+#include <stdio.h>
+#include <setjmp.h>
+
+static jmp_buf env;
+static int count;
+
+int main(void)
+{
+	int r = setjmp(env);
+
+	count++;
+	if (r == 0)
+		longjmp(env, 7);
+	if (r != 7 || count != 2) {
+		printf("setjmp test: FAIL r=%d count=%d\n", r, count);
+		return 1;
+	}
+	printf("setjmp test: OK\n");
+	return 0;
+}

+ 540 - 0
libc/time.c

@@ -0,0 +1,540 @@
+/* UTC wall-clock support for ring-3 commands.
+ *
+ * The CMOS RTC is exposed through SYS_RTC_GET/SYS_RTC_SET.  time_t is 64-bit
+ * so the RTC's 1970-2069 range is representable (a signed 32-bit time_t would
+ * stop at 2038).  There is no timezone database: localtime == gmtime. */
+
+#include <time.h>
+#include <sys/time.h>
+#include <errno.h>
+#include <string.h>
+#include <ucmd_lib.h>
+
+static const char *const wday_abbr[7] = {
+	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+};
+static const char *const wday_full[7] = {
+	"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
+	"Saturday"
+};
+static const char *const mon_abbr[12] = {
+	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
+	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+};
+static const char *const mon_full[12] = {
+	"January", "February", "March", "April", "May", "June",
+	"July", "August", "September", "October", "November", "December"
+};
+
+static long long days_from_civil(int y, unsigned m, unsigned d)
+{
+	long long era;
+	unsigned yoe, doy, doe;
+
+	y -= m <= 2;
+	era = (y >= 0 ? y : y - 399) / 400;
+	yoe = (unsigned)(y - era * 400);
+	doy = (153u * (m + (m > 2 ? (unsigned)-3 : 9u)) + 2u) / 5u + d - 1u;
+	doe = yoe * 365u + yoe / 4u - yoe / 100u + doy;
+	return era * 146097LL + (long long)doe - 719468LL;
+}
+
+static void civil_from_days(long long z, int *year, unsigned *month,
+			    unsigned *day)
+{
+	long long era;
+	unsigned doe, yoe, doy, mp;
+
+	z += 719468LL;
+	era = (z >= 0 ? z : z - 146096LL) / 146097LL;
+	doe = (unsigned)(z - era * 146097LL);
+	yoe = (doe - doe / 1460u + doe / 36524u - doe / 146096u) / 365u;
+	*month = 0;
+	*day = 0;
+	{
+		int y = (int)yoe + (int)era * 400;
+		doy = doe - (365u * yoe + yoe / 4u - yoe / 100u);
+		mp = (5u * doy + 2u) / 153u;
+		*day = doy - (153u * mp + 2u) / 5u + 1u;
+		*month = mp + (mp < 10u ? 3u : (unsigned)-9);
+		y += (*month <= 2u);
+		*year = y;
+	}
+}
+
+static int epoch_from_tm(const struct tm *tm, time_t *out)
+{
+	long long days;
+	long long sec;
+
+	if (!tm || tm->tm_mon < 0 || tm->tm_mon > 11 ||
+	    tm->tm_mday < 1 || tm->tm_mday > 31 ||
+	    tm->tm_hour < 0 || tm->tm_hour > 23 ||
+	    tm->tm_min < 0 || tm->tm_min > 59 ||
+	    tm->tm_sec < 0 || tm->tm_sec > 59)
+		return -1;
+	if (tm->tm_year < -1900 || tm->tm_year > 8099)
+		return -1;
+
+	days = days_from_civil(tm->tm_year + 1900,
+			       (unsigned)(tm->tm_mon + 1),
+			       (unsigned)tm->tm_mday);
+	sec = days * 86400LL + tm->tm_hour * 3600LL +
+	      tm->tm_min * 60LL + tm->tm_sec;
+	*out = (time_t)sec;
+	return 0;
+}
+
+static int rtc_now(struct tm *tm)
+{
+	struct sys_datetime dt;
+
+	if (u_rtc_get(&dt) != 0) {
+		errno = EIO;
+		return -1;
+	}
+	if (dt.year < 1970 || dt.year > 2069 ||
+	    dt.month < 1 || dt.month > 12 ||
+	    dt.day < 1 || dt.day > 31 ||
+	    dt.hour > 23 || dt.minute > 59 || dt.second > 59) {
+		errno = EINVAL;
+		return -1;
+	}
+
+	tm->tm_sec = (int)dt.second;
+	tm->tm_min = (int)dt.minute;
+	tm->tm_hour = (int)dt.hour;
+	tm->tm_mday = (int)dt.day;
+	tm->tm_mon = (int)dt.month - 1;
+	tm->tm_year = (int)dt.year - 1900;
+	tm->tm_wday = (int)(dt.wday % 7u);
+	tm->tm_yday = (int)(days_from_civil((int)dt.year, (unsigned)dt.month,
+					   (unsigned)dt.day) -
+			    days_from_civil((int)dt.year, 1u, 1u));
+	tm->tm_isdst = 0;
+	return 0;
+}
+
+time_t time(time_t *tloc)
+{
+	struct tm tm;
+	time_t t;
+
+	if (rtc_now(&tm) != 0)
+		return (time_t)-1;
+	if (epoch_from_tm(&tm, &t) != 0) {
+		errno = EINVAL;
+		return (time_t)-1;
+	}
+	if (tloc)
+		*tloc = t;
+	return t;
+}
+
+struct tm *gmtime(const time_t *timer)
+{
+	static struct tm tm;
+	long long sec;
+	long long days;
+	unsigned sod;
+	int y;
+	unsigned m, d;
+
+	if (!timer) {
+		errno = EINVAL;
+		return 0;
+	}
+	sec = (long long)*timer;
+	if (sec >= 0) {
+		days = sec / 86400LL;
+		sod = (unsigned)(sec % 86400LL);
+	} else {
+		long long q = (-sec + 86399LL) / 86400LL;
+
+		days = -q;
+		sod = (unsigned)(sec - days * 86400LL);
+	}
+	civil_from_days(days, &y, &m, &d);
+
+	tm.tm_year = y - 1900;
+	tm.tm_mon = (int)m - 1;
+	tm.tm_mday = (int)d;
+	tm.tm_hour = (int)(sod / 3600u);
+	tm.tm_min = (int)((sod / 60u) % 60u);
+	tm.tm_sec = (int)(sod % 60u);
+	tm.tm_wday = (int)((days + 4) % 7);
+	if (tm.tm_wday < 0)
+		tm.tm_wday += 7;
+	tm.tm_yday = (int)(days - days_from_civil(y, 1u, 1u));
+	tm.tm_isdst = 0;
+	return &tm;
+}
+
+struct tm *localtime(const time_t *timer)
+{
+	/* No timezone database: the RTC is UTC. */
+	return gmtime(timer);
+}
+
+time_t mktime(struct tm *tm)
+{
+	time_t t;
+
+	if (epoch_from_tm(tm, &t) != 0) {
+		errno = EINVAL;
+		return (time_t)-1;
+	}
+	return t;
+}
+
+static int out_ch(char **pp, char *end, char c)
+{
+	if (*pp + 1 >= end)
+		return -1;
+	*(*pp)++ = c;
+	return 0;
+}
+
+static int out_dec(char **pp, char *end, unsigned int v, int width)
+{
+	char tmp[12];
+	int n = 0;
+	int i;
+
+	do {
+		tmp[n++] = (char)('0' + v % 10u);
+		v /= 10u;
+	} while (v);
+	while (n < width) {
+		if (out_ch(pp, end, '0'))
+			return -1;
+		width--;
+	}
+	for (i = n - 1; i >= 0; i--) {
+		if (out_ch(pp, end, tmp[i]))
+			return -1;
+	}
+	return 0;
+}
+
+static int out_str(char **pp, char *end, const char *s)
+{
+	while (*s) {
+		if (out_ch(pp, end, *s++))
+			return -1;
+	}
+	return 0;
+}
+
+size_t strftime(char *s, size_t max, const char *format, const struct tm *tm)
+{
+	char *p = s;
+	char *end = s + max;
+
+	if (!s || !format || !tm || max == 0) {
+		errno = EINVAL;
+		return 0;
+	}
+
+	for (; *format; format++) {
+		int c;
+
+		if (*format != '%') {
+			if (out_ch(&p, end, *format))
+				return 0;
+			continue;
+		}
+		format++;
+		if (!*format) {
+			errno = EINVAL;
+			return 0;
+		}
+		c = *format;
+		switch (c) {
+		case 'Y':
+			if (out_dec(&p, end, (unsigned)(tm->tm_year + 1900), 4))
+				return 0;
+			break;
+		case 'y':
+			if (out_dec(&p, end, (unsigned)(tm->tm_year % 100), 2))
+				return 0;
+			break;
+		case 'm':
+			if (out_dec(&p, end, (unsigned)(tm->tm_mon + 1), 2))
+				return 0;
+			break;
+		case 'd':
+			if (out_dec(&p, end, (unsigned)tm->tm_mday, 2))
+				return 0;
+			break;
+		case 'e':
+			if (out_dec(&p, end, (unsigned)tm->tm_mday, 2))
+				return 0;
+			if (p - 2 >= s)
+				*(p - 2) = ' ';
+			break;
+		case 'H':
+			if (out_dec(&p, end, (unsigned)tm->tm_hour, 2))
+				return 0;
+			break;
+		case 'M':
+			if (out_dec(&p, end, (unsigned)tm->tm_min, 2))
+				return 0;
+			break;
+		case 'S':
+			if (out_dec(&p, end, (unsigned)tm->tm_sec, 2))
+				return 0;
+			break;
+		case 'j':
+			if (out_dec(&p, end, (unsigned)(tm->tm_yday + 1), 3))
+				return 0;
+			break;
+		case 'w':
+			if (out_ch(&p, end, (char)('0' + (tm->tm_wday % 7))))
+				return 0;
+			break;
+		case 'u':
+			if (out_ch(&p, end, (char)('0' + (tm->tm_wday ? tm->tm_wday : 7))))
+				return 0;
+			break;
+		case 'a':
+			if (out_str(&p, end, wday_abbr[(unsigned)(tm->tm_wday % 7)]))
+				return 0;
+			break;
+		case 'A':
+			if (out_str(&p, end, wday_full[(unsigned)(tm->tm_wday % 7)]))
+				return 0;
+			break;
+		case 'b':
+			if (out_str(&p, end, mon_abbr[(unsigned)(tm->tm_mon % 12)]))
+				return 0;
+			break;
+		case 'B':
+			if (out_str(&p, end, mon_full[(unsigned)(tm->tm_mon % 12)]))
+				return 0;
+			break;
+		case 'p':
+			if (out_str(&p, end, tm->tm_hour < 12 ? "AM" : "PM"))
+				return 0;
+			break;
+		case 'F':
+			if (out_dec(&p, end, (unsigned)(tm->tm_year + 1900), 4) ||
+			    out_ch(&p, end, '-') ||
+			    out_dec(&p, end, (unsigned)(tm->tm_mon + 1), 2) ||
+			    out_ch(&p, end, '-') ||
+			    out_dec(&p, end, (unsigned)tm->tm_mday, 2))
+				return 0;
+			break;
+		case 'T':
+			if (out_dec(&p, end, (unsigned)tm->tm_hour, 2) ||
+			    out_ch(&p, end, ':') ||
+			    out_dec(&p, end, (unsigned)tm->tm_min, 2) ||
+			    out_ch(&p, end, ':') ||
+			    out_dec(&p, end, (unsigned)tm->tm_sec, 2))
+				return 0;
+			break;
+		case 's': {
+			time_t t;
+			char tmp[32];
+			char *q = tmp + sizeof(tmp);
+			long long v;
+			unsigned long long u;
+			int neg;
+
+			if (epoch_from_tm(tm, &t) != 0)
+				return 0;
+			v = (long long)t;
+			neg = v < 0;
+			u = neg ? (unsigned long long)(-v) : (unsigned long long)v;
+			*--q = '\0';
+			do {
+				*--q = (char)('0' + u % 10u);
+				u /= 10u;
+			} while (u);
+			if (neg)
+				*--q = '-';
+			if (out_str(&p, end, q))
+				return 0;
+			break;
+		}
+		case 'z':
+		case 'Z':
+			/* UTC / no timezone database. */
+			break;
+		case '%':
+			if (out_ch(&p, end, '%'))
+				return 0;
+			break;
+		default:
+			if (out_ch(&p, end, '%') || out_ch(&p, end, c))
+				return 0;
+			break;
+		}
+	}
+	if (p >= end)
+		return 0;
+	*p = '\0';
+	return (size_t)(p - s);
+}
+
+char *asctime(const struct tm *tm)
+{
+	static char buf[32];
+	char *p = buf;
+
+	if (!tm) {
+		errno = EINVAL;
+		return 0;
+	}
+	for (const char *q = wday_abbr[tm->tm_wday % 7]; *q; q++) *p++ = *q;
+	*p++ = ' ';
+	for (const char *q = mon_abbr[tm->tm_mon % 12]; *q; q++) *p++ = *q;
+	*p++ = ' ';
+	*p++ = (char)('0' + (tm->tm_mday / 10) % 10);
+	*p++ = (char)('0' + tm->tm_mday % 10);
+	*p++ = ' ';
+	*p++ = (char)('0' + (tm->tm_hour / 10) % 10);
+	*p++ = (char)('0' + tm->tm_hour % 10);
+	*p++ = ':';
+	*p++ = (char)('0' + (tm->tm_min / 10) % 10);
+	*p++ = (char)('0' + tm->tm_min % 10);
+	*p++ = ':';
+	*p++ = (char)('0' + (tm->tm_sec / 10) % 10);
+	*p++ = (char)('0' + tm->tm_sec % 10);
+	*p++ = ' ';
+	{
+		int y = tm->tm_year + 1900;
+		*p++ = (char)('0' + (y / 1000) % 10);
+		*p++ = (char)('0' + (y / 100) % 10);
+		*p++ = (char)('0' + (y / 10) % 10);
+		*p++ = (char)('0' + y % 10);
+	}
+	*p++ = '\n';
+	*p = '\0';
+	return buf;
+}
+
+char *ctime(const time_t *timer)
+{
+	return asctime(localtime(timer));
+}
+
+double difftime(time_t time1, time_t time0)
+{
+	return (double)time1 - (double)time0;
+}
+
+int gettimeofday(struct timeval *tv, void *tz)
+{
+	time_t t;
+	(void)tz;
+
+	if (!tv) {
+		errno = EINVAL;
+		return -1;
+	}
+	t = time(0);
+	if (t == (time_t)-1)
+		return -1;
+	tv->tv_sec = t;
+	tv->tv_usec = (suseconds_t)((u_ticks_ms() % 1000u) * 1000u);
+	return 0;
+}
+
+int settimeofday(const struct timeval *tv, const void *tz)
+{
+	struct tm tm;
+	struct sys_datetime dt;
+	time_t t;
+	(void)tz;
+
+	if (!tv) {
+		errno = EINVAL;
+		return -1;
+	}
+	t = tv->tv_sec;
+	{
+		struct tm *p = gmtime(&t);
+
+		if (!p) {
+			errno = EINVAL;
+			return -1;
+		}
+		tm = *p;
+	}
+	if (tm.tm_year + 1900 < 1970 || tm.tm_year + 1900 > 2069) {
+		errno = EINVAL;
+		return -1;
+	}
+	dt.year = (unsigned)(tm.tm_year + 1900);
+	dt.month = (unsigned)(tm.tm_mon + 1);
+	dt.day = (unsigned)tm.tm_mday;
+	dt.hour = (unsigned)tm.tm_hour;
+	dt.minute = (unsigned)tm.tm_min;
+	dt.second = (unsigned)tm.tm_sec;
+	dt.wday = (unsigned)(tm.tm_wday % 7);
+	if (u_rtc_set(&dt) != 0) {
+		errno = EINVAL;
+		return -1;
+	}
+	return 0;
+}
+
+int clock_gettime(int clock_id, struct timespec *tp)
+{
+	if (!tp) {
+		errno = EINVAL;
+		return -1;
+	}
+	if (clock_id == CLOCK_REALTIME) {
+		struct timeval tv;
+		if (gettimeofday(&tv, 0) != 0)
+			return -1;
+		tp->tv_sec = tv.tv_sec;
+		tp->tv_nsec = (long)tv.tv_usec * 1000L;
+		return 0;
+	}
+	if (clock_id == CLOCK_MONOTONIC) {
+		unsigned int ms = u_ticks_ms();
+		tp->tv_sec = (time_t)(ms / 1000u);
+		tp->tv_nsec = (long)(ms % 1000u) * 1000000L;
+		return 0;
+	}
+	errno = EINVAL;
+	return -1;
+}
+
+int clock_settime(int clock_id, const struct timespec *tp)
+{
+	if (clock_id != CLOCK_REALTIME || !tp) {
+		errno = EINVAL;
+		return -1;
+	}
+	{
+		struct timeval tv;
+		tv.tv_sec = tp->tv_sec;
+		tv.tv_usec = tp->tv_nsec / 1000L;
+		return settimeofday(&tv, 0);
+	}
+}
+
+int nanosleep(const struct timespec *req, struct timespec *rem)
+{
+	unsigned long ms;
+
+	if (!req || req->tv_sec < 0 || req->tv_nsec < 0 ||
+	    req->tv_nsec >= 1000000000L) {
+		errno = EINVAL;
+		return -1;
+	}
+	ms = (unsigned long)req->tv_sec * 1000UL +
+	     (unsigned long)(req->tv_nsec + 999999L) / 1000000L;
+	if (ms > 0xFFFFFFFFu)
+		ms = 0xFFFFFFFFu;
+	u_sleep_ms((unsigned int)ms);
+	if (rem) {
+		rem->tv_sec = 0;
+		rem->tv_nsec = 0;
+	}
+	return 0;
+}