Quellcode durchsuchen

Add a ring-3 libc with malloc

Introduce libc.a: stddef/stdint/stdarg/stdlib/string/ctype/assert headers, a boundary-tag first-fit allocator with coalescing over the SYS_MEM_* arena, heap_reset() for page-scoped programs, and basic string/stdlib support.  malloc is 16-byte aligned, maps 64 KB lazily, grows in page-rounded steps with 64 KB slack and caps at 32 MB.  The archive is linked only into commands that reference it and --gc-sections drops unused functions.

Move the browser off its bump heap: page buffers, rules and bitmaps now use malloc, each image decodes into an img_estimate()-sized arena that is freed after scaling, and navigation calls heap_reset() to unmap the page heap.  view uses an exact file allocation plus a sized decode arena; curl uses malloc for its fetch buffer.  websrv and term still use the raw arena for now.

Document the ownership rule (a process must not mix malloc with raw SYS_MEM_* calls), add make test-libc and update the docs site and AGENTS.md.  The pack is 247493 bytes compressed, 13626 bytes under the CMDS_GZ_MAX cap.

Verified with make test-libc, a clean make all, and QEMU boots that render view /floppy1/pic.bmp, browser /floppy1/demo.htm, and a browser Ctrl+R reload through heap_reset().
Johannes Zellner vor 1 Woche
Ursprung
Commit
d5a4ecad96
29 geänderte Dateien mit 1681 neuen und 180 gelöschten Zeilen
  1. 2 0
      .gitignore
  2. 58 24
      AGENTS.md
  3. 52 12
      Makefile
  4. 49 94
      browser.c
  5. 4 1
      docs/development.html
  6. 1 1
      docs/filesystems.html
  7. 10 5
      docs/index.html
  8. 20 3
      docs/memory.html
  9. 45 4
      docs/userland.html
  10. 15 0
      libc/include/assert.h
  11. 53 0
      libc/include/ctype.h
  12. 12 0
      libc/include/stdarg.h
  13. 15 0
      libc/include/stddef.h
  14. 28 0
      libc/include/stdint.h
  15. 20 0
      libc/include/stdlib.h
  16. 23 0
      libc/include/string.h
  17. 11 0
      libc/include/ucmd_heap.h
  18. 442 0
      libc/malloc.c
  19. 162 0
      libc/stdlib.c
  20. 19 0
      libc/strdup.c
  21. 163 0
      libc/string.c
  22. 41 0
      libc/test_host_mem.c
  23. 373 0
      libc/test_malloc.c
  24. 20 0
      libc/ucmd_mem.c
  25. 5 1
      sys_mem.h
  26. 3 1
      syscall.h
  27. 6 4
      ucmd_curl.c
  28. 3 1
      ucmd_lib.h
  29. 26 29
      ucmd_view.c

+ 2 - 0
.gitignore

@@ -13,4 +13,6 @@ tls_test
 img_test
 img_test_asan
 text_canvas_test
+libc.a
+malloc_test
 mkrootfs

+ 58 - 24
AGENTS.md

@@ -1,7 +1,8 @@
 # AGENTS.md — NebOS (`nebos`)
 
 A from-scratch, freestanding **32-bit x86 hobby operating system** written in C and
-x86 assembly. Single-author project (~7,000 SLOC, no external runtime, no libc).
+x86 assembly. Single-author project (~7,000 SLOC, no external runtime; the
+kernel has no libc, while ring-3 commands may link the in-tree `libc.a`).
 Targets i586 (first-gen Pentium); runs under QEMU or on real hardware.
 
 ## Documentation site (`docs/`)
@@ -73,6 +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 clean
 ```
 
@@ -565,11 +567,25 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `USER_HEAP_BASE` (`0x60000000`), capped at 32 MB; the initial allocation is
   zeroed but pages appended by `SYS_MEM_GROW` are not (decoders initialize
   what they use), which keeps large image arenas fast to map.  The reaper
-  frees it with the rest of the process and `top` counts its pages.  The
-  canvas mapping at `USER_GFX_BASE` (`0x50000000`) and the WM mappings are
-  separate.
+  frees it with the rest of the process and `top` counts its pages.  Commands
+  that link `libc.a` own this arena through `libc/malloc.c`; the raw syscalls
+  and libc malloc must never be mixed in one process.  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
+  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; each process uses either this heap or the raw
+  `SYS_MEM_*` calls, never both.  The archive plus
+  `-ffunction-sections`/`--gc-sections` keeps unused code out of the legacy
+  pack.  Host test: `make test-libc` (`libc/test_malloc.c`).
 - **Ring-3 commands**: `ucmd_*.c`, `ucmd_lib.h`, `ucmd.ld`, `mkpack.c`,
-  `rootfs.h`, `mkrootfs.c`, `ramfs.c/h` — freestanding ELFs linked at
+  `rootfs.h`, `mkrootfs.c`, `ramfs.c/h` — static ELFs linked at
   `USER_BASE` (`0x40000000`), packed by `mkpack` into `cmds.pack` (as
   `bin/<name>`), gzipped to `cmds_pack_gz.bin` and wrapped by `mkrootfs`
   with a `NBROOT1` header.  The pack is the system rootfs: the boot path
@@ -647,17 +663,19 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   under `/share`, while the browser keeps drawing and scrolling its own
   window.  The helper asks for identity encoding because inflating multi-MB
   pages in the browser process stalled the UI; if a server still sends gzip,
-  the browser's inflate has a progress hook that pumps the UI.  Page, image
-  and CSS scratch buffers come from `SYS_MEM_ALLOC`; the DOM uses fixed static
-  arenas (6144 nodes, 512 KB attributes, 2304 rules), and page bodies are
-  capped at 2 MB with CSS sheets up to 832 KB (six sheets).  Images are
-  decoded once into a shared 24 MB arena and copied to a display bitmap at
-  most 1000 px wide (up to 16 images, 512 KB files / 8 MP decodes), so 4K
-  screenshots fit the 32 MB heap.  There is no JavaScript, forms, flex/grid,
-  CSS variables, absolute/fixed positioning or standalone image viewer mode.
-  `SYS_SPAWN` loads FAT ELFs through `kmalloc` now (the old 16 KB
-  `fat_load_buf` is gone) and wraps the load in `sys_fs_enter/exit`, since the
-  floppy needs IRQ 6.
+  the browser's inflate has a progress hook that pumps the UI.  Page, CSS and
+  image buffers come from the ring-3 libc heap; the DOM uses fixed static
+  arenas (6144 nodes, 512 KB attributes, 4608 rules), and page bodies are
+  capped at 2 MB with CSS sheets up to 832 KB (six sheets).  Each image gets
+  an `img_estimate()`-sized decode arena, freed as soon as the scaled bitmap
+  exists; up to 16 bitmaps (512 KB files / 8 MP decodes) are kept until the
+  page heap is reset.  Navigation calls `heap_reset()` and unmaps the whole
+  arena, so a large image no longer reserves a fixed 24 MB.  There is no
+  JavaScript, forms or standalone image viewer mode; flex/grid, basic tables,
+  inline SVG and CSS variables are supported (see known issue 22 for the
+  remaining CSS gaps).  `SYS_SPAWN` loads FAT ELFs through `kmalloc` now (the
+  old 16 KB `fat_load_buf` is gone) and wraps the load in `sys_fs_enter/exit`,
+  since the floppy needs IRQ 6.
 - **Image library + viewer**: `img.h`, `img.c`, `img_mem.c`, `img_blit.c`,
   `img_png.c`, `img_bmp.c`, `img_gif.c`, `img_jpeg.c`, `img_tga.c`,
   `img_pnm.c`, `img_file.c/h` — freestanding RGB565 decoders with an optional
@@ -1105,8 +1123,10 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 ## Conventions & gotchas
 
-- **Freestanding C** — no libc, no `malloc`, no `printf`. Use `io_putstr` /
-  `io_putchar` / `io_puthex` (`io.h`). Printing is VGA-framebuffer based.
+- **Freestanding C** — the kernel has no libc, no `malloc`, no `printf`; use
+  `io_putstr` / `io_putchar` / `io_puthex` (`io.h`).  Ring-3 commands may
+  link the in-tree `libc.a` (`malloc`, strings, stdlib); a command either uses
+  libc malloc or the raw `SYS_MEM_*` arena, never both.
 - **Paging is on but flat** — identity-mapped 4 MB pages (`paging.c`), so
   physical == virtual everywhere. Still no per-process address spaces or process
   isolation: everything runs ring-0 and shares the address space.
@@ -1164,7 +1184,7 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    legacy path; a larger pack needs the UEFI/kexec path or a chunked
    high-memory loader.  The browser and its ring-3 dependencies are compiled
    with function sections and linked with `--gc-sections`; the current pack
-   is ~241 KiB (246711 bytes), leaving ~14 KB under the cap.  Command growth
+   is ~242 KiB (247493 bytes), leaving ~13 KB under the cap.  Command growth
    still needs care because `libdeflate-gzip -12` is already required (plain
    `gzip -9` is over the cap).
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
@@ -1243,11 +1263,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `em`/`rem` both use a 16 px root, and `line-height` is approximate.
     Pages that need flex alignment/justification, multi-row grid templates
     or CSS variables inside `calc()`/`color-mix()` can still lay out
-    imperfectly.  Images are decoded into a 24 MB shared arena and
-    downscaled to a 1000 px display bitmap (16 images, 512 KB files / 8 MP
-    decodes); a large image-heavy page can still exhaust the 32 MB heap, and
-    the first `<img>` after a big screenshot can transiently need a new heap
-    growth.  `img_draw` rescales the cached bitmap on every repaint.  Lazy
+    imperfectly.  Images are decoded into a per-image `img_estimate()`-sized
+    arena that is freed after the 1000 px display bitmap is made (16 images,
+    512 KB files / 8 MP decodes); a large image-heavy page can still exhaust
+    the 32 MB heap because the scaled bitmaps live until navigation, and the
+    decode arena itself can transiently be large.  `img_draw` rescales the
+    cached bitmap on every repaint.  Lazy
     image loading uses the last measured positions; adding an image can
     reflow the content above it, and images below the viewport stay as
     `[image]` until scrolled into range.  Each network fetch starts a
@@ -1289,3 +1310,16 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     (`8086:3B32`, the `intel_ips` MMIO block) is not read because it needs
     the ME/BIOS to have enabled thermal reporting; the EC and DTS readings
     cover the package temperature.
+
+25. Ring-3 libc heap limits: one process owns the single 32 MB `SYS_MEM_*`
+    arena, there is no `free()`-to-page unmap (only `heap_reset()`), no
+    threads/locking and no double-free recovery beyond the block magic; a
+    pointer into the middle of a block or a stale pointer is silently
+    ignored by `free()`.  The allocator is first-fit with immediate
+    coalescing, so a pathological small/large lifetime mix can still
+    fragment; the browser and viewer use it for a handful of large,
+    page-scoped buffers.  A program must not mix `malloc` with raw
+    `u_mem_alloc`/`u_mem_grow`/`u_mem_free`, and near-32 MB requests fail
+    because the block headers are charged to the same cap.  The `libc.a`
+    members are only pulled into commands that reference them; the legacy
+    pack still needs every added byte checked against `CMDS_GZ_MAX`.

+ 52 - 12
Makefile

@@ -12,6 +12,18 @@ CFLAGS   = -ffreestanding -fno-pie -m32 -march=i586 -nostdlib -fno-stack-protect
 # Ring-3 objects are compiled with function sections so the browser link can
 # drop code it never reaches; the legacy rootfs pack is close to its cap.
 SECTION_CFLAGS = -ffunction-sections -fdata-sections
+
+# Ring-3 libc: a static archive linked only into commands that use it.  The
+# archive means apps that never reference malloc/string keep paying nothing,
+# and --gc-sections drops unused functions from the members that are pulled.
+LIBC_CFLAGS = $(CFLAGS) -Os $(SECTION_CFLAGS) -fno-builtin \
+              -I. -Ilibc/include
+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_OBJS = libc/malloc.o libc/string.o libc/strdup.o \
+            libc/stdlib.o libc/ucmd_mem.o
 ASFLAGS  = --32 -I.
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
@@ -534,8 +546,16 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
 # intermediates between the pattern rules).
 .PRECIOUS: $(addsuffix .elf,$(UCMDS))
 
-ucmd_%.o: ucmd_%.c ucmd_lib.h syscall.h
-	$(CC) $(CFLAGS) -o $@ $<
+# Ring-3 libc objects and archive.
+libc/%.o: libc/%.c $(LIBC_HEADERS) ucmd_lib.h syscall.h
+	$(CC) $(LIBC_CFLAGS) -o $@ $<
+
+libc.a: $(LIBC_OBJS)
+	rm -f $@
+	ar rcs $@ $^
+
+ucmd_%.o: ucmd_%.c ucmd_lib.h syscall.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
 
 ucmd_%.elf: ucmd_%.o ucmd.ld
 	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $<
@@ -617,11 +637,11 @@ $(IMGLIB_OBJS): %.o: %.c img.h img_internal.h inflate.h ucmd_lib.h syscall.h
 # The integer IDCT deliberately relies on 32-bit wrap-around.
 img_jpeg.o: CFLAGS += -fwrapv
 
-ucmd_view.o: ucmd_view.c ucmd_lib.h syscall.h wm_abi.h ngui.h img.h img_file.h
-	$(CC) $(CFLAGS) -o $@ $<
+ucmd_view.o: ucmd_view.c ucmd_lib.h syscall.h wm_abi.h ngui.h img.h img_file.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
 
-ucmd_view.elf: ucmd_view.o $(IMGLIB_OBJS) inflate.o ngui.o font_8x16.o ucmd.ld
-	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+ucmd_view.elf: ucmd_view.o $(IMGLIB_OBJS) inflate.o ngui.o font_8x16.o ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # TLS 1.3 client library (ring-3, linked into ucmd_curl; see tls.h).  The
@@ -633,8 +653,8 @@ TLSLIB_OBJS = tls_sha256.o tls_chacha20.o tls_x25519.o tls_rng.o tls.o
 uhttp.o: uhttp.c uhttp.h ucmd_lib.h tls.h
 	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
 
-ucmd_curl.elf: ucmd_curl.o uhttp.o $(TLSLIB_OBJS) ucmd.ld
-	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
+ucmd_curl.elf: ucmd_curl.o uhttp.o $(TLSLIB_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # browser: the real app is a disk image (BROWSER) because it links ngui, the
@@ -645,10 +665,10 @@ ucmd_curl.elf: ucmd_curl.o uhttp.o $(TLSLIB_OBJS) ucmd.ld
 browser_html.o: browser_html.c browser_html.h
 	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
 
-browser.o: browser.c ucmd_lib.h syscall.h wm_abi.h ngui.h browser_html.h uhttp.h img.h inflate.h
-	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
+browser.o: browser.c ucmd_lib.h syscall.h wm_abi.h ngui.h browser_html.h uhttp.h img.h inflate.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
 
-browser.elf: browser.o browser_html.o uhttp.o ngui.o font_8x16.o $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) ucmd.ld
+browser.elf: browser.o browser_html.o uhttp.o ngui.o font_8x16.o $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
@@ -693,6 +713,26 @@ test-images-asan: $(IMGTEST_SRCS) $(IMGTEST_DEPS)
 	gcc -O1 -g -fwrapv -fsanitize=address,undefined -I. -o img_test_asan $(IMGTEST_SRCS)
 	./img_test_asan
 
+# Host test for the ring-3 allocator.  The malloc/free names are renamed so
+# the host libc (printf, rand, write) keeps working normally.
+HOST_MALLOC_DEFS = -Dmalloc=libc_malloc -Dfree=libc_free \
+                   -Dcalloc=libc_calloc -Drealloc=libc_realloc \
+                   -Dheap_reset=libc_heap_reset
+
+libc/malloc_host.o: libc/malloc.c $(LIBC_HEADERS)
+	gcc -O2 -Wall -Wextra -Ilibc/include -fno-builtin \
+	    $(HOST_MALLOC_DEFS) -c -o $@ $<
+
+libc/test_host_mem.o: libc/test_host_mem.c
+	gcc -O2 -Wall -Wextra -c -o $@ $<
+
+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
+	./malloc_test
+
 mkpack: mkpack.c
 	gcc -O2 -o $@ $<
 
@@ -979,4 +1019,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
+	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

+ 49 - 94
browser.c

@@ -2,11 +2,15 @@
  * shared uhttp client.
  *
  * No JavaScript and no forms; external CSS is loaded over uhttp, and images
- * are decoded with img.c and drawn inline.  Large buffers (page body and the
- * image decode arena) live in the per-process SYS_MEM_ALLOC heap; the DOM and
- * the image/CSS I/O scratch use fixed static arenas.
+ * are decoded with img.c and drawn inline.  Page-scoped buffers (page body,
+ * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
+ * exact-size decode arena that is freed as soon as the scaled bitmap exists.
+ * The DOM and the image/CSS I/O scratch use fixed static arenas.
  */
 
+#include <stdlib.h>
+#include <ucmd_heap.h>
+
 #include "ucmd_lib.h"
 #include "ngui.h"
 #include "browser_html.h"
@@ -21,13 +25,11 @@
 #define BR_TOOLBAR_H    30
 #define BR_STATUS_H     18
 
-#define BR_HEAP_INIT    (6u * 1024u * 1024u)
-#define BR_HEAP_MAX     (32u * 1024u * 1024u)
 #define BR_PAGE_MAX     (2u * 1024u * 1024u)
 #define BR_IMG_FILE_MAX (512u * 1024u)
 #define BR_IMG_PIX_MAX  (8u * 1024u * 1024u)
 #define BR_MAX_IMAGES   16
-#define BR_IMG_ARENA    (24u * 1024u * 1024u)
+#define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
 #define BR_IMG_LAYOUT_W 1000
 #define BR_CSS_MAX      (832u * 1024u)
 #define BR_CSS_COMP_MAX (192u * 1024u)
@@ -91,24 +93,14 @@ static unsigned int post_status_ttl;
 static unsigned short img_top[BR_MAX_NODES];
 static unsigned short img_h[BR_MAX_NODES];
 
-static unsigned char *heap;
-static unsigned int heap_size = 0;
-static unsigned int heap_used = 0;
-
-/* One reusable I/O buffer and one shared decode arena: decoded pixels are
- * scaled down to a display bitmap, then the arena is reused for the next
- * image.  This keeps 4K screenshots inside the 32 MB heap.  The two halves
- * double as the gzip input scratch for page/CSS fetches, where the heap has
- * no room for another multi-megabyte body. */
+/* One reusable I/O buffer: the two halves double as the gzip input scratch
+ * for page/CSS fetches, where the heap has no room for another multi-megabyte
+ * body.  Decode arenas are allocated per image instead of living here. */
 static unsigned char *image_io_buf;
 #define image_file_buf (image_io_buf)
 #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
 #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
 static struct inflate image_inflate_ws;
-static unsigned char *image_arena;
-static unsigned int image_arena_size;
-
-static void *heap_alloc(unsigned int bytes, unsigned int align);
 
 #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
 #error "CSS scratch must fit in image_io_buf"
@@ -289,20 +281,11 @@ static char *trim(char *s)
 
 static int heap_start(void)
 {
-	heap = (unsigned char *)u_mem_alloc(BR_HEAP_INIT);
-	if (!heap) {
-		heap_size = heap_used = 0;
-		return -1;
-	}
-	heap_size = BR_HEAP_INIT;
-	heap_used = 0;
-	image_io_buf = (unsigned char *)heap_alloc(2u * BR_IMG_FILE_MAX, 16);
-	if (!image_io_buf) {
-		heap_size = heap_used = 0;
+	image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
+	if (!image_io_buf)
 		return -1;
-	}
-	page_backbuf = (unsigned short *)heap_alloc(
-		(unsigned int)ui.w * (unsigned int)ui.h * 2u, 16);
+	page_backbuf = (unsigned short *)malloc(
+		(unsigned int)ui.w * (unsigned int)ui.h * 2u);
 	pagebuf_w = page_backbuf ? ui.w : 0;
 	pagebuf_h = page_backbuf ? ui.h : 0;
 	page_cache_valid = 0;
@@ -311,55 +294,19 @@ static int heap_start(void)
 
 static void heap_clear(void)
 {
-	u_mem_free();
-	heap = 0;
-	heap_size = heap_used = 0;
+	heap_reset();
 	image_io_buf = 0;
 	page_backbuf = 0;
 	pagebuf_w = pagebuf_h = 0;
 	page_cache_valid = 0;
-	image_arena = 0;
-	image_arena_size = 0;
-}
-
-static void *heap_alloc(unsigned int bytes, unsigned int align)
-{
-	unsigned int start, want;
-
-	if (!heap || bytes == 0)
-		return 0;
-	if (align < 1)
-		align = 1;
-	if (align & (align - 1))
-		return 0;
-	start = (heap_used + align - 1) & ~(align - 1);
-	if (start > BR_HEAP_MAX || bytes > BR_HEAP_MAX - start)
-		return 0;
-	if (start + bytes > heap_size) {
-		want = heap_size ? heap_size : BR_HEAP_INIT;
-		while (want < start + bytes) {
-			if (want > BR_HEAP_MAX / 2) {
-				want = BR_HEAP_MAX;
-				break;
-			}
-			want *= 2;
-		}
-		if (want < start + bytes || want > BR_HEAP_MAX)
-			return 0;
-		if (u_mem_grow(want) != 0)
-			return 0;
-		heap_size = want;
-	}
-	heap_used = start + bytes;
-	return heap + start;
 }
 
 static void browser_rules_alloc(void)
 {
 	struct br_rule *rules;
 
-	rules = (struct br_rule *)heap_alloc(
-		(unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)), 16);
+	rules = (struct br_rule *)malloc(
+		(unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
 	br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
 }
 
@@ -403,6 +350,7 @@ static int decode_image_data(const unsigned char *data, unsigned int len,
 	struct img_options opt;
 	struct img_mem mem;
 	struct img_image decoded;
+	unsigned char *arena;
 	unsigned int est, bytes, i;
 	unsigned short *px;
 	unsigned char *alpha = 0;
@@ -413,28 +361,25 @@ static int decode_image_data(const unsigned char *data, unsigned int len,
 		return -1;
 	}
 	est = img_estimate(&info);
-	if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA) {
+	if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
 		s_copy(bi->err, "image too large", sizeof(bi->err));
 		return -1;
 	}
-	if (!image_arena) {
-		image_arena = (unsigned char *)heap_alloc(BR_IMG_ARENA, 16);
-		if (!image_arena) {
-			s_copy(bi->err, "out of memory", sizeof(bi->err));
-			return -1;
-		}
-		image_arena_size = BR_IMG_ARENA;
+	arena = (unsigned char *)malloc(est);
+	if (!arena) {
+		s_copy(bi->err, "out of memory", sizeof(bi->err));
+		return -1;
 	}
-	img_mem_init(&mem, image_arena, image_arena_size);
+	img_mem_init(&mem, arena, est);
 	opt.max_pixels = BR_IMG_PIX_MAX;
 	r = img_decode(data, len, &opt, &mem, &decoded);
 	if (r != 0) {
 		s_copy(bi->err, img_error_string(r), sizeof(bi->err));
-		return -1;
+		goto fail;
 	}
 	if (decoded.w == 0 || decoded.h == 0) {
 		s_copy(bi->err, "empty image", sizeof(bi->err));
-		return -1;
+		goto fail;
 	}
 	bi->native_w = (int)decoded.w;
 	bi->native_h = (int)decoded.h;
@@ -451,18 +396,18 @@ static int decode_image_data(const unsigned char *data, unsigned int len,
 	if (dw < 1)
 		dw = 1;
 	bytes = (unsigned int)dw * (unsigned int)dh * 2u;
-	px = (unsigned short *)heap_alloc(bytes, 16);
+	px = (unsigned short *)malloc(bytes);
 	if (!px) {
 		s_copy(bi->err, "out of memory", sizeof(bi->err));
-		return -1;
+		goto fail;
 	}
 	/* Keep the alpha plane for the scaled image so transparent logos and
 	 * icons composite over the page instead of the browser's dark theme
 	 * background.  Very large alpha images stay flattened to bound the
 	 * heap use. */
 	if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
-		alpha = (unsigned char *)heap_alloc((unsigned int)dw *
-						    (unsigned int)dh, 16);
+		alpha = (unsigned char *)malloc((unsigned int)dw *
+						(unsigned int)dh);
 		if (alpha) {
 			for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
 				alpha[i] = 255;
@@ -498,7 +443,12 @@ static int decode_image_data(const unsigned char *data, unsigned int len,
 	bi->img.alpha = alpha;
 	bi->img.flags = 0;
 	bi->state = 1;
+	free(arena);
 	return 0;
+
+fail:
+	free(arena);
+	return -1;
 }
 
 /* ---- URL / local path handling ---- */
@@ -1046,13 +996,14 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 		ctype[0] = '\0';
 
 	if (url[0] == '/') {
-		buf = (unsigned char *)heap_alloc(cap, 16);
+		buf = (unsigned char *)malloc(cap);
 		if (!buf) {
 			s_copy(err, "out of memory", errcap);
 			return -1;
 		}
 		rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf, (int)cap);
 		if (rv < 0) {
+			free(buf);
 			s_copy(err, "file not found", errcap);
 			return -1;
 		}
@@ -1068,19 +1019,24 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 		return 0;
 	}
 
-	buf = (unsigned char *)heap_alloc(cap, 16);
+	buf = (unsigned char *)malloc(cap);
 	if (!buf) {
 		s_copy(err, "out of memory", errcap);
 		return -1;
 	}
 	rv = fetch_remote(url, cap, buf, cap, image_io_buf, BR_PAGE_COMP_MAX,
 			  &fetch_meta, &tr, err, errcap);
-	if (rv == FETCH_ABORT)
+	if (rv == FETCH_ABORT) {
+		free(buf);
 		return FETCH_ABORT;
-	if (rv < 0)
+	}
+	if (rv < 0) {
+		free(buf);
 		return -1;
+	}
 	len = (unsigned int)rv;
 	if (len == 0) {
+		free(buf);
 		s_copy(err, "empty response", errcap);
 		return -1;
 	}
@@ -1095,9 +1051,8 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 	return 0;
 }
 
-/* Fetch an image into the fixed scratch buffers.  The page heap is already
- * carrying the 24 MB decode arena and every scaled bitmap, so images must not
- * allocate their file body from it as well. */
+/* Fetch an image into the fixed scratch buffers.  The scaled bitmaps live on
+ * the heap, so images must not allocate their file body from it as well. */
 static int fetch_image(const char *url, unsigned int cap,
 		       unsigned char **out, unsigned int *outlen,
 		       char *err, unsigned int errcap)
@@ -1140,7 +1095,7 @@ static int fetch_image(const char *url, unsigned int cap,
 
 /* Read one stylesheet into the shared static buffer.  CSS is parsed
  * immediately, so it does not need the page heap; this leaves the heap for
- * the 2 MB page body, the decode arena and the scaled image bitmaps. */
+ * the 2 MB page body, the rules and the scaled image bitmaps. */
 static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
 		     char *err, unsigned int errcap)
 {

+ 4 - 1
docs/development.html

@@ -177,6 +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>
 				</tbody>
 			</table>
 		</div>
@@ -252,6 +253,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>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>
 		</ul>
@@ -272,7 +274,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 	<section id="conventions">
 		<h2>Conventions &amp; gotchas</h2>
 		<ul>
-			<li><strong>Freestanding C.</strong> No libc, no <code>malloc</code>, no <code>printf</code>. Use <code>io_putstr</code>, <code>io_putchar</code> and <code>io_puthex</code>.</li>
+			<li><strong>Freestanding C.</strong> The kernel has no libc, <code>malloc</code> or <code>printf</code>; use <code>io_putstr</code>, <code>io_putchar</code> and <code>io_puthex</code>. Ring-3 commands may link <code>libc.a</code> from <span class="file">libc/</span>; link it explicitly and compile the app with <code>-Ilibc/include</code>.</li>
 			<li><strong>Fresh memory is not zeroed.</strong> Clear structures whose fields are read before being written. QEMU starts RAM clear and hides the bug.</li>
 			<li><strong>Keep the memory map in sync.</strong> Hardcoded addresses appear in assembly, C headers and linker scripts; changing one without the others breaks boot or loading.</li>
 			<li><strong>Ring-3 data segments.</strong> An IRET to ring 3 nulls DS/ES/FS/GS whose DPL is below CPL 3. Kernel stubs must restore selector <code>0x23</code> with <code>IRQ_RETURN_DS</code>. QEMU does not model this; only real hardware fails.</li>
@@ -320,6 +322,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 		<h2>Source map</h2>
 		<ul class="filelist">
 			<li><code>Makefile</code> — targets and image rules</li>
+			<li><code>libc/</code>, <code>libc.a</code> — optional ring-3 libc and its host test</li>
 			<li><code>kexec.c</code>, <code>kexec_send.c</code> — serial reload</li>
 			<li><code>netkexec.c</code>, <code>netkexec_send.c</code> — network reload</li>
 			<li><code>netlog.c</code>, <code>netmonitor.c</code> — UDP console</li>

+ 1 - 1
docs/filesystems.html

@@ -176,7 +176,7 @@
 		<h2>ramfs &amp; the command pack</h2>
 		<p>
 			The system root is a compressed command pack, not a disk image. Every
-			ring-3 command is a freestanding ELF linked at <code>0x40000000</code>,
+			ring-3 command is a static ELF linked at <code>0x40000000</code>,
 			packed as <code>bin/&lt;name&gt;</code>, gzipped and wrapped in a
 			one-sector <code>NBROOT1</code> header. At boot the path loads the
 			pack into RAM and <span class="file">ramfs.c</span> inflates it into a

+ 10 - 5
docs/index.html

@@ -43,7 +43,7 @@
 		</p>
 		<div class="meta">
 			<span class="pill accent">i586 · 32-bit</span>
-			<span class="pill">freestanding · no libc</span>
+			<span class="pill">freestanding kernel · ring-3 libc</span>
 			<span class="pill">BIOS + UEFI</span>
 			<span class="pill">serial + net hot reload</span>
 		</div>
@@ -154,7 +154,7 @@
 			keeping the kernel image small.
 		</p>
 		<ul>
-			<li><strong>Freestanding C.</strong> No libc, no <code>malloc</code>, no <code>printf</code>, no external runtime. Formatting and allocation are in-tree.</li>
+			<li><strong>Freestanding C.</strong> The kernel has no libc, <code>malloc</code> or <code>printf</code>; ring-3 commands can link the in-tree <code>libc.a</code> (<code>malloc</code>, strings, stdlib). Formatting and allocation are in-tree either way.</li>
 			<li><strong>i586 baseline.</strong> Builds use <code>-march=i586 -mno-sse -mno-sse2 -mno-mmx</code>; SSE2 drawing paths are probed at runtime.</li>
 			<li><strong>Identity-mapped paging.</strong> Physical and virtual addresses are equal. There is no per-process address space or isolation.</li>
 			<li><strong>128 MB physical ceiling.</strong> The frame bitmap covers 128 MB; anything above that is unmapped.</li>
@@ -192,7 +192,7 @@
 			</a>
 			<a class="card" href="memory.html">
 				<h3>Memory &amp; paging</h3>
-				<p>E820 map, 4 KB frame bitmap, kmalloc, process stacks, user arena and the hardcoded address ladder.</p>
+				<p>E820 map, 4 KB frame bitmap, kmalloc, process stacks, the ring-3 arena and libc malloc, and the hardcoded address ladder.</p>
 				<span class="card-tag">memory.html</span>
 			</a>
 			<a class="card" href="cpu.html">
@@ -222,9 +222,14 @@
 			</a>
 			<a class="card" href="userland.html">
 				<h3>Userland</h3>
-				<p>Ring-3 address space, ELF loading, syscall groups, PATH dispatch, the command pack and GUI apps.</p>
+				<p>Ring-3 address space, ELF loading, syscall groups, the optional libc and malloc, PATH dispatch, the command pack and GUI apps.</p>
 				<span class="card-tag">userland.html</span>
 			</a>
+			<a class="card" href="userland.html#libc">
+				<h3>Ring-3 libc</h3>
+				<p>Optional static <code>libc.a</code>: boundary-tag malloc/free/realloc, strings, stdlib and heap_reset over the 32 MB SYS_MEM arena.</p>
+				<span class="card-tag">userland.html#libc</span>
+			</a>
 			<a class="card" href="development.html">
 				<h3>Development</h3>
 				<p>Toolchain, build images, QEMU targets, serial/network reload, tests and low-level debugging tools.</p>
@@ -264,7 +269,7 @@
 					</tr>
 					<tr>
 						<td>Userland</td>
-						<td><span class="file">ucmd_*.c</span> <span class="file">ucmd_lib.h</span> <span class="file">ngui.c</span> <span class="file">browser.c</span> <span class="file">gallery.c</span></td>
+						<td><span class="file">ucmd_*.c</span> <span class="file">ucmd_lib.h</span> <span class="file">libc/</span> <span class="file">ngui.c</span> <span class="file">browser.c</span> <span class="file">gallery.c</span></td>
 					</tr>
 					<tr>
 						<td>Build &amp; pack</td>

+ 20 - 3
docs/memory.html

@@ -214,9 +214,13 @@
 			<span class="file">sys_fs.c</span> file loads use it.
 		</p>
 		<p>
-			The kernel heap is not a general-purpose userspace allocator. Ring-3
-			processes get one anonymous arena through <code>SYS_MEM_ALLOC</code>,
-			<code>SYS_MEM_GROW</code> and <code>SYS_MEM_FREE</code>.
+			The kernel heap is separate from userspace. Ring-3 processes get one
+			anonymous arena through <code>SYS_MEM_ALLOC</code>,
+			<code>SYS_MEM_GROW</code> and <code>SYS_MEM_FREE</code>; commands
+			that link <span class="file">libc.a</span> manage it with
+			<code>malloc</code>/<code>free</code> from
+			<span class="file">libc/malloc.c</span>, while small commands may
+			still use the raw syscalls. A process must not mix the two.
 		</p>
 	</section>
 
@@ -267,6 +271,17 @@
 				</tbody>
 			</table>
 		</div>
+		<p>
+			Commands that link <span class="file">libc.a</span> treat that arena
+			as a real heap: <span class="file">libc/malloc.c</span> maps 64 KB on
+			first use, grows in page-rounded steps with 64 KB slack, and uses
+			boundary-tag blocks with a first-fit free list and immediate
+			coalescing. <code>heap_reset()</code> discards everything and unmaps
+			the arena; the browser calls it on navigation, so page-scoped
+			allocations (body, rules, image bitmaps and decode arenas) go back
+			to the frame allocator. A single allocation near 32 MB fails because
+			block headers count against the same cap.
+		</p>
 		<p>
 			Kernel stacks are 4 KB pages from the frame allocator, with an 8-stack
 			static fallback pool in BSS. The idle/bootstrap context uses the
@@ -305,6 +320,8 @@
 		<ul class="filelist">
 			<li><code>mm.c</code>, <code>mm.h</code> — E820 + bitmap allocator</li>
 			<li><code>kmalloc.c</code>, <code>kmalloc.h</code> — kernel heap</li>
+			<li><code>libc/malloc.c</code>, <code>libc/ucmd_mem.c</code> — ring-3 heap and <code>SYS_MEM_*</code> backend</li>
+			<li><code>libc/string.c</code>, <code>libc/stdlib.c</code> — ring-3 libc support</li>
 			<li><code>paging.c</code>, <code>paging.h</code> — identity map</li>
 			<li><code>mtrr.c</code> — write-combining MTRRs</li>
 			<li><code>process.c</code>, <code>process.h</code> — stacks and user layout</li>

+ 45 - 4
docs/userland.html

@@ -35,7 +35,7 @@
 		<p class="kicker">Userland</p>
 		<h1>Commands are ELFs. The shell is a dispatcher.</h1>
 		<p class="lede">
-			Ring-3 programs are freestanding ELFs linked at <code>0x40000000</code>.
+			Ring-3 programs are static ELFs linked at <code>0x40000000</code>.
 			The shell resolves a command name against builtins, the per-terminal
 			PATH and the kernel command registry, then spawns it with one
 			argument string. The command pack supplies 42 PATH commands by default.
@@ -52,6 +52,7 @@
 		<h2>On this page</h2>
 		<ul>
 			<li><a href="#model">Ring-3 model</a></li>
+			<li><a href="#libc">Ring-3 libc</a></li>
 			<li><a href="#spawn">Spawn path</a></li>
 			<li><a href="#syscalls">Syscall ABI</a></li>
 			<li><a href="#shell">Shell &amp; PATH</a></li>
@@ -74,7 +75,7 @@
 			separate address space.
 		</p>
 		<ul>
-			<li><strong>No libc.</strong> Commands include <span class="file">ucmd_lib.h</span> for syscall wrappers and string helpers.</li>
+			<li><strong>Optional libc.</strong> Commands include <span class="file">ucmd_lib.h</span> for syscall wrappers; commands that need allocation or standard string/stdlib functions link the in-tree <span class="file">libc.a</span>.</li>
 			<li><strong>One argument.</strong> The shell passes the raw remainder of the line as a C string at the top of the user stack; <code>_start(const char *arg)</code> needs no crt0.</li>
 			<li><strong>Inherited context.</strong> Each process inherits the spawning terminal's cwd and TTY id; the file syscalls resolve relative paths against the PCB cwd.</li>
 			<li><strong>Page-fault policy.</strong> A ring-3 fault kills the process and prints a short message; it does not halt the kernel.</li>
@@ -87,6 +88,44 @@
 		</div>
 	</section>
 
+	<section id="libc">
+		<h2>Ring-3 libc</h2>
+		<p>
+			<span class="file">libc.a</span> is optional: the Makefile links it
+			only into commands that reference it, and the archive plus
+			<code>--gc-sections</code> keeps unused members and functions out of
+			the legacy command pack. The headers live in
+			<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>.
+		</p>
+		<ul>
+			<li><strong>malloc.</strong> Boundary-tag blocks, first-fit free
+			list, immediate coalescing, 16-byte alignment. The heap maps 64 KB
+			on first use and grows in page-rounded steps with 64 KB slack up to
+			the 32 MB <code>SYS_MEM_*</code> arena cap; <code>calloc</code>
+			zeroes and <code>realloc</code> grows in place when the next block
+			is free.</li>
+			<li><strong>heap_reset.</strong> Discards every allocation and
+			unmaps the whole arena. Page-scoped programs such as the browser
+			use it on navigation instead of tracking individual frees.</li>
+			<li><strong>Ownership.</strong> A command either uses libc
+			<code>malloc</code> or the raw
+			<code>SYS_MEM_ALLOC/GROW/FREE</code> arena, never both. The raw
+			calls remain for small commands that allocate one buffer and exit.</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>
+		</ul>
+	</section>
+
 	<section id="spawn">
 		<h2>Spawn path</h2>
 		<figure class="figure">
@@ -278,8 +317,8 @@
 		</p>
 		<ul>
 			<li><strong>HTML/CSS subset.</strong> External and inline stylesheets, tag/class/id and descendant/child selectors, colours, backgrounds, font size, weights, margins, padding, borders, alignment, percentage widths, basic floats and <code>@media</code> blocks evaluated at a fixed 1000 px viewport.</li>
-			<li><strong>Not supported.</strong> JavaScript, forms, flex/grid, CSS variables, absolute/fixed positioning, standalone image documents, tables with column widths, video/audio.</li>
-			<li><strong>Caps.</strong> 2 MB page body, 832 KB CSS, 6144 DOM nodes, 2304 rules, 16 images; images are downscaled to at most 1000 px wide and decoded into a 24 MB shared arena.</li>
+			<li><strong>Not supported.</strong> JavaScript, forms, pseudo-classes, border-radius clipping of descendants, gradients/box-shadow/transitions and CSS <code>color-mix</code>. Flex rows, card grids, basic tables, inline SVG and CSS variables are supported.</li>
+			<li><strong>Caps.</strong> 2 MB page body, 832 KB CSS, 6144 DOM nodes, 4608 rules, 16 images. Each image gets an <code>img_estimate()</code>-sized decode arena that is freed after the scaled bitmap is made; navigation calls <code>heap_reset()</code> and unmaps the page heap.</li>
 			<li><strong>Fetching.</strong> Each network fetch starts a one-shot helper process and a fresh TCP/TLS connection; images load one per loop within the viewport plus 160 px.</li>
 			</ul>
 		<p>
@@ -301,6 +340,8 @@
 			<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.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>
 			<li><code>ucmd_*.c</code> — commands</li>

+ 15 - 0
libc/include/assert.h

@@ -0,0 +1,15 @@
+/* Minimal freestanding assert.h for ring-3 commands. */
+#ifndef LIBC_ASSERT_H
+#define LIBC_ASSERT_H
+
+#ifdef NDEBUG
+#define assert(expr) ((void)0)
+#else
+void __assert_fail(const char *expr, const char *file, unsigned int line)
+	__attribute__((noreturn));
+
+#define assert(expr) \
+	((expr) ? (void)0 : __assert_fail(#expr, __FILE__, __LINE__))
+#endif
+
+#endif

+ 53 - 0
libc/include/ctype.h

@@ -0,0 +1,53 @@
+/* Minimal freestanding ctype.h for ring-3 commands. */
+#ifndef LIBC_CTYPE_H
+#define LIBC_CTYPE_H
+
+static inline int isdigit(int c)
+{
+	return c >= '0' && c <= '9';
+}
+
+static inline int isxdigit(int c)
+{
+	return (c >= '0' && c <= '9') ||
+	       (c >= 'a' && c <= 'f') ||
+	       (c >= 'A' && c <= 'F');
+}
+
+static inline int isupper(int c)
+{
+	return c >= 'A' && c <= 'Z';
+}
+
+static inline int islower(int c)
+{
+	return c >= 'a' && c <= 'z';
+}
+
+static inline int isalpha(int c)
+{
+	return isupper(c) || islower(c);
+}
+
+static inline int isalnum(int c)
+{
+	return isalpha(c) || isdigit(c);
+}
+
+static inline int isspace(int c)
+{
+	return c == ' ' || c == '\t' || c == '\n' ||
+	       c == '\v' || c == '\f' || c == '\r';
+}
+
+static inline int toupper(int c)
+{
+	return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c;
+}
+
+static inline int tolower(int c)
+{
+	return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c;
+}
+
+#endif

+ 12 - 0
libc/include/stdarg.h

@@ -0,0 +1,12 @@
+/* Minimal freestanding stdarg.h for the ring-3 libc. */
+#ifndef LIBC_STDARG_H
+#define LIBC_STDARG_H
+
+typedef __builtin_va_list va_list;
+
+#define va_start(ap, last) __builtin_va_start(ap, last)
+#define va_end(ap)         __builtin_va_end(ap)
+#define va_arg(ap, type)   __builtin_va_arg(ap, type)
+#define va_copy(dest, src) __builtin_va_copy(dest, src)
+
+#endif

+ 15 - 0
libc/include/stddef.h

@@ -0,0 +1,15 @@
+/* Minimal freestanding stddef.h for the ring-3 libc. */
+#ifndef LIBC_STDDEF_H
+#define LIBC_STDDEF_H
+
+typedef __SIZE_TYPE__ size_t;
+typedef __PTRDIFF_TYPE__ ptrdiff_t;
+typedef __WCHAR_TYPE__ wchar_t;
+
+#ifndef NULL
+#define NULL ((void *)0)
+#endif
+
+#define offsetof(type, member) __builtin_offsetof(type, member)
+
+#endif

+ 28 - 0
libc/include/stdint.h

@@ -0,0 +1,28 @@
+/* Minimal freestanding stdint.h for the ring-3 libc. */
+#ifndef LIBC_STDINT_H
+#define LIBC_STDINT_H
+
+typedef __INT8_TYPE__ int8_t;
+typedef __UINT8_TYPE__ uint8_t;
+typedef __INT16_TYPE__ int16_t;
+typedef __UINT16_TYPE__ uint16_t;
+typedef __INT32_TYPE__ int32_t;
+typedef __UINT32_TYPE__ uint32_t;
+typedef __INT64_TYPE__ int64_t;
+typedef __UINT64_TYPE__ uint64_t;
+
+typedef __INTPTR_TYPE__ intptr_t;
+typedef __UINTPTR_TYPE__ uintptr_t;
+typedef __INTMAX_TYPE__ intmax_t;
+typedef __UINTMAX_TYPE__ uintmax_t;
+
+#define INT8_MAX   0x7f
+#define INT16_MAX  0x7fff
+#define INT32_MAX  0x7fffffff
+#define INT64_MAX  0x7fffffffffffffffLL
+#define UINT8_MAX  0xffu
+#define UINT16_MAX 0xffffu
+#define UINT32_MAX 0xffffffffu
+#define UINT64_MAX 0xffffffffffffffffULL
+
+#endif

+ 20 - 0
libc/include/stdlib.h

@@ -0,0 +1,20 @@
+/* Minimal freestanding stdlib.h for ring-3 commands. */
+#ifndef LIBC_STDLIB_H
+#define LIBC_STDLIB_H
+
+#include <stddef.h>
+
+void *malloc(size_t size);
+void free(void *ptr);
+void *calloc(size_t nmemb, size_t size);
+void *realloc(void *ptr, size_t size);
+
+int abs(int value);
+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 *));
+
+void exit(int status) __attribute__((noreturn));
+void abort(void) __attribute__((noreturn));
+
+#endif

+ 23 - 0
libc/include/string.h

@@ -0,0 +1,23 @@
+/* Minimal freestanding string.h for ring-3 commands. */
+#ifndef LIBC_STRING_H
+#define LIBC_STRING_H
+
+#include <stddef.h>
+
+void *memcpy(void *dst, const void *src, size_t n);
+void *memmove(void *dst, const void *src, size_t n);
+void *memset(void *dst, int c, size_t n);
+int memcmp(const void *a, const void *b, size_t n);
+
+size_t strlen(const char *s);
+char *strcpy(char *dst, const char *src);
+char *strncpy(char *dst, const char *src, size_t n);
+char *strcat(char *dst, const char *src);
+int strcmp(const char *a, const char *b);
+int strncmp(const char *a, const char *b, size_t n);
+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);
+
+#endif

+ 11 - 0
libc/include/ucmd_heap.h

@@ -0,0 +1,11 @@
+/* Ring-3 libc heap extensions (see libc/malloc.c).
+ *
+ * heap_reset() discards every live allocation and unmaps the whole
+ * SYS_MEM_* arena.  It is intended for page-scoped programs such as the
+ * browser; every pointer obtained from malloc becomes invalid. */
+#ifndef LIBC_UCMD_HEAP_H
+#define LIBC_UCMD_HEAP_H
+
+void heap_reset(void);
+
+#endif

+ 442 - 0
libc/malloc.c

@@ -0,0 +1,442 @@
+/* Ring-3 heap allocator: boundary-tag blocks with first-fit free lists.
+ *
+ * The heap lives in the process's single SYS_MEM_* arena at USER_HEAP_BASE.
+ * It is mapped lazily (64 KB at first use) and grows in page-granular steps
+ * with a small slack, so a large image arena does not reserve the whole
+ * 32 MB window.  heap_reset() unmaps everything for page-scoped programs.
+ *
+ * There are no threads in ring 3 and the arena is private to the process, so
+ * no locking is needed.  malloc() returns 16-byte aligned memory; calloc()
+ * zeroes, malloc() does not (grown pages are not zeroed by the kernel).
+ *
+ * Block layout:
+ *
+ *   +0   size      total block size, low bit = free
+ *   +4   prev_size size of the preceding physical block (0 at the base)
+ *   +8   magic     ALLOC_MAGIC or FREE_MAGIC (double-free guard)
+ *   +12  reserved
+ *   +16  payload
+ *
+ * Free blocks keep their next/prev links in the first 8 payload bytes.  The
+ * minimum block is therefore 32 bytes.
+ */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ucmd_heap.h>
+
+#define HEAP_INIT_BYTES  (64u * 1024u)
+#define HEAP_MAX_BYTES   (32u * 1024u * 1024u)
+#define HEAP_GROW_SLACK  (64u * 1024u)
+#define HEAP_ALIGN       16u
+#define HDR_SIZE         16u
+#define MIN_BLOCK        32u
+
+#define FREE_BIT         1u
+#define ALLOC_MAGIC      0x4B424C4Eu     /* "NBLK" */
+#define FREE_MAGIC       0x45455246u     /* "FREE" */
+
+struct blk {
+	unsigned int size;
+	unsigned int prev_size;
+	unsigned int magic;
+	unsigned int reserved;
+};
+
+struct freelink {
+	struct blk *next;
+	struct blk *prev;
+};
+
+/* Implemented by libc/ucmd_mem.c (target) or the host test backend. */
+void *__heap_map(unsigned int bytes);
+int __heap_grow(unsigned int total_bytes);
+void __heap_unmap(void);
+
+static unsigned char *heap_base;
+static unsigned int heap_bytes;     /* mapped bytes */
+static unsigned int heap_end;       /* end of the top block */
+static struct blk *top_blk;
+static struct blk *free_head;
+static int heap_ready;
+
+static unsigned int align_up(unsigned int n)
+{
+	return (n + (HEAP_ALIGN - 1u)) & ~(HEAP_ALIGN - 1u);
+}
+
+static unsigned int blk_size(const struct blk *b)
+{
+	return b->size & ~FREE_BIT;
+}
+
+static int blk_is_free(const struct blk *b)
+{
+	return (b->size & FREE_BIT) != 0;
+}
+
+static struct blk *blk_at(unsigned int off)
+{
+	return (struct blk *)(void *)(heap_base + off);
+}
+
+static unsigned int blk_off(const struct blk *b)
+{
+	return (unsigned int)((const unsigned char *)b - heap_base);
+}
+
+static struct blk *blk_next(struct blk *b)
+{
+	unsigned int off = blk_off(b) + blk_size(b);
+
+	if (off >= heap_end)
+		return 0;
+	return blk_at(off);
+}
+
+static struct freelink *blk_link(struct blk *b)
+{
+	return (struct freelink *)(void *)((unsigned char *)b + HDR_SIZE);
+}
+
+static void free_list_insert(struct blk *b)
+{
+	struct freelink *f = blk_link(b);
+
+	f->prev = 0;
+	f->next = free_head;
+	if (free_head)
+		blk_link(free_head)->prev = b;
+	free_head = b;
+}
+
+static void free_list_remove(struct blk *b)
+{
+	struct freelink *f = blk_link(b);
+
+	if (f->prev)
+		blk_link(f->prev)->next = f->next;
+	else
+		free_head = f->next;
+	if (f->next)
+		blk_link(f->next)->prev = f->prev;
+}
+
+/* Split an allocated block so that it is exactly `need` bytes.  If the
+ * remainder is too small to form a block, keep the whole block. */
+static void split_allocated(struct blk *b, unsigned int need)
+{
+	unsigned int old = blk_size(b);
+	struct blk *rest;
+	struct blk *after;
+
+	if (old - need >= MIN_BLOCK) {
+		rest = (struct blk *)(void *)((unsigned char *)b + need);
+		rest->size = (old - need) | FREE_BIT;
+		rest->prev_size = need;
+		rest->magic = FREE_MAGIC;
+		rest->reserved = 0;
+
+		b->size = need;
+		b->magic = ALLOC_MAGIC;
+
+		after = blk_next(rest);
+		if (after)
+			after->prev_size = blk_size(rest);
+		if (b == top_blk)
+			top_blk = rest;
+		free_list_insert(rest);
+	} else {
+		b->size = old;
+		b->magic = ALLOC_MAGIC;
+	}
+}
+
+/* Free `b`, merging it with a free predecessor and successor when possible. */
+static void free_block(struct blk *b)
+{
+	struct blk *prev;
+	struct blk *next;
+	struct blk *after;
+	unsigned int merged;
+
+	b->size |= FREE_BIT;
+	b->magic = FREE_MAGIC;
+
+	if (b->prev_size) {
+		prev = (struct blk *)(void *)((unsigned char *)b - b->prev_size);
+		if (blk_is_free(prev)) {
+			free_list_remove(prev);
+			merged = blk_size(prev) + blk_size(b);
+			prev->size = merged | FREE_BIT;
+			prev->magic = FREE_MAGIC;
+			if (b == top_blk)
+				top_blk = prev;
+			after = blk_next(prev);
+			if (after)
+				after->prev_size = merged;
+			b = prev;
+		}
+	}
+
+	next = blk_next(b);
+	if (next && blk_is_free(next)) {
+		free_list_remove(next);
+		merged = blk_size(b) + blk_size(next);
+		b->size = merged | FREE_BIT;
+		b->magic = FREE_MAGIC;
+		if (next == top_blk)
+			top_blk = b;
+		after = blk_next(b);
+		if (after)
+			after->prev_size = merged;
+	}
+
+	free_list_insert(b);
+}
+
+/* Extend the mapped arena so that the top block ends at or past
+ * `need_total`, then merge the new region into the top block. */
+static int heap_extend(unsigned int need_total)
+{
+	unsigned int old = heap_bytes;
+	unsigned int target;
+	struct blk *b;
+
+	if (need_total > HEAP_MAX_BYTES)
+		return -1;
+
+	target = need_total;
+	if (target < old + HEAP_GROW_SLACK)
+		target = old + HEAP_GROW_SLACK;
+	if (target > HEAP_MAX_BYTES)
+		target = HEAP_MAX_BYTES;
+	target = (target + 4095u) & ~4095u;
+	if (target > HEAP_MAX_BYTES)
+		target = HEAP_MAX_BYTES;
+	if (target < need_total || target <= old)
+		return -1;
+
+	if (__heap_grow(target) != 0)
+		return -1;
+	heap_bytes = target;
+
+	if (top_blk && blk_is_free(top_blk)) {
+		/* The top block already reaches `old`; extend it in place. */
+		free_list_remove(top_blk);
+		top_blk->size = (blk_size(top_blk) + (target - old)) | FREE_BIT;
+		top_blk->magic = FREE_MAGIC;
+		free_list_insert(top_blk);
+	} else {
+		b = blk_at(old);
+		b->size = (target - old) | FREE_BIT;
+		b->prev_size = top_blk ? blk_size(top_blk) : 0;
+		b->magic = FREE_MAGIC;
+		b->reserved = 0;
+		free_list_insert(b);
+		top_blk = b;
+	}
+	heap_end = target;
+	return 0;
+}
+
+static int heap_init(void)
+{
+	struct blk *b;
+	void *base;
+
+	if (heap_ready)
+		return 0;
+
+	base = __heap_map(HEAP_INIT_BYTES);
+	if (!base)
+		return -1;
+	if ((unsigned long)base & (HEAP_ALIGN - 1u)) {
+		__heap_unmap();
+		return -1;
+	}
+
+	heap_base = (unsigned char *)base;
+	heap_bytes = HEAP_INIT_BYTES;
+	heap_end = HEAP_INIT_BYTES;
+	free_head = 0;
+
+	b = blk_at(0);
+	b->size = HEAP_INIT_BYTES | FREE_BIT;
+	b->prev_size = 0;
+	b->magic = FREE_MAGIC;
+	b->reserved = 0;
+	top_blk = b;
+	free_list_insert(b);
+	heap_ready = 1;
+	return 0;
+}
+
+static void *alloc_block(unsigned int need)
+{
+	struct blk *b = free_head;
+	void *payload;
+
+	while (b && blk_size(b) < need)
+		b = blk_link(b)->next;
+
+	if (!b) {
+		if (heap_extend(heap_end + need) != 0)
+			return 0;
+		b = free_head;
+		while (b && blk_size(b) < need)
+			b = blk_link(b)->next;
+		if (!b)
+			return 0;
+	}
+
+	free_list_remove(b);
+	payload = (void *)((unsigned char *)b + HDR_SIZE);
+	split_allocated(b, need);
+	return payload;
+}
+
+void *malloc(size_t size)
+{
+	unsigned int need;
+
+	if (size == 0 || size > HEAP_MAX_BYTES)
+		return 0;
+	if (size > (size_t)(HEAP_MAX_BYTES - HDR_SIZE))
+		return 0;
+	if (!heap_ready && heap_init() != 0)
+		return 0;
+
+	need = align_up(HDR_SIZE + (unsigned int)size);
+	if (need < MIN_BLOCK)
+		need = MIN_BLOCK;
+	if (need > HEAP_MAX_BYTES)
+		return 0;
+	return alloc_block(need);
+}
+
+static struct blk *block_from_ptr(void *ptr)
+{
+	unsigned char *p = (unsigned char *)ptr;
+	struct blk *b;
+	unsigned int size;
+
+	if (!heap_ready || !ptr)
+		return 0;
+	if (p < heap_base + HDR_SIZE || p >= heap_base + heap_bytes)
+		return 0;
+
+	b = (struct blk *)(void *)(p - HDR_SIZE);
+	if (b->magic != ALLOC_MAGIC)
+		return 0;
+	size = blk_size(b);
+	if (size < MIN_BLOCK || (unsigned char *)b + size > heap_base + heap_bytes)
+		return 0;
+	return b;
+}
+
+void free(void *ptr)
+{
+	struct blk *b = block_from_ptr(ptr);
+
+	if (b)
+		free_block(b);
+}
+
+void *calloc(size_t nmemb, size_t size)
+{
+	size_t total;
+	void *p;
+
+	if (nmemb == 0 || size == 0)
+		return 0;
+	if (nmemb > (size_t)-1 / size)
+		return 0;
+	total = nmemb * size;
+	if (total > HEAP_MAX_BYTES)
+		return 0;
+
+	p = malloc(total);
+	if (p)
+		memset(p, 0, total);
+	return p;
+}
+
+void *realloc(void *ptr, size_t size)
+{
+	struct blk *b;
+	struct blk *next;
+	unsigned int old;
+	unsigned int need;
+	unsigned int merged;
+	unsigned int copy;
+
+	if (!ptr)
+		return malloc(size);
+	if (size == 0) {
+		free(ptr);
+		return 0;
+	}
+	if (size > HEAP_MAX_BYTES ||
+	    size > (size_t)(HEAP_MAX_BYTES - HDR_SIZE))
+		return 0;
+
+	b = block_from_ptr(ptr);
+	if (!b)
+		return 0;
+
+	need = align_up(HDR_SIZE + (unsigned int)size);
+	if (need < MIN_BLOCK)
+		need = MIN_BLOCK;
+
+	old = blk_size(b);
+	if (need <= old) {
+		split_allocated(b, need);
+		return ptr;
+	}
+
+	next = blk_next(b);
+	if (next && blk_is_free(next) && old + blk_size(next) >= need) {
+		free_list_remove(next);
+		merged = old + blk_size(next);
+		b->size = merged;
+		b->magic = ALLOC_MAGIC;
+		if (next == top_blk) {
+			top_blk = b;
+		} else {
+			struct blk *after = blk_next(b);
+
+			if (after)
+				after->prev_size = merged;
+		}
+		split_allocated(b, need);
+		return ptr;
+	}
+
+	{
+		void *np = malloc(size);
+
+		if (!np)
+			return 0;
+		copy = old - HDR_SIZE;
+		if (copy > size)
+			copy = (unsigned int)size;
+		memcpy(np, ptr, copy);
+		free(ptr);
+		return np;
+	}
+}
+
+void heap_reset(void)
+{
+	if (!heap_ready)
+		return;
+	__heap_unmap();
+	heap_base = 0;
+	heap_bytes = 0;
+	heap_end = 0;
+	top_blk = 0;
+	free_head = 0;
+	heap_ready = 0;
+}

+ 162 - 0
libc/stdlib.c

@@ -0,0 +1,162 @@
+/* Minimal freestanding stdlib support for ring-3 commands. */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <ucmd_lib.h>
+
+int abs(int value)
+{
+	return value < 0 ? -value : value;
+}
+
+long strtol(const char *str, char **endptr, int base)
+{
+	const char *p = str;
+	int negative = 0;
+	int any = 0;
+	unsigned long value = 0;
+
+	if (!str) {
+		if (endptr)
+			*endptr = (char *)str;
+		return 0;
+	}
+
+	while (*p == ' ' || *p == '\t' || *p == '\n' ||
+	       *p == '\v' || *p == '\f' || *p == '\r')
+		p++;
+
+	if (*p == '+' || *p == '-') {
+		negative = (*p == '-');
+		p++;
+	}
+
+	if ((base == 0 || base == 16) && p[0] == '0' &&
+	    (p[1] == 'x' || p[1] == 'X')) {
+		base = 16;
+		p += 2;
+	} else if (base == 0) {
+		base = (p[0] == '0') ? 8 : 10;
+	}
+
+	if (base < 2 || base > 36) {
+		if (endptr)
+			*endptr = (char *)str;
+		return 0;
+	}
+
+	for (;;) {
+		int digit;
+
+		if (*p >= '0' && *p <= '9')
+			digit = *p - '0';
+		else if (*p >= 'a' && *p <= 'z')
+			digit = *p - 'a' + 10;
+		else if (*p >= 'A' && *p <= 'Z')
+			digit = *p - 'A' + 10;
+		else
+			break;
+		if (digit >= base)
+			break;
+		value = value * (unsigned long)base + (unsigned long)digit;
+		any = 1;
+		p++;
+	}
+
+	if (!any) {
+		if (endptr)
+			*endptr = (char *)str;
+		return 0;
+	}
+	if (endptr)
+		*endptr = (char *)p;
+	return negative ? -(long)value : (long)value;
+}
+
+static void swap_bytes(unsigned char *a, unsigned char *b, size_t n)
+{
+	while (n--) {
+		unsigned char t = *a;
+
+		*a++ = *b;
+		*b++ = t;
+	}
+}
+
+/* Sift element `start` down in a max heap. */
+static void sift_down(unsigned char *base, size_t start, size_t end,
+		      size_t size, int (*compar)(const void *, const void *))
+{
+	size_t root = start;
+
+	while (root * 2 + 1 <= end) {
+		size_t child = root * 2 + 1;
+
+		if (child + 1 <= end &&
+		    compar(base + child * size, base + (child + 1) * size) < 0)
+			child++;
+		if (compar(base + root * size, base + child * size) < 0) {
+			swap_bytes(base + root * size, base + child * size, size);
+			root = child;
+		} else {
+			return;
+		}
+	}
+}
+
+void qsort(void *base, size_t nmemb, size_t size,
+	   int (*compar)(const void *, const void *))
+{
+	unsigned char *p = (unsigned char *)base;
+	size_t start;
+	size_t end;
+
+	if (!p || !compar || nmemb < 2 || size == 0)
+		return;
+
+	/* Build the max heap. */
+	start = (nmemb - 2) / 2;
+	for (;;) {
+		sift_down(p, start, nmemb - 1, size, compar);
+		if (start == 0)
+			break;
+		start--;
+	}
+
+	/* Repeatedly move the maximum to the end and shrink the heap. */
+	end = nmemb - 1;
+	while (end > 0) {
+		swap_bytes(p, p + end * size, size);
+		end--;
+		sift_down(p, 0, end, size, compar);
+	}
+}
+
+void exit(int status)
+{
+	u_exit(status);
+	for (;;)
+		;
+}
+
+void abort(void)
+{
+	u_puts("abort\n");
+	u_exit(1);
+	for (;;)
+		;
+}
+
+void __assert_fail(const char *expr, const char *file, unsigned int line)
+{
+	u_puts("assert failed: ");
+	u_puts(expr ? expr : "?");
+	u_puts(" (");
+	u_puts(file ? file : "?");
+	u_puts(":");
+	u_putdec(line);
+	u_puts(")\n");
+	u_exit(1);
+	for (;;)
+		;
+}

+ 19 - 0
libc/strdup.c

@@ -0,0 +1,19 @@
+/* strdup lives in its own object so string.o never pulls in malloc. */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+
+char *strdup(const char *s)
+{
+	size_t n;
+	char *p;
+
+	if (!s)
+		return 0;
+	n = strlen(s) + 1;
+	p = (char *)malloc(n);
+	if (p)
+		memcpy(p, s, n);
+	return p;
+}

+ 163 - 0
libc/string.c

@@ -0,0 +1,163 @@
+/* Minimal freestanding string/memory functions for ring-3 commands. */
+
+#include <stddef.h>
+#include <string.h>
+
+void *memcpy(void *dst, const void *src, size_t n)
+{
+	unsigned char *d = (unsigned char *)dst;
+	const unsigned char *s = (const unsigned char *)src;
+
+	while (n--)
+		*d++ = *s++;
+	return dst;
+}
+
+void *memmove(void *dst, const void *src, size_t n)
+{
+	unsigned char *d = (unsigned char *)dst;
+	const unsigned char *s = (const unsigned char *)src;
+
+	if (d < s) {
+		while (n--)
+			*d++ = *s++;
+	} else if (d > s) {
+		d += n;
+		s += n;
+		while (n--)
+			*--d = *--s;
+	}
+	return dst;
+}
+
+void *memset(void *dst, int c, size_t n)
+{
+	unsigned char *d = (unsigned char *)dst;
+
+	while (n--)
+		*d++ = (unsigned char)c;
+	return dst;
+}
+
+int memcmp(const void *a, const void *b, size_t n)
+{
+	const unsigned char *pa = (const unsigned char *)a;
+	const unsigned char *pb = (const unsigned char *)b;
+
+	while (n--) {
+		if (*pa != *pb)
+			return (int)*pa - (int)*pb;
+		pa++;
+		pb++;
+	}
+	return 0;
+}
+
+size_t strlen(const char *s)
+{
+	const char *p = s;
+
+	while (*p)
+		p++;
+	return (size_t)(p - s);
+}
+
+char *strcpy(char *dst, const char *src)
+{
+	char *d = dst;
+
+	while ((*d++ = *src++) != '\0')
+		;
+	return dst;
+}
+
+char *strncpy(char *dst, const char *src, size_t n)
+{
+	char *d = dst;
+
+	while (n && *src) {
+		*d++ = *src++;
+		n--;
+	}
+	while (n--)
+		*d++ = '\0';
+	return dst;
+}
+
+char *strcat(char *dst, const char *src)
+{
+	char *d = dst;
+
+	while (*d)
+		d++;
+	while ((*d++ = *src++) != '\0')
+		;
+	return dst;
+}
+
+int strcmp(const char *a, const char *b)
+{
+	while (*a && *a == *b) {
+		a++;
+		b++;
+	}
+	return (int)(unsigned char)*a - (int)(unsigned char)*b;
+}
+
+int strncmp(const char *a, const char *b, size_t n)
+{
+	while (n && *a && *a == *b) {
+		a++;
+		b++;
+		n--;
+	}
+	if (n == 0)
+		return 0;
+	return (int)(unsigned char)*a - (int)(unsigned char)*b;
+}
+
+char *strchr(const char *s, int c)
+{
+	char ch = (char)c;
+
+	for (;; s++) {
+		if (*s == ch)
+			return (char *)s;
+		if (*s == '\0')
+			return 0;
+	}
+}
+
+char *strrchr(const char *s, int c)
+{
+	char ch = (char)c;
+	const char *last = 0;
+
+	for (;; s++) {
+		if (*s == ch)
+			last = s;
+		if (*s == '\0')
+			return (char *)last;
+	}
+}
+
+char *strstr(const char *haystack, const char *needle)
+{
+	const char *h;
+	const char *n;
+
+	if (!*needle)
+		return (char *)haystack;
+
+	for (; *haystack; haystack++) {
+		h = haystack;
+		n = needle;
+		while (*h && *n && *h == *n) {
+			h++;
+			n++;
+		}
+		if (!*n)
+			return (char *)haystack;
+	}
+	return 0;
+}

+ 41 - 0
libc/test_host_mem.c

@@ -0,0 +1,41 @@
+/* Host backend for the malloc test: a fixed 32 MB, page-aligned arena.
+ *
+ * New pages are poisoned instead of zeroed, which catches an allocator that
+ * accidentally relies on the kernel's zeroed initial mapping.
+ */
+
+#include <stddef.h>
+#include <string.h>
+
+#define HOST_ARENA_BYTES (32u * 1024u * 1024u)
+
+static unsigned char arena[HOST_ARENA_BYTES] __attribute__((aligned(4096)));
+static unsigned int mapped;
+
+void *__heap_map(unsigned int bytes)
+{
+	if (bytes == 0 || bytes > HOST_ARENA_BYTES || mapped)
+		return 0;
+	mapped = bytes;
+	memset(arena, 0xA5, bytes);
+	return arena;
+}
+
+int __heap_grow(unsigned int total_bytes)
+{
+	if (total_bytes > HOST_ARENA_BYTES || total_bytes < mapped)
+		return -1;
+	memset(arena + mapped, 0xA5, total_bytes - mapped);
+	mapped = total_bytes;
+	return 0;
+}
+
+void __heap_unmap(void)
+{
+	mapped = 0;
+}
+
+unsigned int host_mem_mapped(void)
+{
+	return mapped;
+}

+ 373 - 0
libc/test_malloc.c

@@ -0,0 +1,373 @@
+/* Host stress test for libc/malloc.c.
+ *
+ * The allocator is compiled with the malloc/free/... names renamed to
+ * libc_*, so the host libc stays untouched and the test can use rand/write
+ * without recursion.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+void *libc_malloc(size_t size);
+void libc_free(void *ptr);
+void *libc_calloc(size_t nmemb, size_t size);
+void *libc_realloc(void *ptr, size_t size);
+void libc_heap_reset(void);
+unsigned int host_mem_mapped(void);
+
+#define SLOTS       96
+#define LIVE_CAP    (24u * 1024u * 1024u)
+
+struct slot {
+	unsigned char *p;
+	size_t n;
+	unsigned char pat;
+};
+
+static struct slot slots[SLOTS];
+static unsigned int live_bytes;
+static unsigned int pattern_seed;
+static int failures;
+
+static void out(const char *s)
+{
+	(void)!write(1, s, strlen(s));
+}
+
+static void out_num(unsigned long n)
+{
+	char buf[24];
+	char *p = buf + sizeof(buf);
+
+	*--p = '\0';
+	if (n == 0)
+		*--p = '0';
+	while (n) {
+		*--p = (char)('0' + (n % 10));
+		n /= 10;
+	}
+	out(p);
+}
+
+static void fail(const char *msg)
+{
+	out("FAIL: ");
+	out(msg);
+	out("\n");
+	failures++;
+}
+
+static int ranges_overlap(const void *a, size_t an, const void *b, size_t bn)
+{
+	uintptr_t pa = (uintptr_t)a;
+	uintptr_t pb = (uintptr_t)b;
+
+	return pa < pb + bn && pb < pa + an;
+}
+
+static int overlaps_live(const void *p, size_t n, int skip)
+{
+	int i;
+
+	for (i = 0; i < SLOTS; i++) {
+		if (i == skip || !slots[i].p)
+			continue;
+		if (ranges_overlap(p, n, slots[i].p, slots[i].n))
+			return 1;
+	}
+	return 0;
+}
+
+static void fill(unsigned char *p, size_t n, unsigned char pat)
+{
+	size_t i;
+
+	for (i = 0; i < n; i++)
+		p[i] = pat;
+}
+
+static int check_fill(const unsigned char *p, size_t n, unsigned char pat)
+{
+	size_t i;
+
+	for (i = 0; i < n; i++) {
+		if (p[i] != pat)
+			return 0;
+	}
+	return 1;
+}
+
+static size_t pick_size(void)
+{
+	unsigned int r = (unsigned int)rand();
+
+	if ((r & 63u) == 0)
+		return 1 + (size_t)(rand() % (4 * 1024 * 1024));
+	if ((r & 7u) == 0)
+		return 1 + (size_t)(rand() % (256 * 1024));
+	return 1 + (size_t)(rand() % 8192);
+}
+
+static int find_free_slot(void)
+{
+	int i;
+
+	for (i = 0; i < SLOTS; i++) {
+		if (!slots[i].p)
+			return i;
+	}
+	return -1;
+}
+
+static int find_live_slot(void)
+{
+	int i;
+
+	for (i = 0; i < SLOTS; i++) {
+		if (slots[i].p)
+			return i;
+	}
+	return -1;
+}
+
+static void free_slot(int i)
+{
+	if (i < 0 || !slots[i].p)
+		return;
+	if (!check_fill(slots[i].p, slots[i].n, slots[i].pat))
+		fail("pattern changed before free");
+	libc_free(slots[i].p);
+	live_bytes -= (unsigned int)slots[i].n;
+	slots[i].p = 0;
+	slots[i].n = 0;
+}
+
+static void test_basics(void)
+{
+	unsigned char *p;
+	unsigned char *q;
+	unsigned char *r;
+	size_t i;
+
+	if (libc_malloc(0) != 0)
+		fail("malloc(0) is not NULL");
+	libc_free(0);
+
+	p = (unsigned char *)libc_malloc(100);
+	if (!p) {
+		fail("malloc(100) failed");
+		return;
+	}
+	if ((uintptr_t)p & 15u)
+		fail("malloc is not 16-byte aligned");
+	fill(p, 100, 0x5A);
+	if (!check_fill(p, 100, 0x5A))
+		fail("malloc contents changed");
+	libc_free(p);
+
+	p = (unsigned char *)libc_calloc(1024, 4);
+	if (!p) {
+		fail("calloc failed");
+	} else {
+		for (i = 0; i < 4096; i++) {
+			if (p[i] != 0) {
+				fail("calloc returned non-zero memory");
+				break;
+			}
+		}
+		libc_free(p);
+	}
+
+	p = (unsigned char *)libc_realloc(0, 100);
+	if (!p) {
+		fail("realloc(NULL, 100) failed");
+	} else {
+		fill(p, 100, 0x33);
+		if (libc_realloc(p, 0) != 0)
+			fail("realloc(ptr, 0) did not return NULL");
+	}
+
+	p = (unsigned char *)libc_malloc(1024);
+	q = (unsigned char *)libc_malloc(2048);
+	if (!p || !q) {
+		fail("two small allocations failed");
+		libc_free(p);
+		libc_free(q);
+	} else {
+		fill(p, 1024, 0x11);
+		fill(q, 2048, 0x22);
+		if (overlaps_live(p, 1024, -1) ||
+		    overlaps_live(q, 2048, -1))
+			fail("small allocations overlap");
+		if (!check_fill(p, 1024, 0x11) ||
+		    !check_fill(q, 2048, 0x22))
+			fail("small allocation contents changed");
+		r = (unsigned char *)libc_realloc(p, 8192);
+		if (!r) {
+			fail("realloc grow failed");
+			libc_free(p);
+		} else {
+			if (!check_fill(r, 1024, 0x11))
+				fail("realloc lost the prefix");
+			fill(r, 8192, 0x44);
+			libc_free(r);
+		}
+		libc_free(q);
+	}
+
+	if (libc_calloc((size_t)-1, 2) != 0)
+		fail("calloc overflow did not fail");
+}
+
+static void test_random(void)
+{
+	unsigned int op;
+	int i;
+
+	for (op = 0; op < 4000; op++) {
+		int fslot = find_free_slot();
+		int live = find_live_slot();
+		unsigned int r = (unsigned int)rand();
+
+		if (live < 0 || (fslot >= 0 && (r & 3u) != 0)) {
+			size_t n = pick_size();
+			unsigned char *p;
+			unsigned char pat;
+
+			if (live_bytes + (unsigned int)n > LIVE_CAP &&
+			    live >= 0) {
+				free_slot(live);
+				fslot = find_free_slot();
+			}
+			if (fslot < 0)
+				continue;
+			p = (unsigned char *)libc_malloc(n);
+			if (!p) {
+				fail("random malloc failed");
+				continue;
+			}
+			if ((uintptr_t)p & 15u)
+				fail("random malloc is not 16-byte aligned");
+			if (overlaps_live(p, n, -1))
+				fail("random allocations overlap");
+			pat = (unsigned char)(0x30 + (pattern_seed++ & 0x3F));
+			fill(p, n, pat);
+			slots[fslot].p = p;
+			slots[fslot].n = n;
+			slots[fslot].pat = pat;
+			live_bytes += (unsigned int)n;
+		} else {
+			free_slot(live);
+		}
+	}
+
+	/* A realloc pass over the surviving blocks. */
+	for (i = 0; i < SLOTS; i++) {
+		size_t n;
+		size_t old;
+		unsigned char *p;
+		unsigned char *q;
+		unsigned char pat;
+
+		if (!slots[i].p)
+			continue;
+		old = slots[i].n;
+		n = pick_size();
+		if (n > old && live_bytes + (unsigned int)(n - old) > LIVE_CAP)
+			n = old;
+		p = slots[i].p;
+		q = (unsigned char *)libc_realloc(p, n);
+		if (!q) {
+			fail("random realloc failed");
+			continue;
+		}
+		if (overlaps_live(q, n, i))
+			fail("realloc overlaps another block");
+		if (!check_fill(q, old < n ? old : n, slots[i].pat))
+			fail("realloc lost the prefix");
+		pat = (unsigned char)(0x80 + (pattern_seed++ & 0x3F));
+		fill(q, n, pat);
+		live_bytes = live_bytes - (unsigned int)old + (unsigned int)n;
+		slots[i].p = q;
+		slots[i].n = n;
+		slots[i].pat = pat;
+	}
+}
+
+static void free_all(void)
+{
+	int i;
+
+	for (i = 0; i < SLOTS; i++)
+		free_slot(i);
+	if (live_bytes != 0)
+		fail("live byte count is not zero");
+}
+
+static void test_large(void)
+{
+	unsigned char *p;
+	unsigned char *q;
+	size_t n = 8u * 1024u * 1024u;
+
+	p = (unsigned char *)libc_malloc(n);
+	if (!p) {
+		fail("8 MB allocation failed");
+	} else {
+		fill(p, n, 0x6C);
+		if (!check_fill(p, n, 0x6C))
+			fail("8 MB pattern changed");
+		libc_free(p);
+	}
+
+	p = (unsigned char *)libc_malloc(1024u * 1024u);
+	if (!p) {
+		fail("1 MB allocation failed");
+		return;
+	}
+	fill(p, 1024u * 1024u, 0x21);
+	q = (unsigned char *)libc_realloc(p, 4u * 1024u * 1024u);
+	if (!q) {
+		fail("1 MB -> 4 MB realloc failed");
+		libc_free(p);
+		return;
+	}
+	if (!check_fill(q, 1024u * 1024u, 0x21))
+		fail("large realloc lost the prefix");
+	fill(q, 4u * 1024u * 1024u, 0x42);
+	libc_free(q);
+}
+
+int main(void)
+{
+	unsigned int seed;
+
+	for (seed = 1; seed <= 8; seed++) {
+		srand(seed);
+		pattern_seed = 0;
+		test_basics();
+		test_random();
+		free_all();
+
+		libc_heap_reset();
+		if (host_mem_mapped() != 0)
+			fail("heap_reset did not unmap the arena");
+	}
+
+	test_large();
+	libc_heap_reset();
+	if (host_mem_mapped() != 0)
+		fail("second heap_reset did not unmap the arena");
+
+	if (failures) {
+		out("malloc test: ");
+		out_num((unsigned long)failures);
+		out(" failure(s)\n");
+		return 1;
+	}
+	out("malloc test: OK\n");
+	return 0;
+}

+ 20 - 0
libc/ucmd_mem.c

@@ -0,0 +1,20 @@
+/* Target backend for the ring-3 heap: the SYS_MEM_* arena syscalls. */
+
+#include "ucmd_lib.h"
+
+void *__heap_map(unsigned int bytes)
+{
+	int base = u_syscall1(SYS_MEM_ALLOC, (int)bytes);
+
+	return base < 0 ? 0 : (void *)base;
+}
+
+int __heap_grow(unsigned int total_bytes)
+{
+	return u_syscall1(SYS_MEM_GROW, (int)total_bytes);
+}
+
+void __heap_unmap(void)
+{
+	u_syscall0(SYS_MEM_FREE);
+}

+ 5 - 1
sys_mem.h

@@ -3,7 +3,11 @@
  * Ring-3 commands only have a 2 MB image/stack window, which is not enough
  * for a full-frame image.  This service maps a single growable arena at
  * USER_HEAP_BASE into the caller's page directory.  The reaper frees it with
- * the rest of the process. */
+ * the rest of the process.
+ *
+ * Commands that link the ring-3 libc own this arena through libc/malloc.c
+ * (malloc/free/heap_reset); the raw syscalls are for commands that do not
+ * link libc.  The two must not be mixed in one process. */
 #ifndef SYS_MEM_H
 #define SYS_MEM_H
 

+ 3 - 1
syscall.h

@@ -102,7 +102,9 @@
 
 /* Per-process anonymous heap (see sys_mem.c).  One growable arena at
  * USER_HEAP_BASE (0x60000000), at most USER_HEAP_MAX (32 MB), freed when the
- * process exits.  SYS_MEM_ALLOC returns the base address, or <0. */
+ * process exits.  SYS_MEM_ALLOC returns the base address, or <0.  Commands
+ * that link libc.a use malloc/free (libc/malloc.c) and leave these syscalls
+ * to the libc backend. */
 #define SYS_MEM_ALLOC      88  /* (unsigned bytes) -> VA or <0 */
 #define SYS_MEM_GROW       89  /* (unsigned total_bytes) -> 0/-1; new pages not zeroed */
 #define SYS_MEM_FREE       90  /* () -> 0/-1 */

+ 6 - 4
ucmd_curl.c

@@ -8,6 +8,8 @@
  * The TLS and HTTP code lives in uhttp.c (shared with the browser); this file
  * only keeps the CLI, the helper mode and the verbose output hooks. */
 
+#include <stdlib.h>
+
 #include "ucmd_lib.h"
 #include "uhttp.h"
 
@@ -209,7 +211,7 @@ static void fetch_once(void)
 	if (cap == 0 || cap > FETCH_MAX)
 		cap = FETCH_MAX;
 
-	buf = (unsigned char *)u_mem_alloc(FETCH_MAX);
+	buf = (unsigned char *)malloc(FETCH_MAX);
 	if (!buf) {
 		fetch_fail(0, -1, "", "", "");
 		u_exit(1);
@@ -223,7 +225,7 @@ static void fetch_once(void)
 			   (int)body_len);
 	write_meta(0, 0, &h, err, body_len, body_trunc);
 	uhttp_close(&h);
-	u_mem_free();
+	free(buf);
 	u_exit(err ? 1 : 0);
 }
 
@@ -238,7 +240,7 @@ static void fetch_serve(void)
 	unsigned char *buf;
 	unsigned int last_seq = 0, idle = 0;
 
-	buf = (unsigned char *)u_mem_alloc(FETCH_MAX);
+	buf = (unsigned char *)malloc(FETCH_MAX);
 	if (!buf)
 		u_exit(1);
 	uhttp_init(&h);
@@ -304,7 +306,7 @@ static void fetch_serve(void)
 	}
 	h.keepalive = 0;
 	uhttp_close(&h);
-	u_mem_free();
+	free(buf);
 	u_exit(0);
 }
 

+ 3 - 1
ucmd_lib.h

@@ -395,7 +395,9 @@ static inline int u_power_info(struct sys_powerinfo *out, unsigned int flags)
 	return u_syscall2(SYS_POWER_INFO, (int)out, (int)flags);
 }
 
-/* Per-process anonymous heap: one growable arena, freed at exit. */
+/* Raw per-process anonymous heap.  Commands that link libc.a should use
+ * malloc/free instead; never mix these raw calls with the libc heap in one
+ * process, because both own the same SYS_MEM_* arena. */
 static inline void *u_mem_alloc(unsigned int bytes)
 {
 	int r = u_syscall1(SYS_MEM_ALLOC, (int)bytes);

+ 26 - 29
ucmd_view.c

@@ -1,8 +1,10 @@
 /* view: image viewer built on the img library and the ngui toolkit.
  *
  * Usage: view <file>.  The command owns a canvas window, reads the whole file
- * through the kernel file service, decodes it into a per-process heap
- * (SYS_MEM_ALLOC), and draws it with fit/1:1/zoom/pan support. */
+ * through the kernel file service, decodes it into an exact-size malloc arena,
+ * and draws it with fit/1:1/zoom/pan support. */
+
+#include <stdlib.h>
 
 #include "ucmd_lib.h"
 #include "ngui.h"
@@ -10,7 +12,6 @@
 #include "img_file.h"
 
 #define VIEW_FILE_CAP   (IMG_FILE_MAX + 1u)
-#define VIEW_INIT_HEAP  (VIEW_FILE_CAP + 64u * 1024u)
 #define VIEW_HEAP_MAX   (32u * 1024u * 1024u)
 #define VIEW_TOOLBAR_H  28
 #define VIEW_STATUS_H   18
@@ -30,8 +31,8 @@ struct viewer {
 	struct ngui ui;
 	struct img_image img;
 	struct img_mem mem;
-	unsigned char *heap;
-	unsigned int heap_size;
+	unsigned char *file;
+	unsigned char *arena;
 
 	unsigned int file_size;
 	unsigned int iw, ih;
@@ -466,7 +467,8 @@ void _start(const char *arg)
 	struct img_info info;
 	struct win_info wi;
 	struct img_options opt;
-	unsigned int n, arena_off, heap_size;
+	struct sys_stat st;
+	unsigned int n, fcap, est;
 	int r;
 
 	if (!arg || !arg[0]) {
@@ -481,12 +483,15 @@ void _start(const char *arg)
 		s_append(v.title, &tn, v.name, sizeof(v.title));
 	}
 
-	v.heap = (unsigned char *)u_mem_alloc(VIEW_INIT_HEAP);
-	if (!v.heap)
+	fcap = VIEW_FILE_CAP;
+	if (u_stat(arg, &st) == 0 && !st.is_dir && st.size > 0 &&
+	    st.size < VIEW_FILE_CAP)
+		fcap = st.size + 1u;
+	v.file = (unsigned char *)malloc(fcap);
+	if (!v.file)
 		error_exit("Not enough memory for the image");
-	heap_size = VIEW_INIT_HEAP;
 
-	n = (unsigned int)img_read_file(arg, v.heap, VIEW_FILE_CAP);
+	n = (unsigned int)img_read_file(arg, v.file, fcap);
 	if ((int)n < 0) {
 		if ((int)n == IMG_ERR_TOOBIG)
 			error_exit("Image file is larger than 4 MB");
@@ -494,26 +499,18 @@ void _start(const char *arg)
 	}
 	v.file_size = n;
 
-	r = img_sniff(v.heap, n, &info);
+	r = img_sniff(v.file, n, &info);
 	if (r != 0)
 		error_exit(img_error_string(r));
 
-	arena_off = (n + 15u) & ~15u;
-	{
-		unsigned int est = img_estimate(&info);
-		unsigned long long need = (unsigned long long)arena_off + est;
-
-		if (need > VIEW_HEAP_MAX)
-			error_exit("Image needs more than 32 MB");
-		if (need > heap_size) {
-			if (u_mem_grow((unsigned int)need) != 0)
-				error_exit("Not enough memory for the image");
-			heap_size = (unsigned int)need;
-		}
-	}
-	if (heap_size <= arena_off)
+	est = img_estimate(&info);
+	if (est == 0xFFFFFFFFu || est > VIEW_HEAP_MAX ||
+	    (unsigned long long)n + est > VIEW_HEAP_MAX)
+		error_exit("Image needs more than 32 MB");
+	v.arena = (unsigned char *)malloc(est);
+	if (!v.arena)
 		error_exit("Not enough memory for the image");
-	img_mem_init(&v.mem, v.heap + arena_off, heap_size - arena_off);
+	img_mem_init(&v.mem, v.arena, est);
 	v.iw = info.width;
 	v.ih = info.height;
 	v.format = info.format;
@@ -539,7 +536,7 @@ void _start(const char *arg)
 	}
 
 	opt.max_pixels = 0;
-	r = img_decode(v.heap, n, &opt, &v.mem, &v.img);
+	r = img_decode(v.file, n, &opt, &v.mem, &v.img);
 	v.loading = 0;
 	if (r != 0) {
 		s_copy(v.err, img_error_string(r), sizeof(v.err));
@@ -557,7 +554,7 @@ void _start(const char *arg)
 		unsigned int frames = 0, delay = 100;
 		int ha = 0;
 
-		if (img_gif_frames(v.heap, v.file_size, &frames, &delay, &ha) == 0 &&
+		if (img_gif_frames(v.file, v.file_size, &frames, &delay, &ha) == 0 &&
 		    frames > 1) {
 			v.gif_frames = frames;
 			v.gif_index = 0;
@@ -579,7 +576,7 @@ void _start(const char *arg)
 			unsigned int d = v.gif_delay;
 
 			v.gif_index = (v.gif_index + 1) % v.gif_frames;
-			if (img_decode_gif_frame(v.heap, v.file_size,
+			if (img_decode_gif_frame(v.file, v.file_size,
 						 v.gif_index, &v.mem, &v.img,
 						 &d) == 0) {
 				if (d < 20) d = 20;