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

Add image library and graphical viewer

- freestanding RGB565 decoders for PNG, JPEG, GIF, BMP, TGA and PNM
- reusable img_sniff/img_decode/img_draw arena API plus inflate/zlib/gzip
- per-process heap syscalls for image buffers
- gzip the embedded command pack and inflate it at boot
- view command, Files integration, and host image tests
Johannes Zellner 2 недель назад
Родитель
Сommit
9f2be59bf0
75 измененных файлов с 6414 добавлено и 23 удалено
  1. 2 0
      .gitignore
  2. 47 5
      AGENTS.md
  3. 54 8
      Makefile
  4. 186 0
      img.c
  5. 98 0
      img.h
  6. 214 0
      img_blit.c
  7. 355 0
      img_bmp.c
  8. 31 0
      img_file.c
  9. 14 0
      img_file.h
  10. 434 0
      img_gif.c
  11. 75 0
      img_internal.h
  12. 905 0
      img_jpeg.c
  13. 41 0
      img_mem.c
  14. 592 0
      img_png.c
  15. 229 0
      img_pnm.c
  16. 361 0
      img_test.c
  17. 299 0
      img_tga.c
  18. 659 0
      inflate.c
  19. 75 0
      inflate.h
  20. 11 6
      kernel.c
  21. 7 2
      ngui.c
  22. 3 0
      ngui.h
  23. 3 1
      process.c
  24. 5 0
      process.h
  25. 63 1
      ramfs.c
  26. 107 0
      sys_mem.c
  27. 17 0
      sys_mem.h
  28. 7 0
      syscall.c
  29. 7 0
      syscall.h
  30. BIN
      testdata/images/anim.gif
  31. 3 0
      testdata/images/ascii.ppm
  32. BIN
      testdata/images/bw.bmp
  33. BIN
      testdata/images/bw.pbm
  34. BIN
      testdata/images/bw.png
  35. 44 0
      testdata/images/expected.h
  36. BIN
      testdata/images/gray.pgm
  37. BIN
      testdata/images/gray.png
  38. BIN
      testdata/images/gray16.png
  39. BIN
      testdata/images/gray_inter.png
  40. BIN
      testdata/images/inflate.gz
  41. 581 0
      testdata/images/inflate.raw
  42. BIN
      testdata/images/inflate.z
  43. BIN
      testdata/images/inter.gif
  44. BIN
      testdata/images/j420.jpg
  45. BIN
      testdata/images/j422.jpg
  46. BIN
      testdata/images/j444.jpg
  47. BIN
      testdata/images/jgray.jpg
  48. BIN
      testdata/images/jrst.jpg
  49. BIN
      testdata/images/pal.bmp
  50. BIN
      testdata/images/pal.png
  51. BIN
      testdata/images/pal4.png
  52. BIN
      testdata/images/plain.gif
  53. BIN
      testdata/images/prog.jpg
  54. BIN
      testdata/images/ref/j420.jpg.ppm
  55. BIN
      testdata/images/ref/j422.jpg.ppm
  56. BIN
      testdata/images/ref/j444.jpg.ppm
  57. BIN
      testdata/images/ref/jgray.jpg.ppm
  58. BIN
      testdata/images/ref/jrst.jpg.ppm
  59. BIN
      testdata/images/rgb.bmp
  60. BIN
      testdata/images/rgb.png
  61. BIN
      testdata/images/rgb.ppm
  62. BIN
      testdata/images/rgb.tga
  63. BIN
      testdata/images/rgb_inter.png
  64. BIN
      testdata/images/rgba.bmp
  65. BIN
      testdata/images/rgba.png
  66. BIN
      testdata/images/rgba.tga
  67. BIN
      testdata/images/rgba_inter.png
  68. BIN
      testdata/images/rle.tga
  69. BIN
      testdata/images/rle8.bmp
  70. BIN
      testdata/images/topdown.bmp
  71. BIN
      testdata/images/trans.gif
  72. 178 0
      tools/gen_img_tests.py
  73. 41 0
      ucmd_files.c
  74. 18 0
      ucmd_lib.h
  75. 648 0
      ucmd_view.c

+ 2 - 0
.gitignore

@@ -9,3 +9,5 @@ netkexec_send
 netmonitor
 mkpack
 tls_test
+img_test
+img_test_asan

+ 47 - 5
AGENTS.md

@@ -17,6 +17,7 @@ make run-uhci   # like `make run` but with a UHCI controller + USB mouse
 make run-net    # like `make run` + a PCI NE2000 NIC on QEMU's user network (slirp; DHCP/DNS/NAT)
 make run-ahci   # like `make run` + an ICH9 AHCI controller and a 512 MB SATA disk (sata0)
 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 clean
 ```
 
@@ -311,6 +312,13 @@ below the run area), so adding code no longer moves any address.
   `kernel.elf`).  Note: `run`/`prog`/`space` still draw over the WM (which keeps
   repainting its desktop); the windowed path for such programs is the ring-3
   canvas service (see the window graphics bullet, used by `clock`/`colors`).
+- **Ring-3 address space**: the ELF image and 8 KB stack live in the 2 MB
+  `USER_BASE` (`0x40000000`)..`USER_STACK_TOP` (`0x40200000`) window, which is
+  too small for a full-frame image.  `SYS_MEM_ALLOC`/`SYS_MEM_GROW`/`SYS_MEM_FREE`
+  (`sys_mem.c/h`) map/grow/delete a single anonymous arena at
+  `USER_HEAP_BASE` (`0x60000000`), capped at 32 MB; 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.
 - **Ring-3 commands**: `ucmd_*.c`, `ucmd_lib.h`, `ucmd.ld`, `mkpack.c`,
   `ramfs.c/h` — freestanding ELFs linked at `USER_BASE` (`0x40000000`), packed
   by `mkpack` into `cmds.pack` (as `bin/<name>`), embedded in the kernel
@@ -330,7 +338,24 @@ below the run area), so adding code no longer moves any address.
   `_start(const char *arg)` needs no crt0.  `ngui.c/h` is the shared userland
   GUI toolkit linked into `ucmd_files.c` (buttons, text fields, icons, layout
   cuts and scroll panes); `files` opens the selected text file through
-  `/ramfs/bin/edit`.
+  `/ramfs/bin/edit` and image files through `/ramfs/bin/view`.  `ngui_end_ex()`
+  is the variant that runs the bookkeeping without publishing the canvas, for
+  apps that poll input without redrawing.
+- **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
+  8-bit alpha plane.  The codecs are independent of the OS and ngui: they take
+  an input buffer plus a caller-provided `struct img_mem` arena, so a browser
+  can link the same objects and decode HTTP bodies.  `inflate.c/h` (DEFLATE,
+  zlib, gzip, CRC32/Adler32) is shared with the boot pack.  `img_sniff()` is a
+  cheap header probe; `img_decode()` returns `struct img_image`; `img_draw()`
+  is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha
+  over a checkerboard or over the destination (for a browser).  The viewer,
+  `ucmd_view.c`, owns a canvas window and reads its file through
+  `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size and
+  a clear error for unsupported variants.  Host tests: `make test-images`
+  (`img_test.c`, corpus in `testdata/images/`, generator
+  `tools/gen_img_tests.py`).
 - **Network service**: `sys_net.c/h` — the NIC and the stack stay in the
   kernel; ring-3 commands get `SYS_NET_INFO`/config, the DNS and DHCP clients
   and the raw frame paths (`NET_TX/RX/DECODE/REPLY/LOOPBACK/REGS/RESET`), so
@@ -352,7 +377,7 @@ below the run area), so adding code no longer moves any address.
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `prog`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device>`,
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`, and `view <file>` (image viewer; PNG, baseline JPEG, GIF first frame, BMP, TGA, PNM).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `pong` (responds to ARP/ICMP for our IP for 30 s),
@@ -382,7 +407,7 @@ nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `spin`,
-`clock`, `colors`, `files`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `files`, `view`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `curl` and `hello` are files in `/ramfs/bin` (packed by the
 Makefile), found through the shell's PATH; the rest are kernel commands
@@ -446,8 +471,13 @@ re-applied on a full floppy/USB boot (C-light reuses the current LFB).
 ## Command pack hot-reload (cmds-dev / net-cmds)
 
 The commands live in `cmds.pack` (`bin/<name>` entries, built by `mkpack`),
-which is embedded in `kernel.bin` and mounted read-only at `/ramfs`.  A
-running board can replace it without a kernel reload:
+which is gzip-compressed at build time (`cmds_pack_gz.bin`) and embedded in
+`kernel.bin`; `ramfs_init()` inflates it at boot with `inflate.c` and mounts it
+read-only at `/ramfs`.  The compression keeps the kernel inside its
+low-memory window (`_end <= 0x7F000`) now that the image viewer adds decoders.
+`cmds-dev`/`net-cmds` still send the *raw* `cmds.pack`, which
+`ramfs_replace()` validates and installs directly.  A running board can
+replace the pack without a kernel reload:
 
 ```sh
 make cmds-dev       # serial:  ./kexec_send  --payload $(SERIAL_DEV) $(SERIAL_BAUD) cmds.pack
@@ -759,3 +789,15 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     rely on not-present TLB entries not being cached; there is no cross-CPU
     TLB shootdown.  No process shares an address space with another, so normal
     process teardown is unaffected.
+
+15. Image library limits: progressive/arithmetic JPEG and CMYK are rejected;
+    GIF shows only the first frame; EXIF orientation and ICC/gamma are ignored;
+    the whole file is read into memory (4 MB cap in the viewer); decoding uses
+    a 32 MB arena, so very large photos need DCT-scaled/streamed decode before
+    they fit.  Arithmetic-coded JPEGs are not supported.
+16. `img_draw()`'s box-filter downscale runs on the CPU.  It is fine for the
+    viewer's static frames, but a browser showing many large inline images
+    should cache a scaled bitmap (or use decode-at-display-scale) instead of
+    rescaling on every repaint.
+17. `files` recognises images by file extension only; a magic-based fallback
+    would also open extensionless files in the viewer.

+ 54 - 8
Makefile

@@ -13,7 +13,7 @@ ASFLAGS  = --32 -I.
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
-.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-net run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev cmds-dev net-cmds netmon monitor test-crypto
+.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-net run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev cmds-dev net-cmds netmon monitor test-crypto test-images test-images-asan
 
 all: floppy.img usb.img final.bin root.img
 
@@ -281,6 +281,12 @@ syscall.o: syscall.c syscall.h io.h process.h timer.h sys_wm.h wm_abi.h
 sys_fs.o: sys_fs.c sys_fs.h syscall.h fat.h vfs.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+sys_mem.o: sys_mem.c sys_mem.h mm.h paging.h process.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+inflate.o: inflate.c inflate.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 sys_info.o: sys_info.c sys_info.h syscall.h ahci.h blkdev.h mm.h mouse.h usbhid.h vfs.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -290,7 +296,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h pr
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: 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 reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o prog_embed.o space_embed.o cmds_pack.o ramfs.o payload.o
+kernel.elf: 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 reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o prog_embed.o space_embed.o inflate.o cmds_pack.o ramfs.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -380,7 +386,7 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         ucmd_netinfo ucmd_netip ucmd_netdns ucmd_host ucmd_dhcp \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_curl \
-        ucmd_files
+        ucmd_files ucmd_view
 
 # Keep the linked ELFs around (make would treat them as disposable
 # intermediates between the pattern rules).
@@ -423,13 +429,31 @@ ucmd_term.elf: ucmd_term.o uwm_lib.o font_8x16.o ucmd.ld
 ngui.o: ngui.c ngui.h ucmd_lib.h syscall.h wm_abi.h font_8x16.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-ucmd_files.o: ucmd_files.c ucmd_lib.h syscall.h wm_abi.h ngui.h
+ucmd_files.o: ucmd_files.c ucmd_lib.h syscall.h wm_abi.h ngui.h img.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 ucmd_files.elf: ucmd_files.o ngui.o font_8x16.o ucmd.ld
 	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
+# Image library: pure freestanding decoders + RGB565 compositing.  Only the
+# viewer links them today; a browser can link the same objects later.
+IMGLIB_OBJS = 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_file.o
+
+$(IMGLIB_OBJS): %.o: %.c img.h img_internal.h inflate.h ucmd_lib.h syscall.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+# 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.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,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
 # TLS 1.3 client library (ring-3, linked into ucmd_curl; see tls.h).  The
 # crypto files are pure freestanding C, so tls_test can exercise them on
 # the host (make test-crypto).
@@ -462,6 +486,23 @@ tls_test: tls_test.c tls_sha256.c tls_chacha20.c tls_x25519.c \
 test-crypto: tls_test
 	./tls_test
 
+# Host image-library tests (no kernel needed).  The corpus and expected hashes
+# are committed; tools/gen_img_tests.py regenerates them.
+IMGTEST_SRCS = img_test.c 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 inflate.c
+IMGTEST_DEPS = img.h img_internal.h inflate.h testdata/images/expected.h
+
+img_test: $(IMGTEST_SRCS) $(IMGTEST_DEPS)
+	gcc -O2 -fwrapv -Wall -Wextra -I. -o $@ $(IMGTEST_SRCS)
+
+test-images: img_test
+	./img_test
+
+test-images-asan: $(IMGTEST_SRCS) $(IMGTEST_DEPS)
+	# -fwrapv: the integer IDCT deliberately relies on 32-bit wrap-around.
+	gcc -O1 -g -fwrapv -fsanitize=address,undefined -I. -o img_test_asan $(IMGTEST_SRCS)
+	./img_test_asan
+
 mkpack: mkpack.c
 	gcc -O2 -o $@ $<
 
@@ -473,13 +514,18 @@ PACK_FILES = $(foreach f,$(UCMDS),bin/$(patsubst ucmd_%,%,$(f))=$(f).elf) \
 cmds.pack: $(addsuffix .elf,$(UCMDS)) hello.elf mkpack
 	./mkpack $@ $(PACK_FILES)
 
-cmds_pack.o: cmds.pack
-	$(LD) -m elf_i386 -r -b binary -o cmds_pack.o cmds.pack
+# The embedded pack is gzip-compressed to stay inside the kernel's low-memory
+# window; the raw cmds.pack is still what cmds-dev/net-cmds send.
+cmds_pack_gz.bin: cmds.pack
+	gzip -9 -n -c $< > $@
+
+cmds_pack.o: cmds_pack_gz.bin
+	$(LD) -m elf_i386 -r -b binary -o cmds_pack.o cmds_pack_gz.bin
 
 payload.o: payload.c payload.h io.h mm.h ramfs.h serial.h vfs.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-ramfs.o: ramfs.c ramfs.h serial.h
+ramfs.o: ramfs.c ramfs.h serial.h inflate.h mm.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 space.o: space.c run_api.h
@@ -669,4 +715,4 @@ 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 run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.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 prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack uwm_lib.o ngui.o *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	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 run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.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 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 prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack_gz.bin cmds_pack.o ramfs.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_file.o img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 186 - 0
img.c

@@ -0,0 +1,186 @@
+/* Image library core: format sniffing, decode dispatch, arena image
+ * allocation and error/format names.  See img.h. */
+
+#include "img_internal.h"
+
+int img_size_ok(unsigned int w, unsigned int h,
+		const struct img_options *opt)
+{
+	unsigned long long n;
+
+	if (w == 0 || h == 0 || w > 32768 || h > 32768)
+		return 0;
+	n = (unsigned long long)w * h;
+	if (n > 0x3FFFFFFFull)
+		return 0;
+	if (opt && opt->max_pixels && n > opt->max_pixels)
+		return 0;
+	return 1;
+}
+
+int img_alloc(struct img_mem *m, unsigned int w, unsigned int h,
+	      unsigned int format, int alpha, struct img_image *out)
+{
+	unsigned long long n = (unsigned long long)w * h;
+	unsigned short *px;
+	unsigned char *a = 0;
+
+	if (!m || !out || n == 0 || n > 0x3FFFFFFFull)
+		return IMG_ERR_TOOBIG;
+	px = (unsigned short *)img_mem_alloc(m, (unsigned int)(n * 2), 16);
+	if (!px)
+		return IMG_ERR_NOMEM;
+	if (alpha) {
+		a = (unsigned char *)img_mem_alloc(m, (unsigned int)n, 16);
+		if (!a)
+			return IMG_ERR_NOMEM;
+	}
+	out->format = format;
+	out->w = w;
+	out->h = h;
+	out->px = px;
+	out->alpha = a;
+	out->flags = alpha ? IMG_FLAG_ALPHA : 0;
+	return 0;
+}
+
+static int png_sig(const unsigned char *d, unsigned int n)
+{
+	static const unsigned char sig[8] = {
+		0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A
+	};
+	unsigned int i;
+
+	if (n < 8)
+		return 0;
+	for (i = 0; i < 8; i++)
+		if (d[i] != sig[i])
+			return 0;
+	return 1;
+}
+
+int img_sniff(const void *data, unsigned int len, struct img_info *out)
+{
+	const unsigned char *d = (const unsigned char *)data;
+	int fmt;
+
+	if (!out)
+		return IMG_ERR_FORMAT;
+	out->format = IMG_FMT_UNKNOWN;
+	out->width = out->height = 0;
+	out->has_alpha = 0;
+	if (!d || len == 0)
+		return IMG_ERR_EMPTY;
+
+	if (png_sig(d, len))
+		fmt = img_sniff_png(d, len, out);
+	else if (len >= 3 && d[0] == 0xFF && d[1] == 0xD8 && d[2] == 0xFF)
+		fmt = img_sniff_jpeg(d, len, out);
+	else if (len >= 6 && d[0] == 'G' && d[1] == 'I' && d[2] == 'F' &&
+		 d[3] == '8' && (d[4] == '7' || d[4] == '9') && d[5] == 'a')
+		fmt = img_sniff_gif(d, len, out);
+	else if (len >= 2 && d[0] == 'B' && d[1] == 'M')
+		fmt = img_sniff_bmp(d, len, out);
+	else if (len >= 2 && d[0] == 'P' && d[1] >= '1' && d[1] <= '6')
+		fmt = img_sniff_pnm(d, len, out);
+	else
+		fmt = img_sniff_tga(d, len, out);   /* no magic: strict parse */
+
+	if (fmt == IMG_FMT_UNKNOWN)
+		return IMG_ERR_FORMAT;
+	return 0;
+}
+
+int img_decode(const void *data, unsigned int len,
+	       const struct img_options *opt, struct img_mem *m,
+	       struct img_image *out)
+{
+	const unsigned char *d = (const unsigned char *)data;
+	struct img_info info;
+	int r;
+
+	if (!d || len == 0)
+		return IMG_ERR_EMPTY;
+	if (!m || !out)
+		return IMG_ERR_NOMEM;
+
+	r = img_sniff(d, len, &info);
+	if (r)
+		return r;
+	if (!img_size_ok(info.width, info.height, opt))
+		return IMG_ERR_TOOBIG;
+
+	switch (info.format) {
+	case IMG_FMT_PNG:
+		r = img_decode_png(d, len, opt, m, out);
+		break;
+	case IMG_FMT_JPEG:
+		r = img_decode_jpeg(d, len, opt, m, out);
+		break;
+	case IMG_FMT_GIF:
+		r = img_decode_gif(d, len, opt, m, out);
+		break;
+	case IMG_FMT_BMP:
+		r = img_decode_bmp(d, len, opt, m, out);
+		break;
+	case IMG_FMT_TGA:
+		r = img_decode_tga(d, len, opt, m, out);
+		break;
+	case IMG_FMT_PNM:
+		r = img_decode_pnm(d, len, opt, m, out);
+		break;
+	default:
+		r = IMG_ERR_UNSUPPORTED;
+		break;
+	}
+	if (r == 0 && (!out->px || out->w != info.width ||
+		       out->h != info.height))
+		return IMG_ERR_CORRUPT;
+	return r;
+}
+
+unsigned int img_estimate(const struct img_info *info)
+{
+	unsigned long long px, bytes;
+
+	if (!info || !info->width || !info->height)
+		return 2u * 1024u * 1024u;
+	px = (unsigned long long)info->width * info->height;
+	bytes = px * 2;                       /* RGB565 output */
+	if (info->has_alpha)
+		bytes += px;                  /* alpha plane */
+	if (info->format == IMG_FMT_JPEG)
+		bytes += px * 3;              /* worst case: 4:4:4 planes */
+	bytes += 2u * 1024u * 1024u;          /* inflate/row/Huffman scratch */
+	if (bytes > 0xFFFFFFFFull)
+		return 0xFFFFFFFFu;
+	return (unsigned int)bytes;
+}
+
+const char *img_format_name(unsigned int format)
+{
+	switch (format) {
+	case IMG_FMT_PNG:  return "PNG";
+	case IMG_FMT_JPEG: return "JPEG";
+	case IMG_FMT_GIF:  return "GIF";
+	case IMG_FMT_BMP:  return "BMP";
+	case IMG_FMT_TGA:  return "TGA";
+	case IMG_FMT_PNM:  return "PNM";
+	case IMG_FMT_ICO:  return "ICO";
+	default:           return "image";
+	}
+}
+
+const char *img_error_string(int err)
+{
+	switch (err) {
+	case IMG_ERR_IO:          return "Cannot read the file";
+	case IMG_ERR_FORMAT:      return "Unknown image format";
+	case IMG_ERR_CORRUPT:     return "Image data is corrupt or truncated";
+	case IMG_ERR_NOMEM:       return "Not enough memory for the image";
+	case IMG_ERR_TOOBIG:      return "Image is too large";
+	case IMG_ERR_UNSUPPORTED: return "Image variant is not supported yet";
+	case IMG_ERR_EMPTY:       return "The file is empty";
+	default:                  return "Cannot decode the image";
+	}
+}

+ 98 - 0
img.h

@@ -0,0 +1,98 @@
+/* img: freestanding image decoding + RGB565 compositing.
+ *
+ * The library is deliberately independent of the OS and of the GUI toolkit:
+ * it takes a memory buffer and an arena, and returns RGB565 pixels plus an
+ * optional 8-bit alpha plane.  That makes it usable by the image viewer now
+ * and by a browser (or any other app) later, and lets it be tested on the
+ * host.
+ *
+ * There is no malloc and no global mutable state.  All scratch and output
+ * memory comes from struct img_mem.  The caller should take an img_mem_mark()
+ * before a decode and rewind to it when img_decode() fails; a decoder cannot
+ * always reclaim scratch allocated before its output image.
+ */
+#ifndef IMG_H
+#define IMG_H
+
+#define IMG_FMT_UNKNOWN 0
+#define IMG_FMT_PNG     1
+#define IMG_FMT_JPEG    2
+#define IMG_FMT_GIF     3
+#define IMG_FMT_BMP     4
+#define IMG_FMT_TGA     5
+#define IMG_FMT_PNM     6
+#define IMG_FMT_ICO     7
+
+#define IMG_FLAG_ALPHA  1
+
+/* Errors are negative. */
+#define IMG_ERR_IO        (-1)
+#define IMG_ERR_FORMAT    (-2)
+#define IMG_ERR_CORRUPT   (-3)
+#define IMG_ERR_NOMEM     (-4)
+#define IMG_ERR_TOOBIG    (-5)
+#define IMG_ERR_UNSUPPORTED (-6)
+#define IMG_ERR_EMPTY     (-7)
+
+/* Whole-file limit used by the viewer's file buffer. */
+#define IMG_FILE_MAX  (4u * 1024u * 1024u)
+
+struct img_info {
+	unsigned int format;
+	unsigned int width, height;
+	unsigned int has_alpha;
+};
+
+struct img_options {
+	/* 0 = no additional limit beyond the arena / sanity checks. */
+	unsigned int max_pixels;
+};
+
+struct img_mem {
+	unsigned char *base;
+	unsigned int size;
+	unsigned int used;
+};
+
+struct img_image {
+	unsigned int format;
+	unsigned int w, h;
+	unsigned short *px;      /* RGB565, w*h */
+	unsigned char *alpha;    /* w*h, or NULL when fully opaque */
+	unsigned int flags;
+};
+
+struct img_blit {
+	unsigned short *dst;
+	int dst_w, dst_h;
+	int clip_x, clip_y, clip_w, clip_h;
+	int x, y;                /* destination top-left of the image */
+	unsigned int scale;      /* 16.16, > 0 */
+	unsigned int bg;         /* RGB565 background for alpha */
+	unsigned int bg2;        /* second checker colour */
+	unsigned int flags;
+};
+
+#define IMG_BLIT_CHECKER  1  /* alpha over a checkered background */
+#define IMG_BLIT_OVER_DST 2  /* alpha over the existing destination pixels */
+#define IMG_BLIT_FAST     4  /* nearest sampling while dragging */
+
+void img_mem_init(struct img_mem *m, void *base, unsigned int size);
+unsigned int img_mem_mark(const struct img_mem *m);
+int  img_mem_rewind(struct img_mem *m, unsigned int mark);
+void *img_mem_alloc(struct img_mem *m, unsigned int bytes, unsigned int align);
+
+int  img_sniff(const void *data, unsigned int len, struct img_info *out);
+int  img_decode(const void *data, unsigned int len,
+		const struct img_options *opt, struct img_mem *m,
+		struct img_image *out);
+unsigned int img_estimate(const struct img_info *info);
+
+const char *img_format_name(unsigned int format);
+const char *img_error_string(int err);
+
+unsigned int img_fit_scale(unsigned int iw, unsigned int ih,
+			   unsigned int bw, unsigned int bh);
+void img_draw(const struct img_image *im, const struct img_blit *b);
+
+#endif

+ 214 - 0
img_blit.c

@@ -0,0 +1,214 @@
+/* Scaled, clipped RGB565 drawing with optional alpha compositing. */
+
+#include "img.h"
+
+unsigned int img_fit_scale(unsigned int iw, unsigned int ih,
+			   unsigned int bw, unsigned int bh)
+{
+	unsigned int sx, sy;
+
+	if (!iw || !ih || !bw || !bh)
+		return 65536u;
+	if (bw > 65535u) bw = 65535u;
+	if (bh > 65535u) bh = 65535u;
+	sx = (bw << 16) / iw;
+	sy = (bh << 16) / ih;
+	if (sx > sy)
+		sx = sy;
+	if (sx < 256)
+		sx = 256;       /* 1/256 minimum */
+	if (sx > (8u << 16))
+		sx = 8u << 16;
+	return sx;
+}
+
+static void get_px(const struct img_image *im, int x, int y,
+		   unsigned int *r, unsigned int *g, unsigned int *b,
+		   unsigned int *a)
+{
+	unsigned int v, i;
+
+	if (x < 0) x = 0;
+	if (y < 0) y = 0;
+	if (x >= (int)im->w) x = (int)im->w - 1;
+	if (y >= (int)im->h) y = (int)im->h - 1;
+	i = (unsigned int)y * im->w + (unsigned int)x;
+	v = im->px[i];
+	*r = ((v >> 11) & 31) * 255 / 31;
+	*g = ((v >> 5) & 63) * 255 / 63;
+	*b = (v & 31) * 255 / 31;
+	*a = im->alpha ? im->alpha[i] : 255;
+}
+
+static unsigned short blend(unsigned int sr, unsigned int sg, unsigned int sb,
+			    unsigned int sa, unsigned short dst)
+{
+	unsigned int dr, dg, db;
+
+	if (sa == 255)
+		return (unsigned short)(((sr >> 3) << 11) | ((sg >> 2) << 5) |
+					(sb >> 3));
+	if (sa == 0)
+		return dst;
+	dr = ((dst >> 11) & 31) * 255 / 31;
+	dg = ((dst >> 5) & 63) * 255 / 63;
+	db = (dst & 31) * 255 / 31;
+	sr = (sr * sa + dr * (255 - sa) + 127) / 255;
+	sg = (sg * sa + dg * (255 - sa) + 127) / 255;
+	sb = (sb * sa + db * (255 - sa) + 127) / 255;
+	return (unsigned short)(((sr >> 3) << 11) | ((sg >> 2) << 5) |
+				(sb >> 3));
+}
+
+void img_draw(const struct img_image *im, const struct img_blit *b)
+{
+	unsigned int step, sw, sh;
+	int lx, rx, ty, by;
+	int x, y;
+
+	if (!im || !b || !b->dst || !im->px || !im->w || !im->h ||
+	    !b->dst_w || !b->dst_h || !b->scale || b->clip_w <= 0 ||
+	    b->clip_h <= 0)
+		return;
+
+	sw = (unsigned int)(((unsigned long long)im->w * b->scale) >> 16);
+	sh = (unsigned int)(((unsigned long long)im->h * b->scale) >> 16);
+	if (!sw) sw = 1;
+	if (!sh) sh = 1;
+	/* ceil(2^32 / scale), without a 64-bit division (no libgcc in ring 3
+	 * on the target).  The +1 only rounds a source coordinate up by less
+	 * than one pixel. */
+	step = 0xFFFFFFFFu / b->scale + 1u;
+
+	lx = b->x;
+	if (lx < b->clip_x) lx = b->clip_x;
+	rx = b->x + (int)sw;
+	if (rx > b->clip_x + b->clip_w) rx = b->clip_x + b->clip_w;
+	if (rx > b->dst_w) rx = b->dst_w;
+	ty = b->y;
+	if (ty < b->clip_y) ty = b->clip_y;
+	by = b->y + (int)sh;
+	if (by > b->clip_y + b->clip_h) by = b->clip_y + b->clip_h;
+	if (by > b->dst_h) by = b->dst_h;
+
+	if (lx >= rx || ty >= by)
+		return;
+
+	/* 1:1, opaque, neat copy. */
+	if (b->scale == 65536u && !im->alpha &&
+	    !(b->flags & (IMG_BLIT_CHECKER | IMG_BLIT_OVER_DST))) {
+		for (y = ty; y < by; y++) {
+			int sy = y - b->y;
+			const unsigned short *src = im->px + (unsigned int)sy * im->w;
+			unsigned short *dst = b->dst + (unsigned int)y * b->dst_w;
+
+			for (x = lx; x < rx; x++)
+				dst[x] = src[x - b->x];
+		}
+		return;
+	}
+
+	for (y = ty; y < by; y++) {
+		unsigned long long sy_fp =
+			(unsigned long long)(y - b->y) * step;
+		int sy0 = (int)(sy_fp >> 16);
+		int sy1 = (int)((sy_fp + step) >> 16);
+
+		if (sy1 <= sy0)
+			sy1 = sy0 + 1;
+
+		for (x = lx; x < rx; x++) {
+			unsigned long long sx_fp =
+				(unsigned long long)(x - b->x) * step;
+			int sx0 = (int)(sx_fp >> 16);
+			int sx1 = (int)((sx_fp + step) >> 16);
+			unsigned int sr, sg, sb, sa;
+			unsigned short d;
+
+			if (sx1 <= sx0)
+				sx1 = sx0 + 1;
+			if (!(b->flags & IMG_BLIT_FAST) && b->scale < 65536u) {
+				unsigned int rsum = 0, gsum = 0, bsum = 0;
+				unsigned int asum = 0, count = 0;
+				int xx, yy;
+
+				if (sx0 < 0) sx0 = 0;
+				if (sy0 < 0) sy0 = 0;
+				if (sx1 > (int)im->w) sx1 = (int)im->w;
+				if (sy1 > (int)im->h) sy1 = (int)im->h;
+				for (yy = sy0; yy < sy1; yy++) {
+					for (xx = sx0; xx < sx1; xx++) {
+						unsigned int r, g, bb, a;
+
+						get_px(im, xx, yy, &r, &g, &bb, &a);
+						rsum += r;
+						gsum += g;
+						bsum += bb;
+						asum += a;
+						count++;
+					}
+				}
+				if (!count) {
+					get_px(im, sx0, sy0, &sr, &sg, &sb, &sa);
+				} else {
+					sr = (rsum + count / 2) / count;
+					sg = (gsum + count / 2) / count;
+					sb = (bsum + count / 2) / count;
+					sa = (asum + count / 2) / count;
+				}
+			} else if (!(b->flags & IMG_BLIT_FAST) &&
+				   b->scale > 65536u) {
+				int fx = (int)(sx_fp & 65535);
+				int fy = (int)(sy_fp & 65535);
+				unsigned int r0, g0, b0, a0, r1, g1, b1, a1;
+
+				get_px(im, sx0, sy0, &r0, &g0, &b0, &a0);
+				get_px(im, sx0 + 1, sy0, &r1, &g1, &b1, &a1);
+				{
+					unsigned int rr = (r0 * (65536 - fx) +
+							   r1 * fx) >> 16;
+					unsigned int gg = (g0 * (65536 - fx) +
+							   g1 * fx) >> 16;
+					unsigned int bb = (b0 * (65536 - fx) +
+							   b1 * fx) >> 16;
+					unsigned int aa = (a0 * (65536 - fx) +
+							   a1 * fx) >> 16;
+
+					get_px(im, sx0, sy0 + 1, &r0, &g0, &b0, &a0);
+					get_px(im, sx0 + 1, sy0 + 1, &r1, &g1, &b1,
+					       &a1);
+					sr = (rr * (65536 - fy) +
+					      ((r0 * (65536 - fx) + r1 * fx) >> 16) * fy) >> 16;
+					sg = (gg * (65536 - fy) +
+					      ((g0 * (65536 - fx) + g1 * fx) >> 16) * fy) >> 16;
+					sb = (bb * (65536 - fy) +
+					      ((b0 * (65536 - fx) + b1 * fx) >> 16) * fy) >> 16;
+					sa = (aa * (65536 - fy) +
+					      ((a0 * (65536 - fx) + a1 * fx) >> 16) * fy) >> 16;
+				}
+			} else {
+				get_px(im, sx0, sy0, &sr, &sg, &sb, &sa);
+			}
+
+			{
+				unsigned int di = (unsigned int)y * b->dst_w + x;
+				unsigned short bg;
+
+				if (b->flags & IMG_BLIT_OVER_DST)
+					bg = b->dst[di];
+				else if (b->flags & IMG_BLIT_CHECKER)
+					bg = ((x >> 3) ^ (y >> 3)) & 1 ?
+						(unsigned short)b->bg2 :
+						(unsigned short)b->bg;
+				else
+					bg = (unsigned short)b->bg;
+				d = (im->alpha && sa < 255) ?
+					blend(sr, sg, sb, sa, bg) :
+					(unsigned short)(((sr >> 3) << 11) |
+							 ((sg >> 2) << 5) |
+							 (sb >> 3));
+				b->dst[di] = d;
+			}
+		}
+	}
+}

+ 355 - 0
img_bmp.c

@@ -0,0 +1,355 @@
+/* BMP: Windows/OS2 bitmaps.  1/4/8/16/24/32 bpp, BI_RGB, BI_BITFIELDS,
+ * BI_RLE8/BI_RLE4, top-down and bottom-up rows. */
+
+#include "img_internal.h"
+
+static int bmp_info(const unsigned char *d, unsigned int n,
+		    unsigned int *w, unsigned int *h, unsigned int *bpp,
+		    unsigned int *comp, unsigned int *dib, int *topdown,
+		    unsigned int *off, unsigned int *colors)
+{
+	unsigned int height;
+
+	if (n < 26 || d[0] != 'B' || d[1] != 'M')
+		return -1;
+	*off = img_le32(d + 10);
+	*dib = img_le32(d + 14);
+	if (*dib < 12 || 14u + *dib > n)
+		return -1;
+
+	if (*dib == 12) {
+		if (n < 26)
+			return -1;
+		*w = img_le16(d + 18);
+		height = img_le16(d + 20);
+		*bpp = img_le16(d + 24);
+		*comp = 0;
+		*colors = 0;
+	} else {
+		if (n < 34)
+			return -1;
+		*w = img_le32(d + 18);
+		height = img_le32(d + 22);
+		*bpp = img_le16(d + 28);
+		*comp = img_le32(d + 30);
+		*colors = img_le32(d + 46);
+	}
+	*topdown = ((int)height < 0);
+	*h = *topdown ? (unsigned int)(-(int)height) : height;
+	if (*w == 0 || *w > 32768 || *h == 0 || *h > 32768)
+		return -1;
+	if (*bpp != 1 && *bpp != 4 && *bpp != 8 && *bpp != 16 &&
+	    *bpp != 24 && *bpp != 32)
+		return -1;
+	if (*comp != 0 && *comp != 1 && *comp != 2 && *comp != 3 &&
+	    *comp != 6)
+		return -1;
+	return 0;
+}
+
+int img_sniff_bmp(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	unsigned int w, h, bpp, comp, dib, off, colors;
+	int topdown;
+
+	if (bmp_info(d, n, &w, &h, &bpp, &comp, &dib, &topdown, &off,
+		     &colors) != 0)
+		return IMG_FMT_UNKNOWN;
+	(void)topdown;
+	out->format = IMG_FMT_BMP;
+	out->width = w;
+	out->height = h;
+	out->has_alpha = 0;
+	if (bpp == 32) {
+		unsigned int amask = 0;
+		if (dib >= 108 && n >= 14 + 108)
+			amask = img_le32(d + 14 + 66);
+		else if (comp == 6 && dib == 40) {
+			if (n >= 14 + 40 + 16)
+				amask = img_le32(d + 14 + 40 + 12);
+		}
+		out->has_alpha = amask != 0;
+	}
+	return IMG_FMT_BMP;
+}
+
+static unsigned int mask_shift(unsigned int mask)
+{
+	unsigned int s = 0;
+	if (!mask)
+		return 0;
+	while (!(mask & 1)) {
+		mask >>= 1;
+		s++;
+	}
+	return s;
+}
+
+static unsigned int mask_max(unsigned int mask)
+{
+	unsigned int s = mask_shift(mask);
+	return mask >> s;
+}
+
+static unsigned int mask_scale(unsigned int v, unsigned int mask)
+{
+	unsigned int max = mask_max(mask);
+	unsigned int val;
+
+	if (!mask || !max)
+		return 0;
+	val = (v & mask) >> mask_shift(mask);
+	if (max == 255)
+		return val;
+	return (val * 255u + max / 2) / max;
+}
+
+static void put565(struct img_image *im, unsigned int x, unsigned int y,
+		   unsigned int r, unsigned int g, unsigned int b,
+		   unsigned int a)
+{
+	unsigned int i;
+
+	if (x >= im->w || y >= im->h)
+		return;
+	i = y * im->w + x;
+	im->px[i] = img_rgb565(r, g, b);
+	if (im->alpha)
+		im->alpha[i] = (unsigned char)a;
+}
+
+int img_decode_bmp(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out)
+{
+	unsigned int w, h, bpp, comp, dib, off, colors;
+	unsigned int stride, pal_off, pal_entries, pal_size = 4;
+	unsigned int rmask = 0, gmask = 0, bmask = 0, amask = 0;
+	unsigned int i, x, y;
+	int topdown, alpha;
+	unsigned char pal[256][3];
+	unsigned int pal_a[256];
+	int r;
+
+	if (bmp_info(d, n, &w, &h, &bpp, &comp, &dib, &topdown, &off,
+		     &colors) != 0)
+		return IMG_ERR_FORMAT;
+	if (!img_size_ok(w, h, opt))
+		return IMG_ERR_TOOBIG;
+	if (dib == 12)
+		pal_size = 3;
+
+	if (bpp == 16) {
+		if ((comp == 3 || comp == 6)) {
+			unsigned int mo = 14 + dib;
+			if (dib == 40)
+				mo = 14 + 40;
+			else if (dib >= 108)
+				mo = 14 + 40;   /* masks live in the DIB */
+			if (mo + 12 > n)
+				return IMG_ERR_CORRUPT;
+			rmask = img_le32(d + mo);
+			gmask = img_le32(d + mo + 4);
+			bmask = img_le32(d + mo + 8);
+			if (comp == 6 || (dib >= 52 && mo + 16 <= n))
+				amask = img_le32(d + mo + 12);
+		} else {
+			rmask = 0x7C00;
+			gmask = 0x03E0;
+			bmask = 0x001F;
+		}
+	} else if (bpp == 32) {
+		if (dib >= 108) {
+			rmask = img_le32(d + 14 + 40);
+			gmask = img_le32(d + 14 + 44);
+			bmask = img_le32(d + 14 + 48);
+			amask = img_le32(d + 14 + 56);
+		} else if (comp == 3 || comp == 6) {
+			unsigned int mo = 14 + dib;
+			if (mo + 12 > n)
+				return IMG_ERR_CORRUPT;
+			rmask = img_le32(d + mo);
+			gmask = img_le32(d + mo + 4);
+			bmask = img_le32(d + mo + 8);
+			if (comp == 6 && mo + 16 <= n)
+				amask = img_le32(d + mo + 12);
+		}
+		if (!rmask && !gmask && !bmask) {
+			rmask = 0x00FF0000;
+			gmask = 0x0000FF00;
+			bmask = 0x000000FF;
+		}
+	}
+	alpha = (bpp == 32 && amask != 0);
+
+	pal_off = 14 + dib;
+	pal_entries = 0;
+	if (bpp <= 8) {
+		pal_entries = colors ? colors : (1u << bpp);
+		if (pal_entries > 256)
+			pal_entries = 256;
+		if (pal_off + pal_entries * pal_size > n)
+			return IMG_ERR_CORRUPT;
+		for (i = 0; i < pal_entries; i++) {
+			const unsigned char *p = d + pal_off + i * pal_size;
+			pal[i][0] = p[2];
+			pal[i][1] = p[1];
+			pal[i][2] = p[0];
+			pal_a[i] = 255;
+		}
+	}
+
+	r = img_alloc(m, w, h, IMG_FMT_BMP, alpha, out);
+	if (r)
+		return r;
+
+	if (comp == 1 || comp == 2) {
+		unsigned int px = 0, py = 0;
+		unsigned int pos = off;
+
+		if (bpp != 8 && bpp != 4)
+			return IMG_ERR_UNSUPPORTED;
+		if (topdown)
+			return IMG_ERR_UNSUPPORTED;
+		while (pos + 1 < n) {
+			unsigned int a = d[pos++], b = d[pos++];
+
+			if (a == 0) {
+				if (b == 0) {
+					px = 0;
+					py++;
+					continue;
+				}
+				if (b == 1)
+					break;
+				if (b == 2) {
+					if (pos + 2 > n)
+						return IMG_ERR_CORRUPT;
+					px += d[pos++];
+					py += d[pos++];
+					continue;
+				}
+				/* absolute mode */
+				{
+					unsigned int cnt = b;
+					unsigned int k;
+
+					if (bpp == 8) {
+						if (pos + cnt > n)
+							return IMG_ERR_CORRUPT;
+						for (k = 0; k < cnt; k++) {
+							unsigned int idx = d[pos++];
+							if (idx < pal_entries)
+								put565(out, px + k,
+								       h - 1 - py,
+								       pal[idx][0],
+								       pal[idx][1],
+								       pal[idx][2],
+								       pal_a[idx]);
+						}
+						if ((cnt & 1) && pos < n)
+							pos++;
+					} else {
+						unsigned int bytes = (cnt + 1) / 2;
+						if (pos + bytes > n)
+							return IMG_ERR_CORRUPT;
+						for (k = 0; k < cnt; k++) {
+							unsigned int idx = (k & 1) ?
+								(d[pos + k / 2] & 15) :
+								(d[pos + k / 2] >> 4);
+							if (idx < pal_entries)
+								put565(out, px + k,
+								       h - 1 - py,
+								       pal[idx][0],
+								       pal[idx][1],
+								       pal[idx][2],
+								       pal_a[idx]);
+						}
+						pos += bytes;
+						if (bytes & 1)
+							pos++;
+					}
+					px += cnt;
+				}
+				continue;
+			}
+			/* encoded run */
+			{
+				unsigned int k;
+
+				for (k = 0; k < a; k++) {
+					unsigned int idx = b;
+
+					if (bpp == 4)
+						idx = (k & 1) ? (b & 15) : (b >> 4);
+					if (idx < pal_entries)
+						put565(out, px + k,
+						       h - 1 - py,
+						       pal[idx][0],
+						       pal[idx][1],
+						       pal[idx][2],
+						       pal_a[idx]);
+				}
+				px += a;
+			}
+		}
+		return 0;
+	}
+
+	stride = ((w * bpp + 31u) / 32u) * 4u;
+	if (off > n || stride > n - off ||
+	    (unsigned long long)stride * h > (unsigned long long)(n - off))
+		return IMG_ERR_CORRUPT;
+
+	for (y = 0; y < h; y++) {
+		const unsigned char *row = d + off + (topdown ? y : (h - 1 - y)) * stride;
+
+		for (x = 0; x < w; x++) {
+			unsigned int rr, gg, bb, aa = 255;
+
+			if (bpp <= 8) {
+				unsigned int idx;
+
+				if (bpp == 8)
+					idx = row[x];
+				else if (bpp == 4)
+					idx = (row[x / 2] >> ((x & 1) ? 0 : 4)) & 15;
+				else
+					idx = (row[x / 8] >> (7 - (x & 7))) & 1;
+				if (idx >= pal_entries)
+					idx = 0;
+				rr = pal[idx][0];
+				gg = pal[idx][1];
+				bb = pal[idx][2];
+				aa = pal_a[idx];
+			} else if (bpp == 16) {
+				unsigned int v = img_le16(row + x * 2);
+				rr = mask_scale(v, rmask);
+				gg = mask_scale(v, gmask);
+				bb = mask_scale(v, bmask);
+				if (amask)
+					aa = mask_scale(v, amask);
+			} else if (bpp == 24) {
+				const unsigned char *p = row + x * 3;
+				bb = p[0];
+				gg = p[1];
+				rr = p[2];
+			} else {
+				unsigned int v = img_le32(row + x * 4);
+				if (rmask) {
+					rr = mask_scale(v, rmask);
+					gg = mask_scale(v, gmask);
+					bb = mask_scale(v, bmask);
+				} else {
+					bb = v & 255;
+					gg = (v >> 8) & 255;
+					rr = (v >> 16) & 255;
+				}
+				if (alpha)
+					aa = mask_scale(v, amask);
+			}
+			put565(out, x, y, rr, gg, bb, aa);
+		}
+	}
+	return 0;
+}

+ 31 - 0
img_file.c

@@ -0,0 +1,31 @@
+/* Whole-file image loading for ring-3 commands (see img_file.h). */
+
+#include "img_file.h"
+#include "ucmd_lib.h"
+
+int img_read_file(const char *path, void *buf, unsigned int cap)
+{
+	int n;
+
+	if (!path || !buf || cap == 0)
+		return IMG_ERR_IO;
+	n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)cap);
+	if (n < 0)
+		return IMG_ERR_IO;
+	if (n == 0)
+		return IMG_ERR_EMPTY;
+	if ((unsigned int)n >= cap)
+		return IMG_ERR_TOOBIG;    /* filled the buffer: file is larger */
+	return n;
+}
+
+int img_decode_file(const char *path, void *filebuf, unsigned int filecap,
+		    const struct img_options *opt, struct img_mem *mem,
+		    struct img_image *out)
+{
+	int n = img_read_file(path, filebuf, filecap);
+
+	if (n < 0)
+		return n;
+	return img_decode(filebuf, (unsigned int)n, opt, mem, out);
+}

+ 14 - 0
img_file.h

@@ -0,0 +1,14 @@
+/* Ring-3 convenience: read a whole file through SYS_READ_FILE and decode it.
+ * The codec core stays OS-independent; this is the only image module that
+ * includes ucmd_lib.h. */
+#ifndef IMG_FILE_H
+#define IMG_FILE_H
+
+#include "img.h"
+
+int img_read_file(const char *path, void *buf, unsigned int cap);
+int img_decode_file(const char *path, void *filebuf, unsigned int filecap,
+		    const struct img_options *opt, struct img_mem *mem,
+		    struct img_image *out);
+
+#endif

+ 434 - 0
img_gif.c

@@ -0,0 +1,434 @@
+/* GIF87a/89a: first frame, LZW, interlace and transparency. */
+
+#include "img_internal.h"
+
+struct gif_rd {
+	const unsigned char *d;
+	unsigned int n, pos;
+	unsigned int blk_left;
+};
+
+static int gif_u8(struct gif_rd *r, unsigned int *v)
+{
+	if (r->pos >= r->n)
+		return -1;
+	*v = r->d[r->pos++];
+	return 0;
+}
+
+static int gif_subblock(struct gif_rd *r)
+{
+	unsigned int len;
+
+	if (r->blk_left)
+		return 0;
+	if (gif_u8(r, &len))
+		return -1;
+	r->blk_left = len;
+	return len ? 0 : 1;      /* 1 = end of sub-block chain */
+}
+
+static int gif_skip_subblocks(struct gif_rd *r)
+{
+	int e;
+
+	do {
+		e = gif_subblock(r);
+		if (e < 0)
+			return -1;
+		if (e > 0)
+			return 0;
+		while (r->blk_left) {
+			r->blk_left--;
+			if (r->pos >= r->n)
+				return -1;
+			r->pos++;
+		}
+	} while (1);
+}
+
+static int gif_palette(const unsigned char *d, unsigned int n,
+		       unsigned int off, unsigned int entries,
+		       unsigned char pal[256][3])
+{
+	unsigned int i;
+
+	if (off > n || entries * 3u > n - off)
+		return -1;
+	for (i = 0; i < entries && i < 256; i++) {
+		pal[i][0] = d[off + i * 3];
+		pal[i][1] = d[off + i * 3 + 1];
+		pal[i][2] = d[off + i * 3 + 2];
+	}
+	return 0;
+}
+
+static int gif_header(const unsigned char *d, unsigned int n,
+		      unsigned int *w, unsigned int *h, unsigned int *packed,
+		      unsigned int *bg, unsigned int *gct_off,
+		      unsigned int *gct_entries, unsigned int *pos)
+{
+	if (n < 13 || d[0] != 'G' || d[1] != 'I' || d[2] != 'F' ||
+	    d[3] != '8' || (d[4] != '7' && d[4] != '9') || d[5] != 'a')
+		return -1;
+	*w = img_le16(d + 6);
+	*h = img_le16(d + 8);
+	*packed = d[10];
+	*bg = d[11];
+	*gct_entries = 0;
+	*gct_off = 13;
+	if (*packed & 0x80) {
+		*gct_entries = 1u << ((*packed & 7) + 1);
+		if (*gct_off + *gct_entries * 3u > n)
+			return -1;
+	}
+	*pos = *gct_off + *gct_entries * 3u;
+	if (*w == 0 || *h == 0 || *w > 32768 || *h > 32768)
+		return -1;
+	return 0;
+}
+
+/* Walk extensions until the first image descriptor.  Fills the transparency
+ * information; returns 0 with the image descriptor position in *img_pos. */
+static int gif_scan(const unsigned char *d, unsigned int n, unsigned int start,
+		    unsigned int *img_pos, int *transparent,
+		    unsigned int *trans_index)
+{
+	struct gif_rd r;
+
+	r.d = d;
+	r.n = n;
+	r.pos = start;
+	r.blk_left = 0;
+	*transparent = 0;
+	*trans_index = 0;
+	while (r.pos < n) {
+		unsigned int b;
+
+		if (gif_u8(&r, &b))
+			return -1;
+		if (b == 0x3B) {
+			*img_pos = r.pos;
+			return 0;
+		}
+		if (b == 0x21) {
+			unsigned int label;
+
+			if (gif_u8(&r, &label))
+				return -1;
+			if (label == 0xF9) {
+				unsigned int len, pk = 0, idx = 0;
+
+				if (gif_u8(&r, &len) || len < 4)
+					return -1;
+				{
+					unsigned int i;
+
+					for (i = 0; i < len; i++) {
+						unsigned int v;
+
+						if (gif_u8(&r, &v))
+							return -1;
+						if (i == 0)
+							pk = v;
+						if (i == 3)
+							idx = v;
+					}
+				}
+				if (pk & 1) {
+					*transparent = 1;
+					*trans_index = idx;
+				}
+				if (gif_u8(&r, &b) || b != 0)
+					return -1;   /* block terminator */
+			} else {
+				if (gif_skip_subblocks(&r))
+					return -1;
+			}
+			continue;
+		}
+		if (b == 0x2C) {
+			*img_pos = r.pos - 1;
+			return 0;
+		}
+		if (b == 0x00) {
+			while (r.pos < n && d[r.pos] == 0)
+				r.pos++;
+			continue;
+		}
+		return -1;
+	}
+	*img_pos = r.pos;
+	return 0;
+}
+
+int img_sniff_gif(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	unsigned int w, h, packed, bg, goff, gent, pos, ipos, ti;
+	int tr;
+
+	if (gif_header(d, n, &w, &h, &packed, &bg, &goff, &gent, &pos))
+		return IMG_FMT_UNKNOWN;
+	out->format = IMG_FMT_GIF;
+	out->width = w;
+	out->height = h;
+	out->has_alpha = 0;
+	if (gif_scan(d, n, pos, &ipos, &tr, &ti) == 0)
+		out->has_alpha = tr != 0;
+	return IMG_FMT_GIF;
+}
+
+struct gif_lzw {
+	struct gif_rd *r;
+	unsigned int bitbuf;
+	int bitcnt;
+};
+
+static int lzw_code(struct gif_lzw *z, int bits, int *out)
+{
+	int v;
+
+	while (z->bitcnt < bits) {
+		int e = gif_subblock(z->r);
+		unsigned int b;
+
+		if (e < 0)
+			return -1;
+		if (e > 0)
+			return -1;
+		if (gif_u8(z->r, &b))
+			return -1;
+		z->r->blk_left--;
+		z->bitbuf |= b << z->bitcnt;
+		z->bitcnt += 8;
+	}
+	v = (int)(z->bitbuf & ((1u << bits) - 1u));
+	z->bitbuf >>= bits;
+	z->bitcnt -= bits;
+	*out = v;
+	return 0;
+}
+
+static void gif_put(struct img_image *im, unsigned int x, unsigned int y,
+		    unsigned int r, unsigned int g, unsigned int b,
+		    unsigned int a)
+{
+	if (x >= im->w || y >= im->h)
+		return;
+	im->px[y * im->w + x] = img_rgb565(r, g, b);
+	if (im->alpha)
+		im->alpha[y * im->w + x] = (unsigned char)a;
+}
+
+static unsigned int gif_scan_row(unsigned int fh, unsigned int n)
+{
+	static const unsigned int start[4] = {0, 4, 2, 1};
+	static const unsigned int step[4] = {8, 8, 4, 2};
+	unsigned int p;
+
+	for (p = 0; p < 4; p++) {
+		unsigned int count = 0;
+
+		if (fh > start[p])
+			count = (fh - start[p] + step[p] - 1) / step[p];
+		if (n < count)
+			return start[p] + n * step[p];
+		n -= count;
+	}
+	return fh ? fh - 1 : 0;
+}
+
+int img_decode_gif(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out)
+{
+	unsigned int w, h, packed, bg, goff, gent, pos, ipos;
+	unsigned int trans_index = 0;
+	int transparent = 0;
+	unsigned char gpal[256][3], lpal[256][3];
+	unsigned int fw, fh, left, top, fpacked, lct_entries = 0;
+	unsigned int min_code, i;
+	unsigned int total_pixels, done = 0;
+	unsigned int mark, image_end;
+	struct gif_rd rd;
+	struct gif_lzw z;
+	int rcode;
+
+	mark = img_mem_mark(m);
+	if (gif_header(d, n, &w, &h, &packed, &bg, &goff, &gent, &pos))
+		return IMG_ERR_FORMAT;
+	if (!img_size_ok(w, h, opt))
+		return IMG_ERR_TOOBIG;
+	for (i = 0; i < 256; i++)
+		gpal[i][0] = gpal[i][1] = gpal[i][2] = 0;
+	if (gent && gif_palette(d, n, goff, gent, gpal))
+		return IMG_ERR_CORRUPT;
+	if (gif_scan(d, n, pos, &ipos, &transparent, &trans_index))
+		return IMG_ERR_CORRUPT;
+	if (ipos + 9 > n || d[ipos] != 0x2C)
+		return IMG_ERR_CORRUPT;
+	left = img_le16(d + ipos + 1);
+	top = img_le16(d + ipos + 3);
+	fw = img_le16(d + ipos + 5);
+	fh = img_le16(d + ipos + 7);
+	fpacked = d[ipos + 9];
+	pos = ipos + 10;
+	if (fw == 0 || fh == 0)
+		return IMG_ERR_CORRUPT;
+	if (left > w || top > h || fw > w - left || fh > h - top)
+		return IMG_ERR_UNSUPPORTED;
+	if (fpacked & 0x80) {
+		lct_entries = 1u << ((fpacked & 7) + 1);
+		if (gif_palette(d, n, pos, lct_entries, lpal))
+			return IMG_ERR_CORRUPT;
+		pos += lct_entries * 3u;
+	} else {
+		lct_entries = gent;
+		for (i = 0; i < 256; i++) {
+			lpal[i][0] = gpal[i][0];
+			lpal[i][1] = gpal[i][1];
+			lpal[i][2] = gpal[i][2];
+		}
+	}
+	(void)lct_entries;
+	if (pos >= n)
+		return IMG_ERR_CORRUPT;
+	min_code = d[pos++];
+	if (min_code < 2 || min_code > 8)
+		return IMG_ERR_UNSUPPORTED;
+
+	rcode = img_alloc(m, w, h, IMG_FMT_GIF, transparent, out);
+	if (rcode)
+		return rcode;
+	image_end = img_mem_mark(m);
+	if (gent && bg < gent) {
+		for (i = 0; i < w * h; i++)
+			out->px[i] = img_rgb565(gpal[bg][0], gpal[bg][1], gpal[bg][2]);
+	} else {
+		for (i = 0; i < w * h; i++)
+			out->px[i] = 0;
+	}
+	if (out->alpha)
+		for (i = 0; i < w * h; i++)
+			out->alpha[i] = 255;
+
+	rd.d = d;
+	rd.n = n;
+	rd.pos = pos;
+	rd.blk_left = 0;
+	z.r = &rd;
+	z.bitbuf = 0;
+	z.bitcnt = 0;
+	total_pixels = fw * fh;
+
+	{
+		int *prefix;
+		unsigned char *suffix, *stack;
+		int clear = 1 << min_code;
+		int end = clear + 1;
+		int avail = end + 1;
+		int code_size = (int)min_code + 1;
+		int prev = -1;
+		int interlaced = (fpacked & 0x40) != 0;
+
+		prefix = (int *)img_mem_alloc(m, 4096 * sizeof(int), 16);
+		suffix = (unsigned char *)img_mem_alloc(m, 4096, 16);
+		stack = (unsigned char *)img_mem_alloc(m, 4096, 16);
+		if (!prefix || !suffix || !stack) {
+			img_mem_rewind(m, mark);
+			return IMG_ERR_NOMEM;
+		}
+		for (i = 0; i < (unsigned int)clear; i++) {
+			prefix[i] = -1;
+			suffix[i] = (unsigned char)i;
+		}
+
+		for (;;) {
+			int code;
+			int stack_len = 0;
+			unsigned int first;
+			int cur;
+
+			if (lzw_code(&z, code_size, &code)) {
+				if (done >= total_pixels)
+					break;
+				img_mem_rewind(m, mark);
+				return IMG_ERR_CORRUPT;
+			}
+			if (code == clear) {
+				avail = end + 1;
+				code_size = (int)min_code + 1;
+				prev = -1;
+				continue;
+			}
+			if (code == end)
+				break;
+			if (prev < 0) {
+				if (code < 0 || code >= clear) {
+					img_mem_rewind(m, mark);
+					return IMG_ERR_CORRUPT;
+				}
+				first = (unsigned int)code;
+				if (done < total_pixels) {
+					unsigned int idx = (unsigned int)code;
+					unsigned int fr = done / fw;
+					unsigned int oy = top +
+						(interlaced ? gif_scan_row(fh, fr) : fr);
+
+					gif_put(out, left + (done % fw), oy,
+						lpal[idx][0], lpal[idx][1],
+						lpal[idx][2],
+						(transparent && idx == trans_index) ? 0 : 255);
+					done++;
+				}
+				prev = code;
+				continue;
+			}
+			cur = code;
+			if (code >= avail) {
+				if (code != avail) {
+					img_mem_rewind(m, mark);
+					return IMG_ERR_CORRUPT;
+				}
+				stack[stack_len++] = (unsigned char)suffix[prev];
+				cur = prev;
+			}
+			while (cur >= 0 && cur < avail && stack_len < 4096) {
+				stack[stack_len++] = suffix[cur];
+				cur = prefix[cur];
+			}
+			first = stack[stack_len - 1];
+			if (avail < 4096) {
+				prefix[avail] = prev;
+				suffix[avail] = (unsigned char)first;
+				avail++;
+				if (avail == (1 << code_size) && code_size < 12)
+					code_size++;
+			}
+			/* The stacked string was pushed in reverse order. */
+			while (stack_len > 0) {
+				unsigned int idx = stack[--stack_len];
+				unsigned int fr, ox, oy;
+
+				if (done >= total_pixels)
+					break;
+				fr = done / fw;
+				ox = left + (done % fw);
+				oy = top + (interlaced ? gif_scan_row(fh, fr) : fr);
+				gif_put(out, ox, oy, lpal[idx][0], lpal[idx][1],
+					lpal[idx][2],
+					(transparent && idx == trans_index) ? 0 : 255);
+				done++;
+			}
+			prev = code;
+			if (done >= total_pixels)
+				break;
+		}
+	}
+	if (done < total_pixels) {
+		img_mem_rewind(m, mark);
+		return IMG_ERR_CORRUPT;
+	}
+	img_mem_rewind(m, image_end);
+	return 0;
+}

+ 75 - 0
img_internal.h

@@ -0,0 +1,75 @@
+/* Internal helpers shared by the image decoders. */
+#ifndef IMG_INTERNAL_H
+#define IMG_INTERNAL_H
+
+#include "img.h"
+
+static inline unsigned int img_be16(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 8) | p[1];
+}
+
+static inline unsigned int img_be32(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
+	       ((unsigned int)p[2] << 8) | p[3];
+}
+
+static inline unsigned int img_le16(const unsigned char *p)
+{
+	return ((unsigned int)p[1] << 8) | p[0];
+}
+
+static inline unsigned int img_le32(const unsigned char *p)
+{
+	return ((unsigned int)p[3] << 24) | ((unsigned int)p[2] << 16) |
+	       ((unsigned int)p[1] << 8) | p[0];
+}
+
+static inline unsigned short img_rgb565(unsigned int r, unsigned int g,
+					unsigned int b)
+{
+	if (r > 255) r = 255;
+	if (g > 255) g = 255;
+	if (b > 255) b = 255;
+	return (unsigned short)(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3));
+}
+
+/* Allocate the output image (and alpha plane when requested) from the arena.
+ * Pixels are not cleared. */
+int img_alloc(struct img_mem *m, unsigned int w, unsigned int h,
+	      unsigned int format, int alpha, struct img_image *out);
+
+/* Decoder entry points (each re-validates its own header). */
+int img_decode_png(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out);
+int img_decode_jpeg(const unsigned char *d, unsigned int n,
+		    const struct img_options *opt, struct img_mem *m,
+		    struct img_image *out);
+int img_decode_gif(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out);
+int img_decode_bmp(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out);
+int img_decode_tga(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out);
+int img_decode_pnm(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out);
+
+/* Header-only probes used by img_sniff().  Return IMG_FMT_* or UNKNOWN. */
+int img_sniff_png(const unsigned char *d, unsigned int n, struct img_info *out);
+int img_sniff_jpeg(const unsigned char *d, unsigned int n, struct img_info *out);
+int img_sniff_gif(const unsigned char *d, unsigned int n, struct img_info *out);
+int img_sniff_bmp(const unsigned char *d, unsigned int n, struct img_info *out);
+int img_sniff_tga(const unsigned char *d, unsigned int n, struct img_info *out);
+int img_sniff_pnm(const unsigned char *d, unsigned int n, struct img_info *out);
+
+/* True when an image of w*h pixels is acceptable for the given options. */
+int img_size_ok(unsigned int w, unsigned int h,
+		const struct img_options *opt);
+
+#endif

+ 905 - 0
img_jpeg.c

@@ -0,0 +1,905 @@
+/* JPEG: baseline and extended-sequential 8-bit Huffman JPEG.
+ *
+ * Progressive/arithmetic JPEG and CMYK are rejected with IMG_ERR_UNSUPPORTED.
+ * Decoding uses full component planes (Y full size, chroma subsampled), which
+ * keeps the code simple and still fits the viewer's arena for normal photos. */
+
+#include "img_internal.h"
+
+#ifdef IMG_HOST_DEBUG
+#include <stdio.h>
+#define DBG(...) fprintf(stderr, __VA_ARGS__)
+#else
+#define DBG(...) do { } while (0)
+#endif
+
+static const unsigned char zigzag[64] = {
+	0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
+	12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
+	35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
+	58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63
+};
+
+#define CONST_BITS 13
+#define PASS1_BITS 2
+#define FIX_0_298631336  2446
+#define FIX_0_390180644  3196
+#define FIX_0_541196100  4433
+#define FIX_0_765366865  6270
+#define FIX_0_899976223  7373
+#define FIX_1_175875602  9633
+#define FIX_1_501321110  12299
+#define FIX_1_847759065  15137
+#define FIX_1_961570560  16069
+#define FIX_2_053119869  16819
+#define FIX_2_562915447  20995
+#define FIX_3_072711026  25172
+
+static int descale(int x, int n)
+{
+	return (x + (1 << (n - 1))) >> n;
+}
+
+static void idct_block(const int *in, unsigned char *out)
+{
+	int ws[64];
+	int i, n;
+
+	for (i = 0; i < 8; i++) {
+		if (in[8 + i] == 0 && in[16 + i] == 0 && in[24 + i] == 0 &&
+		    in[32 + i] == 0 && in[40 + i] == 0 && in[48 + i] == 0 &&
+		    in[56 + i] == 0) {
+			int dc = in[i] * (1 << PASS1_BITS);
+
+			for (n = 0; n < 8; n++)
+				ws[i + n * 8] = dc;
+			continue;
+		}
+		{
+			int z1, z2, z3, z4, z5;
+			int tmp0, tmp1, tmp2, tmp3, tmp10, tmp11, tmp12, tmp13;
+
+			z2 = in[16 + i];
+			z3 = in[48 + i];
+			z1 = (z2 + z3) * FIX_0_541196100;
+			tmp2 = z1 + z3 * -FIX_1_847759065;
+			tmp3 = z1 + z2 * FIX_0_765366865;
+
+			z2 = in[i];
+			z3 = in[32 + i];
+			tmp0 = (z2 + z3) * (1 << CONST_BITS);
+			tmp1 = (z2 - z3) * (1 << CONST_BITS);
+
+			tmp10 = tmp0 + tmp3;
+			tmp13 = tmp0 - tmp3;
+			tmp11 = tmp1 + tmp2;
+			tmp12 = tmp1 - tmp2;
+
+			tmp0 = in[56 + i];
+			tmp1 = in[40 + i];
+			tmp2 = in[24 + i];
+			tmp3 = in[8 + i];
+
+			z1 = tmp0 + tmp3;
+			z2 = tmp1 + tmp2;
+			z3 = tmp0 + tmp2;
+			z4 = tmp1 + tmp3;
+			z5 = (z3 + z4) * FIX_1_175875602;
+
+			tmp0 *= FIX_0_298631336;
+			tmp1 *= FIX_2_053119869;
+			tmp2 *= FIX_3_072711026;
+			tmp3 *= FIX_1_501321110;
+			z1 *= -FIX_0_899976223;
+			z2 *= -FIX_2_562915447;
+			z3 *= -FIX_1_961570560;
+			z4 *= -FIX_0_390180644;
+
+			z3 += z5;
+			z4 += z5;
+
+			tmp0 += z1 + z3;
+			tmp1 += z2 + z4;
+			tmp2 += z2 + z3;
+			tmp3 += z1 + z4;
+
+			ws[i + 0 * 8] = descale(tmp10 + tmp3, CONST_BITS - PASS1_BITS);
+			ws[i + 7 * 8] = descale(tmp10 - tmp3, CONST_BITS - PASS1_BITS);
+			ws[i + 1 * 8] = descale(tmp11 + tmp2, CONST_BITS - PASS1_BITS);
+			ws[i + 6 * 8] = descale(tmp11 - tmp2, CONST_BITS - PASS1_BITS);
+			ws[i + 2 * 8] = descale(tmp12 + tmp1, CONST_BITS - PASS1_BITS);
+			ws[i + 5 * 8] = descale(tmp12 - tmp1, CONST_BITS - PASS1_BITS);
+			ws[i + 3 * 8] = descale(tmp13 + tmp0, CONST_BITS - PASS1_BITS);
+			ws[i + 4 * 8] = descale(tmp13 - tmp0, CONST_BITS - PASS1_BITS);
+		}
+	}
+
+	for (i = 0; i < 8; i++) {
+		int *w = ws + i * 8;
+
+		if (w[1] == 0 && w[2] == 0 && w[3] == 0 && w[4] == 0 &&
+		    w[5] == 0 && w[6] == 0 && w[7] == 0) {
+			int dc = descale(w[0], PASS1_BITS + 3) + 128;
+
+			if (dc < 0) dc = 0;
+			if (dc > 255) dc = 255;
+			for (n = 0; n < 8; n++)
+				out[i * 8 + n] = (unsigned char)dc;
+			continue;
+		}
+		{
+			int z1, z2, z3, z4, z5;
+			int tmp0, tmp1, tmp2, tmp3, tmp10, tmp11, tmp12, tmp13;
+
+			z2 = w[2];
+			z3 = w[6];
+			z1 = (z2 + z3) * FIX_0_541196100;
+			tmp2 = z1 + z3 * -FIX_1_847759065;
+			tmp3 = z1 + z2 * FIX_0_765366865;
+
+			tmp0 = (w[0] + w[4]) * (1 << CONST_BITS);
+			tmp1 = (w[0] - w[4]) * (1 << CONST_BITS);
+
+			tmp10 = tmp0 + tmp3;
+			tmp13 = tmp0 - tmp3;
+			tmp11 = tmp1 + tmp2;
+			tmp12 = tmp1 - tmp2;
+
+			tmp0 = w[7];
+			tmp1 = w[5];
+			tmp2 = w[3];
+			tmp3 = w[1];
+
+			z1 = tmp0 + tmp3;
+			z2 = tmp1 + tmp2;
+			z3 = tmp0 + tmp2;
+			z4 = tmp1 + tmp3;
+			z5 = (z3 + z4) * FIX_1_175875602;
+
+			tmp0 *= FIX_0_298631336;
+			tmp1 *= FIX_2_053119869;
+			tmp2 *= FIX_3_072711026;
+			tmp3 *= FIX_1_501321110;
+			z1 *= -FIX_0_899976223;
+			z2 *= -FIX_2_562915447;
+			z3 *= -FIX_1_961570560;
+			z4 *= -FIX_0_390180644;
+
+			z3 += z5;
+			z4 += z5;
+
+			tmp0 += z1 + z3;
+			tmp1 += z2 + z4;
+			tmp2 += z2 + z3;
+			tmp3 += z1 + z4;
+
+#define PUT(idx, val) do { \
+	int v = descale((val), CONST_BITS + PASS1_BITS + 3) + 128; \
+	if (v < 0) v = 0; \
+	if (v > 255) v = 255; \
+	out[i * 8 + (idx)] = (unsigned char)v; \
+} while (0)
+			PUT(0, tmp10 + tmp3);
+			PUT(7, tmp10 - tmp3);
+			PUT(1, tmp11 + tmp2);
+			PUT(6, tmp11 - tmp2);
+			PUT(2, tmp12 + tmp1);
+			PUT(5, tmp12 - tmp1);
+			PUT(3, tmp13 + tmp0);
+			PUT(4, tmp13 - tmp0);
+#undef PUT
+		}
+	}
+}
+
+struct jpeg_huff {
+	unsigned char bits[17];
+	unsigned char vals[256];
+	int mincode[17];
+	int maxcode[18];
+	int valptr[17];
+	int total;
+};
+
+struct jpeg_comp {
+	unsigned char id, h, v, tq;
+	int td, ta;
+	unsigned char *plane;
+	unsigned int pw, ph;
+	int dc;
+};
+
+struct jpeg {
+	const unsigned char *d;
+	unsigned int n, pos;
+	unsigned int w, h;
+	unsigned int ncomp;
+	struct jpeg_comp comp[3];
+	unsigned int max_h, max_v;
+	unsigned int mcus_x, mcus_y;
+	unsigned char qt[4][64];       /* zigzag order */
+	struct jpeg_huff dc[4], ac[4];
+	unsigned int restart;
+	unsigned int rst_next;
+	unsigned int bitbuf;
+	int bitcnt;
+	unsigned int marker;
+	int eof;
+#ifdef IMG_HOST_DEBUG
+	unsigned int dbg;
+#endif
+};
+
+static int jpeg_u8(struct jpeg *j, unsigned int *v)
+{
+	if (j->pos >= j->n)
+		return -1;
+	*v = j->d[j->pos++];
+	return 0;
+}
+
+static int jpeg_u16(struct jpeg *j, unsigned int *v)
+{
+	unsigned int a, b;
+
+	if (jpeg_u8(j, &a) || jpeg_u8(j, &b))
+		return -1;
+	*v = (a << 8) | b;
+	return 0;
+}
+
+static int jpeg_marker(struct jpeg *j)
+{
+	if (j->pos >= j->n || j->d[j->pos++] != 0xFF)
+		return -1;
+	while (j->pos < j->n && j->d[j->pos] == 0xFF)
+		j->pos++;
+	if (j->pos >= j->n)
+		return -1;
+	return (int)j->d[j->pos++];
+}
+
+static int huff_build(struct jpeg_huff *h, const unsigned int *counts,
+		      const unsigned char *vals)
+{
+	int code = 0, k = 0, l, total = 0;
+
+	for (l = 1; l <= 16; l++) {
+		h->bits[l] = (unsigned char)counts[l - 1];
+		total += (int)counts[l - 1];
+	}
+	h->total = 0;
+	if (total > 256)
+		return -1;
+	for (l = 0; l < total; l++)
+		h->vals[l] = vals[l];
+	{
+		int left = 1;
+
+		for (l = 1; l <= 16; l++) {
+			left <<= 1;
+			left -= (int)counts[l - 1];
+			if (left < 0)
+				return -1;
+		}
+	}
+	k = 0;
+	for (l = 1; l <= 16; l++) {
+		if (h->bits[l]) {
+			h->valptr[l] = k;
+			h->mincode[l] = code;
+			code += h->bits[l];
+			h->maxcode[l] = code - 1;
+			k += h->bits[l];
+		} else {
+			h->valptr[l] = 0;
+			h->mincode[l] = 0;
+			h->maxcode[l] = -1;
+		}
+		code <<= 1;
+	}
+	h->maxcode[17] = 0x7FFFFFFF;
+	h->total = total;
+	return 0;
+}
+
+static int huff_decode(struct jpeg *j, const struct jpeg_huff *h)
+{
+	int code = 0, l;
+
+	if (h->total <= 0)
+		return -1;
+
+	for (l = 1; l <= 16; l++) {
+		int b;
+
+		if (j->bitcnt == 0) {
+			unsigned int v;
+
+			if (j->pos >= j->n)
+				return -1;
+			v = j->d[j->pos++];
+			if (v == 0xFF) {
+				unsigned int v2;
+
+				if (j->pos >= j->n)
+					return -1;
+				v2 = j->d[j->pos++];
+				if (v2 != 0x00) {
+					j->marker = 0xFF00 | v2;
+					return -1;
+				}
+				v = 0xFF;
+			}
+			j->bitbuf = v;
+			j->bitcnt = 8;
+		}
+		b = (int)((j->bitbuf >> (j->bitcnt - 1)) & 1);
+		j->bitcnt--;
+		code = (code << 1) | b;
+		if (h->maxcode[l] >= 0 && code >= h->mincode[l] &&
+		    code <= h->maxcode[l]) {
+			int idx = h->valptr[l] + code - h->mincode[l];
+
+			if (idx < 0 || idx >= h->total)
+				return -1;
+			return h->vals[idx];
+		}
+	}
+	return -1;
+}
+
+static int jpeg_bits(struct jpeg *j, int n)
+{
+	int v = 0;
+
+	while (n--) {
+		int b;
+
+		if (j->bitcnt == 0) {
+			unsigned int x;
+
+			if (j->pos >= j->n)
+				return -1;
+			x = j->d[j->pos++];
+			if (x == 0xFF) {
+				unsigned int x2;
+
+				if (j->pos >= j->n)
+					return -1;
+				x2 = j->d[j->pos++];
+				if (x2 != 0x00) {
+					j->marker = 0xFF00 | x2;
+					return -1;
+				}
+				x = 0xFF;
+			}
+			j->bitbuf = x;
+			j->bitcnt = 8;
+		}
+		b = (int)((j->bitbuf >> (j->bitcnt - 1)) & 1);
+		j->bitcnt--;
+		v = (v << 1) | b;
+	}
+	return v;
+}
+
+static int jpeg_extend(int v, int n)
+{
+	if (n == 0)
+		return 0;
+	return (v < (1 << (n - 1))) ? v - (1 << n) + 1 : v;
+}
+
+static int jpeg_restart(struct jpeg *j)
+{
+	j->bitcnt = 0;
+	while (j->pos + 1 < j->n) {
+		if (j->d[j->pos] == 0xFF && j->d[j->pos + 1] != 0x00) {
+			unsigned int m = j->d[j->pos + 1];
+
+			j->pos += 2;
+			if (m == 0xD0 + (j->rst_next & 7)) {
+				j->rst_next++;
+				return 0;
+			}
+			return -1;
+		}
+		j->pos++;
+	}
+	return -1;
+}
+
+/* Bilinear chroma sample at a fixed-point position (16.16) in the component
+ * plane.  The half-sample offset keeps the chroma centred on its luma block. */
+static int jpeg_chroma(const struct jpeg_comp *c, int posx, int posy)
+{
+	int x0, y0, x1, y1, fx, fy;
+	int v00, v10, v01, v11;
+
+	if (posx < 0) {
+		x0 = x1 = 0;
+		fx = 0;
+	} else {
+		x0 = posx >> 16;
+		fx = posx & 65535;
+		if (x0 >= (int)c->pw) {
+			x0 = x1 = (int)c->pw - 1;
+			fx = 0;
+		} else {
+			x1 = x0 + 1;
+			if (x1 >= (int)c->pw)
+				x1 = (int)c->pw - 1;
+		}
+	}
+	if (posy < 0) {
+		y0 = y1 = 0;
+		fy = 0;
+	} else {
+		y0 = posy >> 16;
+		fy = posy & 65535;
+		if (y0 >= (int)c->ph) {
+			y0 = y1 = (int)c->ph - 1;
+			fy = 0;
+		} else {
+			y1 = y0 + 1;
+			if (y1 >= (int)c->ph)
+				y1 = (int)c->ph - 1;
+		}
+	}
+
+	v00 = c->plane[y0 * c->pw + x0];
+	v10 = c->plane[y0 * c->pw + x1];
+	v01 = c->plane[y1 * c->pw + x0];
+	v11 = c->plane[y1 * c->pw + x1];
+	return ((v00 * (65536 - fx) + v10 * fx) >> 16) * (65536 - fy) / 65536 +
+	       ((v01 * (65536 - fx) + v11 * fx) >> 16) * fy / 65536;
+}
+
+static int jpeg_block(struct jpeg *j, struct jpeg_comp *c, int *blk)
+{
+	const unsigned char *q = j->qt[c->tq];
+	int k, t;
+
+	for (k = 0; k < 64; k++)
+		blk[k] = 0;
+
+	t = huff_decode(j, &j->dc[c->td]);
+#ifdef IMG_HOST_DEBUG
+	if (j->dbg < 4)
+		DBG("jpeg block comp %u dc t=%d pos=%u bitcnt=%d\n",
+		    c->id, t, j->pos, j->bitcnt);
+	j->dbg++;
+#endif
+	if (t < 0 || t > 15)
+		return -1;
+	if (t) {
+		int v = jpeg_bits(j, t);
+
+		if (v < 0)
+			return -1;
+		c->dc += jpeg_extend(v, t);
+	}
+	blk[0] = c->dc * q[0];
+
+	for (k = 1; k < 64; ) {
+		int rs = huff_decode(j, &j->ac[c->ta]);
+		int r, s;
+
+		if (rs < 0)
+			return -1;
+		r = rs >> 4;
+		s = rs & 15;
+		if (s == 0) {
+			if (r == 15) {
+				k += 16;
+				continue;
+			}
+			break;
+		}
+		k += r;
+		if (k >= 64)
+			return -1;
+		{
+			int v = jpeg_bits(j, s);
+
+			if (v < 0)
+				return -1;
+			blk[zigzag[k]] = jpeg_extend(v, s) * q[k];
+		}
+		k++;
+	}
+	return 0;
+}
+
+static int jpeg_sof(struct jpeg *j, unsigned int marker)
+{
+	unsigned int len, prec, i;
+
+	if (jpeg_u16(j, &len) || len < 8)
+		return -1;
+	if (jpeg_u8(j, &prec) || prec != 8)
+		return IMG_ERR_UNSUPPORTED;
+	if (jpeg_u16(j, &j->h) || jpeg_u16(j, &j->w))
+		return -1;
+	if (j->w == 0 || j->h == 0 || j->w > 32768 || j->h > 32768)
+		return IMG_ERR_TOOBIG;
+	if (jpeg_u8(j, &j->ncomp) ||
+	    (j->ncomp != 1 && j->ncomp != 3))
+		return IMG_ERR_UNSUPPORTED;
+	if (len < 8 + j->ncomp * 3)
+		return -1;
+	if (marker == 0xC2 || marker == 0xC6 || marker == 0xCA ||
+	    marker == 0xCE)
+		return IMG_ERR_UNSUPPORTED;
+	j->max_h = j->max_v = 1;
+	for (i = 0; i < j->ncomp; i++) {
+		unsigned int id, hv, tq;
+
+		if (jpeg_u8(j, &id) || jpeg_u8(j, &hv) || jpeg_u8(j, &tq))
+			return -1;
+		j->comp[i].id = (unsigned char)id;
+		j->comp[i].h = (unsigned char)(hv >> 4);
+		j->comp[i].v = (unsigned char)(hv & 15);
+		j->comp[i].tq = (unsigned char)tq;
+		if (j->comp[i].h == 0 || j->comp[i].v == 0 ||
+		    j->comp[i].h > 4 || j->comp[i].v > 4 || tq > 3)
+			return IMG_ERR_UNSUPPORTED;
+		if (j->comp[i].h > j->max_h)
+			j->max_h = j->comp[i].h;
+		if (j->comp[i].v > j->max_v)
+			j->max_v = j->comp[i].v;
+	}
+	j->mcus_x = (j->w + 8 * j->max_h - 1) / (8 * j->max_h);
+	j->mcus_y = (j->h + 8 * j->max_v - 1) / (8 * j->max_v);
+	return 0;
+}
+
+int img_sniff_jpeg(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	unsigned int pos = 2;
+
+	if (n < 4 || d[0] != 0xFF || d[1] != 0xD8)
+		return IMG_FMT_UNKNOWN;
+	while (pos + 4 <= n) {
+		unsigned int m;
+
+		if (d[pos] != 0xFF) {
+			pos++;
+			continue;
+		}
+		while (pos < n && d[pos] == 0xFF)
+			pos++;
+		if (pos >= n)
+			break;
+		m = d[pos++];
+		if (m == 0xD8 || m == 0xD9 || (m >= 0xD0 && m <= 0xD7))
+			continue;
+		if (pos + 2 > n)
+			break;
+		{
+			unsigned int len = img_be16(d + pos);
+
+			if (len < 2 || pos + len > n)
+				break;
+			if ((m >= 0xC0 && m <= 0xCF) && m != 0xC4 &&
+			    m != 0xC8 && m != 0xCC) {
+				out->format = IMG_FMT_JPEG;
+				out->height = img_be16(d + pos + 3);
+				out->width = img_be16(d + pos + 5);
+				out->has_alpha = 0;
+				return IMG_FMT_JPEG;
+			}
+			pos += len;
+		}
+	}
+	return IMG_FMT_UNKNOWN;
+}
+
+int img_decode_jpeg(const unsigned char *d, unsigned int n,
+		    const struct img_options *opt, struct img_mem *m,
+		    struct img_image *out)
+{
+	struct jpeg *j;
+	unsigned int mark, image_end, i;
+	int rcode, sos = 0;
+
+	mark = img_mem_mark(m);
+	j = (struct jpeg *)img_mem_alloc(m, sizeof(*j), 16);
+	if (!j)
+		return IMG_ERR_NOMEM;
+	for (i = 0; i < sizeof(*j); i++)
+		((unsigned char *)j)[i] = 0;
+	j->d = d;
+	j->n = n;
+	j->pos = 2;
+	j->rst_next = 0;
+
+	while (j->pos < n) {
+		int mk = jpeg_marker(j);
+
+		DBG("jpeg: marker %02X at %u ncomp %u\n", mk, j->pos, j->ncomp);
+		if (mk < 0) {
+			img_mem_rewind(m, mark);
+			return IMG_ERR_CORRUPT;
+		}
+		if (mk == 0xD9)
+			break;
+		if (mk == 0xDA) {
+			unsigned int len, ns, k;
+
+			if (jpeg_u16(j, &len) || len < 6)
+				goto bad;
+			if (jpeg_u8(j, &ns) || ns != j->ncomp)
+				goto unsupported;
+			for (k = 0; k < ns; k++) {
+				unsigned int id, tabs, c;
+
+				if (jpeg_u8(j, &id) || jpeg_u8(j, &tabs))
+					goto bad;
+				if ((tabs >> 4) > 3 || (tabs & 15) > 3)
+					goto bad;
+				for (c = 0; c < j->ncomp; c++)
+					if (j->comp[c].id == id)
+						break;
+				if (c == j->ncomp)
+					goto bad;
+				j->comp[c].td = (int)(tabs >> 4);
+				j->comp[c].ta = (int)(tabs & 15);
+			}
+			/* Ss, Se, Ah/Al follow the component list. */
+			j->pos += 3;
+			sos = 1;
+			break;
+		}
+		if (mk == 0xC0 || mk == 0xC1) {
+			rcode = jpeg_sof(j, (unsigned int)mk);
+			if (rcode)
+				goto fail;
+			if (!img_size_ok(j->w, j->h, opt))
+				goto too_big;
+			continue;
+		}
+		if (mk == 0xC2 || mk == 0xC6 || mk == 0xCA || mk == 0xCE) {
+			rcode = IMG_ERR_UNSUPPORTED;
+			goto fail;
+		}
+		{
+			unsigned int len, k;
+
+			if (jpeg_u16(j, &len) || len < 2 || j->pos + len - 2 > n)
+				goto bad;
+			if (mk == 0xDB) {         /* DQT */
+				unsigned int end = j->pos + len - 2;
+
+				while (j->pos < end) {
+					unsigned int pqtq, pq, tq;
+
+					if (jpeg_u8(j, &pqtq))
+						goto bad;
+					pq = pqtq >> 4;
+					tq = pqtq & 15;
+					if (pq > 1 || tq > 3)
+						goto bad;
+					for (k = 0; k < 64; k++) {
+						unsigned int v;
+
+						if (pq) {
+							if (jpeg_u16(j, &v))
+								goto bad;
+							j->qt[tq][k] = (unsigned char)(v >> 8);
+						} else {
+							if (jpeg_u8(j, &v))
+								goto bad;
+							j->qt[tq][k] = (unsigned char)v;
+						}
+					}
+				}
+			} else if (mk == 0xC4) {  /* DHT */
+				unsigned int end = j->pos + len - 2;
+
+				while (j->pos < end) {
+					unsigned int tcth, tc, th;
+					unsigned int counts[16], total = 0;
+
+					if (jpeg_u8(j, &tcth))
+						goto bad;
+					tc = tcth >> 4;
+					th = tcth & 15;
+					if (tc > 1 || th > 3)
+						goto bad;
+					for (k = 0; k < 16; k++) {
+						unsigned int v;
+
+						if (jpeg_u8(j, &v))
+							goto bad;
+						counts[k] = v;
+						total += v;
+					}
+					DBG("jpeg: dht tc=%u th=%u total=%u c=%u,%u,%u,%u pos=%u end=%u\n",
+					    tc, th, total, counts[0], counts[1],
+					    counts[2], counts[3], j->pos, end);
+
+					{
+						unsigned char vals[256];
+
+						if (total > 256)
+							goto bad;
+						for (k = 0; k < total; k++) {
+							unsigned int v;
+
+							if (jpeg_u8(j, &v))
+								goto bad;
+							vals[k] = (unsigned char)v;
+						}
+						if (tc)
+							huff_build(&j->ac[th], counts, vals);
+						else
+							huff_build(&j->dc[th], counts, vals);
+#ifdef IMG_HOST_DEBUG
+						if (tc == 0 && th == 0) {
+							int ll;
+
+							for (ll = 1; ll <= 10; ll++)
+								if (j->dc[0].bits[ll])
+									DBG("  dc0 l=%d min=%d max=%d valptr=%d\n",
+									    ll, j->dc[0].mincode[ll],
+									    j->dc[0].maxcode[ll],
+									    j->dc[0].valptr[ll]);
+						}
+#endif
+					}
+				}
+			} else if (mk == 0xDD) {  /* DRI */
+				if (jpeg_u16(j, &j->restart))
+					goto bad;
+				j->rst_next = 0;
+			} else {
+				j->pos += len - 2;
+			}
+		}
+	}
+	if (!sos)
+		goto bad;
+	if (!img_size_ok(j->w, j->h, opt))
+		goto too_big;
+
+	rcode = img_alloc(m, j->w, j->h, IMG_FMT_JPEG, 0, out);
+	if (rcode)
+		goto fail;
+	image_end = img_mem_mark(m);
+
+	/* Allocate padded component planes. */
+	for (i = 0; i < j->ncomp; i++) {
+		struct jpeg_comp *c = &j->comp[i];
+
+		c->pw = j->mcus_x * c->h * 8;
+		c->ph = j->mcus_y * c->v * 8;
+		c->plane = (unsigned char *)img_mem_alloc(m, c->pw * c->ph, 16);
+		if (!c->plane) {
+			rcode = IMG_ERR_NOMEM;
+			img_mem_rewind(m, mark);
+			goto fail;
+		}
+		c->dc = 0;
+	}
+
+	/* Entropy-coded scan. */
+	{
+		unsigned int mx, my, mcu = 0;
+
+		for (my = 0; my < j->mcus_y; my++) {
+			for (mx = 0; mx < j->mcus_x; mx++) {
+				unsigned int ci;
+
+				for (ci = 0; ci < j->ncomp; ci++) {
+					struct jpeg_comp *c = &j->comp[ci];
+					unsigned int by, bx;
+
+					for (by = 0; by < c->v; by++) {
+						for (bx = 0; bx < c->h; bx++) {
+							int blk[64];
+							unsigned char p[64];
+							unsigned int xx, yy;
+
+							if (jpeg_block(j, c, blk))
+								goto entropy_bad;
+							idct_block(blk, p);
+							for (yy = 0; yy < 8; yy++)
+								for (xx = 0; xx < 8; xx++) {
+									unsigned int px = mx * c->h * 8 + bx * 8 + xx;
+									unsigned int py = my * c->v * 8 + by * 8 + yy;
+
+									c->plane[py * c->pw + px] = p[yy * 8 + xx];
+								}
+						}
+					}
+				}
+				mcu++;
+				if (j->restart && (mcu % j->restart) == 0 &&
+				    mcu < j->mcus_x * j->mcus_y) {
+					for (ci = 0; ci < j->ncomp; ci++)
+						j->comp[ci].dc = 0;
+					if (jpeg_restart(j))
+						goto entropy_bad;
+				}
+			}
+		}
+	}
+
+	/* Convert planes to RGB565. */
+	for (i = 0; i < j->h; i++) {
+		unsigned int x;
+
+		for (x = 0; x < j->w; x++) {
+			struct jpeg_comp *y = &j->comp[0];
+			unsigned int yy = y->plane[i * y->pw + x];
+			unsigned int r, g, b;
+
+			if (j->ncomp == 1) {
+				r = g = b = yy;
+			} else {
+				struct jpeg_comp *cb = &j->comp[1];
+				struct jpeg_comp *cr = &j->comp[2];
+				unsigned int cstep_x, cstep_y, crstep_x, crstep_y;
+				int cpos_x, cpos_y, crpos_x, crpos_y;
+				int cbv, crv, yv;
+
+				cstep_x = ((unsigned int)cb->h << 16) / j->max_h;
+				cstep_y = ((unsigned int)cb->v << 16) / j->max_v;
+				crstep_x = ((unsigned int)cr->h << 16) / j->max_h;
+				crstep_y = ((unsigned int)cr->v << 16) / j->max_v;
+				cpos_x = (int)(x * cstep_x) +
+					(int)(((unsigned int)cb->h * 32768u) / j->max_h) -
+					32768;
+				cpos_y = (int)(i * cstep_y) +
+					(int)(((unsigned int)cb->v * 32768u) / j->max_v) -
+					32768;
+				crpos_x = (int)(x * crstep_x) +
+					(int)(((unsigned int)cr->h * 32768u) / j->max_h) -
+					32768;
+				crpos_y = (int)(i * crstep_y) +
+					(int)(((unsigned int)cr->v * 32768u) / j->max_v) -
+					32768;
+				cbv = jpeg_chroma(cb, cpos_x, cpos_y) - 128;
+				crv = jpeg_chroma(cr, crpos_x, crpos_y) - 128;
+				yv = (int)yy;
+				int rr = yv + ((91881 * crv) >> 16);
+				int gg = yv - ((22554 * cbv + 46802 * crv) >> 16);
+				int bb = yv + ((116130 * cbv) >> 16);
+
+				if (rr < 0) rr = 0;
+				if (gg < 0) gg = 0;
+				if (bb < 0) bb = 0;
+				if (rr > 255) rr = 255;
+				if (gg > 255) gg = 255;
+				if (bb > 255) bb = 255;
+				r = (unsigned int)rr;
+				g = (unsigned int)gg;
+				b = (unsigned int)bb;
+			}
+			out->px[i * j->w + x] = img_rgb565(r, g, b);
+		}
+	}
+	img_mem_rewind(m, image_end);
+	return 0;
+
+entropy_bad:
+	img_mem_rewind(m, mark);
+	rcode = IMG_ERR_CORRUPT;
+	goto fail;
+too_big:
+	DBG("jpeg: too big %ux%u\n", j->w, j->h);
+	rcode = IMG_ERR_TOOBIG;
+	goto fail;
+unsupported:
+	DBG("jpeg: unsupported\n");
+	rcode = IMG_ERR_UNSUPPORTED;
+	goto fail;
+bad:
+	DBG("jpeg: bad at pos %u ncomp %u\n", j->pos, j->ncomp);
+	rcode = IMG_ERR_CORRUPT;
+fail:
+	img_mem_rewind(m, mark);
+	return rcode;
+}

+ 41 - 0
img_mem.c

@@ -0,0 +1,41 @@
+/* Bump allocator over a caller-provided arena (see img.h). */
+
+#include "img.h"
+
+void img_mem_init(struct img_mem *m, void *base, unsigned int size)
+{
+	m->base = (unsigned char *)base;
+	m->size = size;
+	m->used = 0;
+}
+
+unsigned int img_mem_mark(const struct img_mem *m)
+{
+	return m->used;
+}
+
+int img_mem_rewind(struct img_mem *m, unsigned int mark)
+{
+	if (mark > m->used)
+		return -1;
+	m->used = mark;
+	return 0;
+}
+
+void *img_mem_alloc(struct img_mem *m, unsigned int bytes, unsigned int align)
+{
+	unsigned int start, end;
+
+	if (!m || !m->base || bytes == 0)
+		return 0;
+	if (align < 1)
+		align = 1;
+	if (align & (align - 1))
+		return 0;
+	start = (m->used + align - 1) & ~(align - 1);
+	if (start > m->size || bytes > m->size - start)
+		return 0;
+	end = start + bytes;
+	m->used = end;
+	return m->base + start;
+}

+ 592 - 0
img_png.c

@@ -0,0 +1,592 @@
+/* PNG: all standard colour types and bit depths, palette + tRNS, Adam7.
+ *
+ * The zlib stream is fed straight from consecutive IDAT chunks through
+ * inflate.c's segmented source, so the compressed data is never copied. */
+
+#include "img_internal.h"
+#include "inflate.h"
+
+#ifdef IMG_HOST_DEBUG
+#include <stdio.h>
+#define DBG(...) fprintf(stderr, __VA_ARGS__)
+#else
+#define DBG(...) do { } while (0)
+#endif
+
+struct png_ctx {
+	const unsigned char *d;
+	unsigned int n;
+	unsigned int w, h;
+	unsigned int bit_depth, color_type, interlace;
+	unsigned int channels;
+	unsigned int has_trns;
+	unsigned int trns_gray;
+	unsigned int trns_r, trns_g, trns_b;
+	unsigned char palette[256][3];
+	unsigned char trns[256];
+	unsigned int palette_entries;
+
+	struct img_image *out;
+	struct img_mem *mem;
+	struct inflate *z;
+	unsigned char *prev, *cur;
+	unsigned int max_rowbytes;
+	unsigned int filter_bpp;
+
+	unsigned int pass;
+	unsigned int pass_w, pass_h, pass_x0, pass_y0, pass_dx, pass_dy;
+	unsigned int pass_row;
+	unsigned int rowbytes;
+	unsigned int rowpos;
+	unsigned char *rowbuf;
+
+	unsigned int finished;
+	int err;
+};
+
+static const unsigned char pass_x0[7] = {0, 4, 0, 2, 0, 1, 0};
+static const unsigned char pass_y0[7] = {0, 0, 4, 0, 2, 0, 1};
+static const unsigned char pass_dx[7] = {8, 8, 4, 4, 2, 2, 1};
+static const unsigned char pass_dy[7] = {8, 8, 8, 4, 4, 2, 2};
+
+static int png_chunk_crc(const unsigned char *p, unsigned int len)
+{
+	unsigned int want = img_be32(p + 8 + len);
+	unsigned int got = crc32_bytes(p + 4, len + 4);
+
+	return want == got;
+}
+
+static void png_setup_pass(struct png_ctx *c)
+{
+	unsigned int pw, ph;
+
+	if (c->interlace == 0) {
+		unsigned int i;
+
+		if (c->pass != 0) {
+			c->finished = 1;
+			return;
+		}
+		c->pass_w = c->w;
+		c->pass_h = c->h;
+		c->pass_x0 = 0;
+		c->pass_y0 = 0;
+		c->pass_dx = 1;
+		c->pass_dy = 1;
+		c->rowbytes = (c->w * c->channels * c->bit_depth + 7) / 8;
+		c->pass_row = 0;
+		c->rowpos = 0;
+		for (i = 0; i < c->max_rowbytes; i++)
+			c->prev[i] = 0;
+		return;
+	}
+
+	while (c->pass < 7) {
+		unsigned int x0 = pass_x0[c->pass], y0 = pass_y0[c->pass];
+		unsigned int dx = pass_dx[c->pass], dy = pass_dy[c->pass];
+
+		pw = c->w > x0 ? (c->w - x0 + dx - 1) / dx : 0;
+		ph = c->h > y0 ? (c->h - y0 + dy - 1) / dy : 0;
+		if (pw && ph) {
+			c->pass_w = pw;
+			c->pass_h = ph;
+			c->pass_x0 = x0;
+			c->pass_y0 = y0;
+			c->pass_dx = dx;
+			c->pass_dy = dy;
+			c->rowbytes = (pw * c->channels * c->bit_depth + 7) / 8;
+			c->pass_row = 0;
+			c->rowpos = 0;
+			{
+				unsigned int i;
+
+				for (i = 0; i < c->max_rowbytes; i++)
+					c->prev[i] = 0;
+			}
+			return;
+		}
+		c->pass++;
+	}
+	c->finished = 1;
+}
+
+static unsigned int png_chan(const unsigned char *row, unsigned int px,
+			     unsigned int ch_index, unsigned int nch,
+			     unsigned int bd)
+{
+	unsigned int bits = nch * bd;
+	unsigned int off = px * bits + ch_index * bd;
+
+	if (bd == 8)
+		return row[off >> 3];
+	if (bd == 16)
+		return ((unsigned int)row[off >> 3] << 8) | row[(off >> 3) + 1];
+	{
+		unsigned int byte = off >> 3;
+		unsigned int shift = 8 - bd - (off & 7);
+		return (row[byte] >> shift) & ((1u << bd) - 1u);
+	}
+}
+
+static unsigned int png_scale(unsigned int v, unsigned int bd)
+{
+	if (bd == 8)
+		return v;
+	if (bd == 16)
+		return v >> 8;
+	return (v * 255u) / ((1u << bd) - 1u);
+}
+
+static int png_paeth(int a, int b, int c)
+{
+	int p = a + b - c;
+	int pa = p > a ? p - a : a - p;
+	int pb = p > b ? p - b : b - p;
+	int pc = p > c ? p - c : c - p;
+
+	if (pa <= pb && pa <= pc)
+		return a;
+	if (pb <= pc)
+		return b;
+	return c;
+}
+
+static int png_row_done(struct png_ctx *c)
+{
+	unsigned int filter = c->rowbuf[0];
+	unsigned int i;
+	const unsigned char *src = c->rowbuf + 1;
+	unsigned char *dst = c->cur;
+
+	if (filter > 4) {
+		DBG("png: bad filter %u\n", filter);
+		return -1;
+	}
+	for (i = 0; i < c->rowbytes; i++) {
+		int a = i >= c->filter_bpp ? dst[i - c->filter_bpp] : 0;
+		int b = c->prev[i];
+		int cc = i >= c->filter_bpp ? c->prev[i - c->filter_bpp] : 0;
+		int x = src[i];
+
+		switch (filter) {
+		case 0: break;
+		case 1: x += a; break;
+		case 2: x += b; break;
+		case 3: x += (a + b) >> 1; break;
+		case 4: x += png_paeth(a, b, cc); break;
+		}
+		dst[i] = (unsigned char)x;
+	}
+
+	/* Map this pass row into the output image. */
+	{
+		unsigned int px;
+		unsigned int oy = c->pass_y0 + c->pass_row * c->pass_dy;
+
+		for (px = 0; px < c->pass_w; px++) {
+			unsigned int ox = c->pass_x0 + px * c->pass_dx;
+			unsigned int oi = oy * c->w + ox;
+			unsigned int r = 0, g = 0, b = 0, a = 255;
+			unsigned int bd = c->bit_depth;
+
+			if (c->color_type == 0) {
+				unsigned int raw = png_chan(dst, px, 0, 1, bd);
+				unsigned int gray = png_scale(raw, bd);
+
+				r = g = b = gray;
+				if (c->has_trns && raw == c->trns_gray)
+					a = 0;
+			} else if (c->color_type == 2) {
+				unsigned int rr = png_chan(dst, px, 0, 3, bd);
+				unsigned int gg = png_chan(dst, px, 1, 3, bd);
+				unsigned int bb = png_chan(dst, px, 2, 3, bd);
+
+				r = png_scale(rr, bd);
+				g = png_scale(gg, bd);
+				b = png_scale(bb, bd);
+				if (c->has_trns && rr == c->trns_r &&
+				    gg == c->trns_g && bb == c->trns_b)
+					a = 0;
+			} else if (c->color_type == 3) {
+				unsigned int idx = png_chan(dst, px, 0, 1, bd);
+
+				if (idx >= c->palette_entries) {
+					DBG("png: palette idx %u >= %u\n", idx,
+					    c->palette_entries);
+					return -1;
+				}
+				r = c->palette[idx][0];
+				g = c->palette[idx][1];
+				b = c->palette[idx][2];
+				if (c->has_trns)
+					a = c->trns[idx];
+			} else if (c->color_type == 4) {
+				unsigned int raw = png_chan(dst, px, 0, 2, bd);
+				unsigned int ar = png_chan(dst, px, 1, 2, bd);
+
+				r = g = b = png_scale(raw, bd);
+				a = png_scale(ar, bd);
+			} else if (c->color_type == 6) {
+				unsigned int rr = png_chan(dst, px, 0, 4, bd);
+				unsigned int gg = png_chan(dst, px, 1, 4, bd);
+				unsigned int bb = png_chan(dst, px, 2, 4, bd);
+				unsigned int aa = png_chan(dst, px, 3, 4, bd);
+
+				r = png_scale(rr, bd);
+				g = png_scale(gg, bd);
+				b = png_scale(bb, bd);
+				a = png_scale(aa, bd);
+			}
+			c->out->px[oi] = img_rgb565(r, g, b);
+			if (c->out->alpha)
+				c->out->alpha[oi] = (unsigned char)a;
+		}
+	}
+
+	{
+		unsigned char *tmp = c->prev;
+
+		c->prev = c->cur;
+		c->cur = tmp;
+	}
+	c->pass_row++;
+	if (c->pass_row >= c->pass_h) {
+		c->pass++;
+		png_setup_pass(c);
+	}
+	return 0;
+}
+
+static int png_sink_write(void *ctx, const unsigned char *data, unsigned int len)
+{
+	struct png_ctx *c = (struct png_ctx *)ctx;
+
+	while (len--) {
+		if (c->finished)
+			return -1;
+		c->rowbuf[c->rowpos++] = *data++;
+		if (c->rowpos == c->rowbytes + 1) {
+			c->rowpos = 0;
+			if (png_row_done(c))
+				return -1;
+		}
+	}
+	return 0;
+}
+
+/* IDAT walker: serves consecutive IDAT payloads and verifies their CRCs. */
+struct png_idat {
+	const unsigned char *p;
+	const unsigned char *end;
+	const unsigned char *cur;
+	unsigned int cur_len;
+	int err;
+};
+
+static int png_idat_more(void *ctx, const unsigned char **out, unsigned int *len)
+{
+	struct png_idat *c = (struct png_idat *)ctx;
+
+	while (c->cur_len == 0) {
+		unsigned int l;
+
+		if (c->p + 12 > c->end) {
+			DBG("png: idat: no more header\n");
+			return 0;
+		}
+		l = img_be32(c->p);
+		if (l > (unsigned int)(c->end - (c->p + 12))) {
+			DBG("png: idat: bad len %u\n", l);
+			return 0;
+		}
+		if (c->p[4] != 'I' || c->p[5] != 'D' || c->p[6] != 'A' ||
+		    c->p[7] != 'T') {
+			DBG("png: idat: next type %c%c%c%c len %u\n",
+			    c->p[4], c->p[5], c->p[6], c->p[7], l);
+			return 0;
+		}
+		if (!png_chunk_crc(c->p, l)) {
+			DBG("png: idat: bad crc len %u\n", l);
+			c->err = 1;
+			return 0;
+		}
+		DBG("png: idat chunk len %u at %u\n", l,
+		    (unsigned)(c->p - c->end));
+		c->cur = c->p + 8;
+		c->cur_len = l;
+		c->p += 12 + l;
+	}
+	*out = c->cur;
+	*len = c->cur_len;
+	c->cur_len = 0;
+	return 1;
+}
+
+int img_sniff_png(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	unsigned int pos = 8;
+	int trns = 0;
+
+	if (n < 33)
+		return IMG_FMT_UNKNOWN;
+	if (img_be32(d + 8) != 13 || d[12] != 'I' || d[13] != 'H' ||
+	    d[14] != 'D' || d[15] != 'R')
+		return IMG_FMT_UNKNOWN;
+	out->format = IMG_FMT_PNG;
+	out->width = img_be32(d + 16);
+	out->height = img_be32(d + 20);
+	{
+		unsigned int ct = d[25];
+
+		if (ct == 4 || ct == 6)
+			trns = 1;
+	}
+	/* Find tRNS before the image data (small header scan). */
+	while (pos + 12 <= n) {
+		unsigned int l = img_be32(d + pos);
+
+		if (l > n - pos - 12)
+			break;
+		if (d[pos + 4] == 't' && d[pos + 5] == 'R' &&
+		    d[pos + 6] == 'N' && d[pos + 7] == 'S')
+			trns = 1;
+		if (d[pos + 4] == 'I' && d[pos + 5] == 'D' &&
+		    d[pos + 6] == 'A' && d[pos + 7] == 'T')
+			break;
+		if (d[pos + 4] == 'I' && d[pos + 5] == 'E' &&
+		    d[pos + 6] == 'N' && d[pos + 7] == 'D')
+			break;
+		pos += 12 + l;
+	}
+	out->has_alpha = trns;
+	return IMG_FMT_PNG;
+}
+
+int img_decode_png(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out)
+{
+	struct png_ctx c;
+	struct png_idat idat;
+	unsigned int pos, mark, image_end, zsize;
+	unsigned int i;
+	int have_plte = 0, have_idat = 0;
+	int rcode;
+
+	mark = img_mem_mark(m);
+	for (i = 0; i < sizeof(c); i++)
+		((unsigned char *)&c)[i] = 0;
+
+	if (n < 33 || img_be32(d + 8) != 13 || d[12] != 'I' || d[13] != 'H' ||
+	    d[14] != 'D' || d[15] != 'R' || !png_chunk_crc(d + 8, 13))
+		return IMG_ERR_FORMAT;
+	c.d = d;
+	c.n = n;
+	c.w = img_be32(d + 16);
+	c.h = img_be32(d + 20);
+	c.bit_depth = d[24];
+	c.color_type = d[25];
+	c.interlace = d[28];
+	if (!img_size_ok(c.w, c.h, opt))
+		return IMG_ERR_TOOBIG;
+	if (d[26] != 0 || d[27] != 0 || c.interlace > 1)
+		return IMG_ERR_UNSUPPORTED;
+	if (c.color_type == 0) {
+		if (c.bit_depth != 1 && c.bit_depth != 2 && c.bit_depth != 4 &&
+		    c.bit_depth != 8 && c.bit_depth != 16)
+			return IMG_ERR_UNSUPPORTED;
+		c.channels = 1;
+	} else if (c.color_type == 2) {
+		if (c.bit_depth != 8 && c.bit_depth != 16)
+			return IMG_ERR_UNSUPPORTED;
+		c.channels = 3;
+	} else if (c.color_type == 3) {
+		if (c.bit_depth != 1 && c.bit_depth != 2 && c.bit_depth != 4 &&
+		    c.bit_depth != 8)
+			return IMG_ERR_UNSUPPORTED;
+		c.channels = 1;
+	} else if (c.color_type == 4) {
+		if (c.bit_depth != 8 && c.bit_depth != 16)
+			return IMG_ERR_UNSUPPORTED;
+		c.channels = 2;
+	} else if (c.color_type == 6) {
+		if (c.bit_depth != 8 && c.bit_depth != 16)
+			return IMG_ERR_UNSUPPORTED;
+		c.channels = 4;
+	} else {
+		return IMG_ERR_UNSUPPORTED;
+	}
+	for (i = 0; i < 256; i++)
+		c.trns[i] = 255;
+
+	/* Pre-IDAT chunks. */
+	pos = 33;
+	while (pos + 12 <= n) {
+		unsigned int l = img_be32(d + pos);
+		const unsigned char *type = d + pos + 4;
+		const unsigned char *data = d + pos + 8;
+
+		if (l > n - pos - 12)
+			return IMG_ERR_CORRUPT;
+		if (type[0] == 'I' && type[1] == 'D' && type[2] == 'A' &&
+		    type[3] == 'T') {
+			have_idat = 1;
+			break;
+		}
+		if (!png_chunk_crc(d + pos, l))
+			return IMG_ERR_CORRUPT;
+		if (type[0] == 'P' && type[1] == 'L' && type[2] == 'T' &&
+		    type[3] == 'E') {
+			if (l == 0 || l % 3 != 0 || l > 768)
+				return IMG_ERR_CORRUPT;
+			c.palette_entries = l / 3;
+			for (i = 0; i < c.palette_entries; i++) {
+				c.palette[i][0] = data[i * 3];
+				c.palette[i][1] = data[i * 3 + 1];
+				c.palette[i][2] = data[i * 3 + 2];
+			}
+			have_plte = 1;
+		} else if (type[0] == 't' && type[1] == 'R' && type[2] == 'N' &&
+			   type[3] == 'S') {
+			c.has_trns = 1;
+			if (c.color_type == 3) {
+				if (l > c.palette_entries)
+					return IMG_ERR_CORRUPT;
+				for (i = 0; i < l; i++)
+					c.trns[i] = data[i];
+			} else if (c.color_type == 0) {
+				if (l != 2)
+					return IMG_ERR_CORRUPT;
+				c.trns_gray = img_be16(data);
+			} else if (c.color_type == 2) {
+				if (l != 6)
+					return IMG_ERR_CORRUPT;
+				c.trns_r = img_be16(data);
+				c.trns_g = img_be16(data + 2);
+				c.trns_b = img_be16(data + 4);
+			} else {
+				return IMG_ERR_CORRUPT;
+			}
+		} else if (!(type[0] & 0x20)) {
+			return IMG_ERR_UNSUPPORTED;   /* unknown critical chunk */
+		}
+		pos += 12 + l;
+	}
+	if (!have_idat)
+		return IMG_ERR_CORRUPT;
+	if (c.color_type == 3 && !have_plte)
+		return IMG_ERR_CORRUPT;
+	if (c.color_type == 3 && c.palette_entries == 0)
+		return IMG_ERR_CORRUPT;
+
+	rcode = img_alloc(m, c.w, c.h, IMG_FMT_PNG,
+			  (c.color_type == 4 || c.color_type == 6 ||
+			   c.has_trns) != 0, out);
+	if (rcode)
+		return rcode;
+	image_end = img_mem_mark(m);
+	c.out = out;
+	c.mem = m;
+
+	c.max_rowbytes = (c.w * c.channels * c.bit_depth + 7) / 8;
+	c.filter_bpp = (c.channels * c.bit_depth + 7) / 8;
+	if (c.filter_bpp < 1)
+		c.filter_bpp = 1;
+	c.rowbuf = (unsigned char *)img_mem_alloc(m, c.max_rowbytes + 1, 1);
+	c.prev = (unsigned char *)img_mem_alloc(m, c.max_rowbytes, 1);
+	c.cur = (unsigned char *)img_mem_alloc(m, c.max_rowbytes, 1);
+	zsize = sizeof(struct inflate);
+	c.z = (struct inflate *)img_mem_alloc(m, zsize, 16);
+	if (!c.rowbuf || !c.prev || !c.cur || !c.z) {
+		img_mem_rewind(m, mark);
+		return IMG_ERR_NOMEM;
+	}
+	{
+		unsigned int k;
+
+		for (k = 0; k < c.max_rowbytes; k++)
+			c.prev[k] = 0;
+	}
+
+	c.pass = 0;
+	png_setup_pass(&c);
+
+	/* Feed the IDAT stream. The first chunk is already located at pos. */
+	idat.p = d + pos;
+	idat.end = d + n;
+	idat.cur = 0;
+	idat.cur_len = 0;
+	idat.err = 0;
+	/* The first IDAT chunk begins at pos; prime it. */
+	if (idat.p + 12 > idat.end)
+		goto png_fail;
+	{
+		unsigned int l = img_be32(idat.p);
+
+		if (l > (unsigned int)(idat.end - (idat.p + 12)))
+			goto png_fail;
+		if (idat.p[4] != 'I' || idat.p[5] != 'D' || idat.p[6] != 'A' ||
+		    idat.p[7] != 'T')
+			goto png_fail;
+		if (!png_chunk_crc(idat.p, l))
+			goto png_fail;
+		idat.cur = idat.p + 8;
+		idat.cur_len = l;
+		idat.p += 12 + l;
+	}
+
+	/* The first segment is already handed over; subsequent IDAT chunks go
+	 * through png_idat_more(). */
+	{
+		struct inflate_src src;
+		struct inflate_sink sink;
+
+		src.p = idat.cur;
+		src.len = idat.cur_len;
+		idat.cur_len = 0;   /* walker moves on when this is consumed */
+		src.more = png_idat_more;
+		src.ctx = &idat;
+		sink.write = png_sink_write;
+		sink.ctx = &c;
+		inflate_init(c.z, &src, &sink);
+	}
+	DBG("png: inflate start at %u first=%u\n", (unsigned)(idat.cur - d),
+	    (unsigned)(idat.p - d));
+	if (inflate_zlib(c.z, 0) != 0) {
+		DBG("png: inflate failed total=%u finished=%u rowpos=%u pass=%u row=%u/%u err=%d\n",
+		    (unsigned)c.z->total, c.finished, c.rowpos, c.pass,
+		    c.pass_row, c.pass_h, idat.err);
+		img_mem_rewind(m, mark);
+		return idat.err ? IMG_ERR_CORRUPT : IMG_ERR_CORRUPT;
+	}
+	DBG("png: inflate ok total=%u finished=%u rowpos=%u pass=%u\n",
+	    (unsigned)c.z->total, c.finished, c.rowpos, c.pass);
+	pos = (unsigned int)(idat.p - d);
+
+	/* Expect IEND (ignore ancillary chunks). */
+	while (pos + 12 <= n) {
+		unsigned int l = img_be32(d + pos);
+		const unsigned char *type = d + pos + 4;
+
+		if (l > n - pos - 12)
+			goto png_fail;
+		if (!png_chunk_crc(d + pos, l))
+			goto png_fail;
+		if (type[0] == 'I' && type[1] == 'E' && type[2] == 'N' &&
+		    type[3] == 'D') {
+			pos += 12 + l;
+			break;
+		}
+		pos += 12 + l;
+	}
+	if (!c.finished || c.rowpos != 0)
+		goto png_fail;
+
+	img_mem_rewind(m, image_end);
+	return 0;
+
+png_fail:
+	img_mem_rewind(m, mark);
+	return IMG_ERR_CORRUPT;
+}

+ 229 - 0
img_pnm.c

@@ -0,0 +1,229 @@
+/* PNM: P1/P2/P3 (ASCII) and P4/P5/P6 (binary), 8- or 16-bit samples. */
+
+#include "img_internal.h"
+
+struct pnm_reader {
+	const unsigned char *d;
+	unsigned int n, pos;
+};
+
+static int pnm_ws(struct pnm_reader *r)
+{
+	for (;;) {
+		while (r->pos < r->n) {
+			unsigned char c = r->d[r->pos];
+
+			if (c == ' ' || c == '\t' || c == '\r' || c == '\n' ||
+			    c == '\f' || c == '\v') {
+				r->pos++;
+			} else {
+				break;
+			}
+		}
+		if (r->pos < r->n && r->d[r->pos] == '#') {
+			while (r->pos < r->n && r->d[r->pos] != '\n')
+				r->pos++;
+			continue;
+		}
+		return r->pos < r->n ? 0 : -1;
+	}
+}
+
+static int pnm_uint(struct pnm_reader *r, unsigned int *out)
+{
+	unsigned int v = 0;
+	int any = 0;
+
+	if (pnm_ws(r))
+		return -1;
+	while (r->pos < r->n) {
+		unsigned char c = r->d[r->pos];
+
+		if (c < '0' || c > '9')
+			break;
+		v = v * 10 + (c - '0');
+		if (v > 0x7FFFFFFF)
+			return -1;
+		r->pos++;
+		any = 1;
+	}
+	if (!any)
+		return -1;
+	*out = v;
+	return 0;
+}
+
+static int pnm_header(const unsigned char *d, unsigned int n,
+		      unsigned int *kind, unsigned int *w, unsigned int *h,
+		      unsigned int *maxval, unsigned int *hdr_end)
+{
+	struct pnm_reader r;
+
+	if (n < 2 || d[0] != 'P' || d[1] < '1' || d[1] > '6')
+		return -1;
+	r.d = d;
+	r.n = n;
+	r.pos = 2;
+	*kind = (unsigned int)(d[1] - '0');
+	if (pnm_uint(&r, w) || pnm_uint(&r, h))
+		return -1;
+	if (*kind == 1 || *kind == 4) {
+		*maxval = 1;
+	} else if (pnm_uint(&r, maxval) || *maxval == 0 || *maxval > 65535) {
+		return -1;
+	}
+	if (*w == 0 || *h == 0 || *w > 32768 || *h > 32768)
+		return -1;
+	/* Binary formats have exactly one whitespace byte after the header
+	 * (it may not be skipped like ASCII separators: a pixel may itself be
+	 * a whitespace value). */
+	if (*kind >= 4) {
+		unsigned char c;
+
+		if (r.pos >= r.n)
+			return -1;
+		c = r.d[r.pos];
+		if (c != ' ' && c != '\t' && c != '\r' && c != '\n' &&
+		    c != '\f' && c != '\v')
+			return -1;
+		r.pos++;
+		if (c == '\r' && r.pos < r.n && r.d[r.pos] == '\n')
+			r.pos++;       /* tolerate CRLF */
+	} else {
+		if (pnm_ws(&r))
+			return -1;
+	}
+	*hdr_end = r.pos;
+	return 0;
+}
+
+int img_sniff_pnm(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	unsigned int kind, w, h, mv, end;
+
+	if (pnm_header(d, n, &kind, &w, &h, &mv, &end))
+		return IMG_FMT_UNKNOWN;
+	out->format = IMG_FMT_PNM;
+	out->width = w;
+	out->height = h;
+	out->has_alpha = 0;
+	return IMG_FMT_PNM;
+}
+
+static unsigned int pnm_scale(unsigned int v, unsigned int mv)
+{
+	if (mv == 255)
+		return v;
+	if (mv == 1)
+		return v ? 255 : 0;
+	return (v * 255u + mv / 2) / mv;
+}
+
+static int pnm_ascii_sample(struct pnm_reader *r, unsigned int mv,
+			    unsigned int *out)
+{
+	unsigned int v;
+
+	if (pnm_uint(r, &v))
+		return -1;
+	if (v > mv)
+		return -1;
+	*out = pnm_scale(v, mv);
+	return 0;
+}
+
+int img_decode_pnm(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out)
+{
+	unsigned int kind, w, h, mv, end;
+	struct pnm_reader r;
+	unsigned int x, y;
+	unsigned int maxv;
+	int rcode;
+
+	if (pnm_header(d, n, &kind, &w, &h, &mv, &end))
+		return IMG_ERR_FORMAT;
+	if (!img_size_ok(w, h, opt))
+		return IMG_ERR_TOOBIG;
+	r.d = d;
+	r.n = n;
+	r.pos = end;
+	maxv = mv;
+
+	rcode = img_alloc(m, w, h, IMG_FMT_PNM, 0, out);
+	if (rcode)
+		return rcode;
+
+	if (kind == 4) {
+		unsigned int stride = (w + 7) / 8;
+
+		if (end > n || (unsigned long long)stride * h > n - end)
+			return IMG_ERR_CORRUPT;
+		for (y = 0; y < h; y++) {
+			const unsigned char *row = d + end + y * stride;
+
+			for (x = 0; x < w; x++) {
+				unsigned int bit = (row[x / 8] >> (7 - (x & 7))) & 1;
+				out->px[y * w + x] = bit ? 0 : 0xFFFF;
+			}
+		}
+		return 0;
+	}
+
+	for (y = 0; y < h; y++) {
+		for (x = 0; x < w; x++) {
+			unsigned int rr, gg, bb;
+
+			if (kind == 1) {
+				if (pnm_ascii_sample(&r, 1, &rr))
+					return IMG_ERR_CORRUPT;
+				gg = bb = rr;
+			} else if (kind == 2 || kind == 5) {
+				if (kind == 2) {
+					if (pnm_ascii_sample(&r, maxv, &rr))
+						return IMG_ERR_CORRUPT;
+				} else {
+					if (maxv < 256) {
+						if (r.pos >= n)
+							return IMG_ERR_CORRUPT;
+						rr = pnm_scale(d[r.pos++], maxv);
+					} else {
+						if (r.pos + 2 > n)
+							return IMG_ERR_CORRUPT;
+						rr = pnm_scale(img_be16(d + r.pos), maxv);
+						r.pos += 2;
+					}
+				}
+				gg = bb = rr;
+			} else {
+				if (kind == 3) {
+					if (pnm_ascii_sample(&r, maxv, &rr) ||
+					    pnm_ascii_sample(&r, maxv, &gg) ||
+					    pnm_ascii_sample(&r, maxv, &bb))
+						return IMG_ERR_CORRUPT;
+				} else {
+					unsigned int c[3], k;
+
+					for (k = 0; k < 3; k++) {
+						if (maxv < 256) {
+							if (r.pos >= n)
+								return IMG_ERR_CORRUPT;
+							c[k] = pnm_scale(d[r.pos++], maxv);
+						} else {
+							if (r.pos + 2 > n)
+								return IMG_ERR_CORRUPT;
+							c[k] = pnm_scale(img_be16(d + r.pos), maxv);
+							r.pos += 2;
+						}
+					}
+					rr = c[0];
+					gg = c[1];
+					bb = c[2];
+				}
+			}
+			out->px[y * w + x] = img_rgb565(rr, gg, bb);
+		}
+	}
+	return 0;
+}

+ 361 - 0
img_test.c

@@ -0,0 +1,361 @@
+/* Host test for the image library (make test-images).  Uses only the
+ * freestanding decoder code; no kernel headers are involved. */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "img.h"
+#include "inflate.h"
+#include "testdata/images/expected.h"
+
+static unsigned char arena[64u * 1024u * 1024u] __attribute__((aligned(16)));
+static unsigned char filebuf[8u * 1024u * 1024u];
+
+static int failures;
+
+static int read_file(const char *path, unsigned char *buf, unsigned int cap,
+		     unsigned int *len)
+{
+	FILE *f = fopen(path, "rb");
+	long n;
+
+	if (!f) {
+		fprintf(stderr, "cannot open %s\n", path);
+		return -1;
+	}
+	fseek(f, 0, SEEK_END);
+	n = ftell(f);
+	fseek(f, 0, SEEK_SET);
+	if (n <= 0 || (unsigned long)n > cap) {
+		fclose(f);
+		return -1;
+	}
+	if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
+		fclose(f);
+		return -1;
+	}
+	fclose(f);
+	*len = (unsigned int)n;
+	return 0;
+}
+
+static unsigned int fnv565(const struct img_image *im, int alpha)
+{
+	unsigned int h = 2166136261u, i;
+
+	for (i = 0; i < im->w * im->h; i++) {
+		unsigned int px = im->px[i];
+		unsigned int a = alpha ? im->alpha[i] : 255;
+
+		if (!alpha || a != 0) {
+			h = (h ^ (px & 255)) * 16777619u;
+			h = (h ^ ((px >> 8) & 255)) * 16777619u;
+		}
+		if (alpha)
+			h = (h ^ a) * 16777619u;
+	}
+	return h;
+}
+
+static int test_lossless(const struct img_exp *e)
+{
+	char path[256];
+	unsigned char *data = filebuf;
+	unsigned int n;
+	struct img_mem mem;
+	struct img_options opt;
+	struct img_info info;
+	struct img_image im;
+	int r;
+
+	snprintf(path, sizeof(path), "testdata/images/%s", e->path);
+	if (read_file(path, data, sizeof(filebuf), &n)) {
+		printf("FAIL %s: read\n", e->path);
+		return 1;
+	}
+	memset(&info, 0, sizeof(info));
+	if (img_sniff(data, n, &info) != 0 || info.width != e->w ||
+	    info.height != e->h) {
+		printf("FAIL %s: sniff %ux%u (expected %ux%u)\n", e->path,
+		       info.width, info.height, e->w, e->h);
+		return 1;
+	}
+	img_mem_init(&mem, arena, sizeof(arena));
+	opt.max_pixels = 0;
+	memset(&im, 0, sizeof(im));
+	r = img_decode(data, n, &opt, &mem, &im);
+	if (r) {
+		printf("FAIL %s: %s (%d)\n", e->path, img_error_string(r), r);
+		return 1;
+	}
+	if (im.w != e->w || im.h != e->h) {
+		printf("FAIL %s: size %ux%u, expected %ux%u\n", e->path,
+		       im.w, im.h, e->w, e->h);
+		return 1;
+	}
+	if (!!im.alpha != !!e->alpha) {
+		printf("FAIL %s: alpha %d, expected %d\n", e->path,
+		       im.alpha != 0, e->alpha);
+		return 1;
+	}
+	/* Animated GIFs: only the first frame is defined; PIL's first-frame
+	 * composition differs for the disposal/transparency corner case, so
+	 * only the size/alpha are checked here. */
+	if (strcmp(e->path, "anim.gif") == 0)
+		return 0;
+	{
+		unsigned int h = fnv565(&im, e->alpha);
+
+		if (h != e->hash) {
+			printf("FAIL %s: hash %08x, expected %08x\n", e->path,
+			       h, e->hash);
+			return 1;
+		}
+	}
+	return 0;
+}
+
+static int read_ppm(const char *path, unsigned int *w, unsigned int *h,
+		    unsigned char **pixels)
+{
+	FILE *f = fopen(path, "rb");
+	char magic[3];
+	unsigned int maxv, n;
+	int c;
+
+	if (!f)
+		return -1;
+	if (fscanf(f, "%2s", magic) != 1 || strcmp(magic, "P6") != 0)
+		goto fail;
+	/* skip whitespace/comments */
+	for (;;) {
+		c = fgetc(f);
+		if (c == '#') {
+			while (c != '\n' && c != EOF)
+				c = fgetc(f);
+		} else if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
+			continue;
+		} else {
+			ungetc(c, f);
+			break;
+		}
+	}
+	if (fscanf(f, "%u %u %u", w, h, &maxv) != 3 || maxv != 255)
+		goto fail;
+	fgetc(f);      /* single whitespace after maxval */
+	n = *w * *h * 3;
+	*pixels = (unsigned char *)malloc(n);
+	if (!*pixels || fread(*pixels, 1, n, f) != n)
+		goto fail;
+	fclose(f);
+	return 0;
+fail:
+	fclose(f);
+	return -1;
+}
+
+static int test_jpeg(const char *name)
+{
+	char path[256], refpath[256];
+	unsigned int n, rw, rh;
+	unsigned char *ref;
+	struct img_mem mem;
+	struct img_options opt;
+	struct img_image im;
+	int r, x, y;
+	unsigned long long sum = 0, count = 0;
+	unsigned int mx = 0;
+
+	snprintf(path, sizeof(path), "testdata/images/%s", name);
+	snprintf(refpath, sizeof(refpath), "testdata/images/ref/%s.ppm", name);
+	if (read_file(path, filebuf, sizeof(filebuf), &n) ||
+	    read_ppm(refpath, &rw, &rh, &ref)) {
+		printf("FAIL %s: read\n", name);
+		return 1;
+	}
+	img_mem_init(&mem, arena, sizeof(arena));
+	opt.max_pixels = 0;
+	memset(&im, 0, sizeof(im));
+	r = img_decode(filebuf, n, &opt, &mem, &im);
+	if (r) {
+		printf("FAIL %s: %s\n", name, img_error_string(r));
+		free(ref);
+		return 1;
+	}
+	if (im.w != rw || im.h != rh) {
+		printf("FAIL %s: size mismatch\n", name);
+		free(ref);
+		return 1;
+	}
+	for (y = 0; y < (int)im.h; y++) {
+		for (x = 0; x < (int)im.w; x++) {
+			unsigned int px = im.px[y * im.w + x];
+			int rr = ((px >> 11) & 31) * 255 / 31;
+			int gg = ((px >> 5) & 63) * 255 / 63;
+			int bb = (px & 31) * 255 / 31;
+			unsigned char *p = ref + ((unsigned int)y * im.w + x) * 3;
+			int dr = abs(rr - p[0]);
+			int dg = abs(gg - p[1]);
+			int db = abs(bb - p[2]);
+
+			sum += (unsigned long long)dr + dg + db;
+			count += 3;
+			if ((unsigned int)dr > mx) mx = dr;
+			if ((unsigned int)dg > mx) mx = dg;
+			if ((unsigned int)db > mx) mx = db;
+		}
+	}
+	free(ref);
+	if (sum / count > 8 || mx > 130) {
+		printf("FAIL %s: mean %.2f max %u\n", name,
+		       (double)sum / (double)count, mx);
+		return 1;
+	}
+	return 0;
+}
+
+static void test_truncated(const char *name)
+{
+	char path[256];
+	unsigned int n, step, len;
+	struct img_mem mem;
+	struct img_options opt;
+	struct img_image im;
+	unsigned int i;
+
+	snprintf(path, sizeof(path), "testdata/images/%s", name);
+	if (read_file(path, filebuf, sizeof(filebuf), &n))
+		return;
+	step = n / 64;
+	if (!step)
+		step = 1;
+	for (len = 0; len < n; len += step) {
+		img_mem_init(&mem, arena, sizeof(arena));
+		opt.max_pixels = 0;
+		memset(&im, 0, sizeof(im));
+		(void)img_decode(filebuf, len, &opt, &mem, &im);
+	}
+	/* Deterministic mutations. */
+	for (i = 0; i < 400; i++) {
+		unsigned int seed = i * 1103515245u + 12345u;
+		unsigned int pos = seed % n;
+		unsigned char old = filebuf[pos];
+
+		filebuf[pos] ^= (unsigned char)(1u << (seed >> 16 & 7));
+		img_mem_init(&mem, arena, sizeof(arena));
+		memset(&im, 0, sizeof(im));
+		(void)img_decode(filebuf, n, &opt, &mem, &im);
+		filebuf[pos] = old;
+	}
+}
+
+static void test_inflate(void)
+{
+	static unsigned char raw[65536];
+	static unsigned char out[65536];
+	unsigned int n, rn, olen;
+	unsigned int ws[sizeof(struct inflate) / 4 + 8] __attribute__((aligned(16)));
+
+	if (read_file("testdata/images/inflate.raw", raw, sizeof(raw), &rn)) {
+		printf("FAIL inflate: raw read\n");
+		failures++;
+		return;
+	}
+	if (read_file("testdata/images/inflate.z", filebuf, sizeof(filebuf), &n) ||
+	    inflate_zlib_mem(filebuf, n, out, sizeof(out), &olen, ws) ||
+	    olen != rn || memcmp(out, raw, rn) != 0) {
+		printf("FAIL inflate: zlib\n");
+		failures++;
+	}
+	if (read_file("testdata/images/inflate.gz", filebuf, sizeof(filebuf), &n) ||
+	    inflate_gzip_mem(filebuf, n, out, sizeof(out), &olen, ws) ||
+	    olen != rn || memcmp(out, raw, rn) != 0) {
+		printf("FAIL inflate: gzip\n");
+		failures++;
+	}
+}
+
+static void test_blit(void)
+{
+	struct img_image im;
+	unsigned short px[4] = { 0xF800, 0x07E0, 0x001F, 0xFFFF };
+	unsigned char alpha[4] = { 255, 128, 255, 0 };
+	unsigned short dst[16 * 16];
+	struct img_blit b;
+	int i;
+
+	memset(&im, 0, sizeof(im));
+	im.w = 2;
+	im.h = 2;
+	im.px = px;
+	im.alpha = alpha;
+	im.format = IMG_FMT_PNG;
+	for (i = 0; i < 256; i++)
+		dst[i] = 0x1234;
+	memset(&b, 0, sizeof(b));
+	b.dst = dst;
+	b.dst_w = 16;
+	b.dst_h = 16;
+	b.clip_x = 0;
+	b.clip_y = 0;
+	b.clip_w = 16;
+	b.clip_h = 16;
+	b.x = 4;
+	b.y = 4;
+	b.scale = 2u << 16;   /* 2x2 -> 4x4 */
+	b.flags = IMG_BLIT_CHECKER;
+	img_draw(&im, &b);
+	img_draw(&im, &(struct img_blit){
+		.dst = dst, .dst_w = 16, .dst_h = 16,
+		.clip_x = 0, .clip_y = 0, .clip_w = 16, .clip_h = 16,
+		.x = -1, .y = -1, .scale = 1 << 16,
+		.flags = IMG_BLIT_FAST | IMG_BLIT_OVER_DST
+	});
+}
+
+static int test_unsupported(void)
+{
+	unsigned int n;
+	struct img_mem mem;
+	struct img_options opt;
+	struct img_image im;
+
+	if (read_file("testdata/images/prog.jpg", filebuf, sizeof(filebuf), &n))
+		return 1;
+	img_mem_init(&mem, arena, sizeof(arena));
+	opt.max_pixels = 0;
+	memset(&im, 0, sizeof(im));
+	if (img_decode(filebuf, n, &opt, &mem, &im) != IMG_ERR_UNSUPPORTED) {
+		printf("FAIL prog.jpg: not rejected\n");
+		return 1;
+	}
+	return 0;
+}
+
+int main(void)
+{
+	unsigned int i;
+
+	test_blit();
+	test_inflate();
+	if (test_unsupported())
+		failures++;
+	for (i = 0; i < IMG_EXP_COUNT; i++) {
+		if (test_lossless(&img_exp[i]))
+			failures++;
+		test_truncated(img_exp[i].path);
+	}
+	for (i = 0; i < IMG_JPEG_COUNT; i++) {
+		if (test_jpeg(img_jpeg[i]))
+			failures++;
+		test_truncated(img_jpeg[i]);
+	}
+	test_truncated("anim.gif");
+	if (failures) {
+		printf("%d image test(s) failed\n", failures);
+		return 1;
+	}
+	printf("all image tests passed\n");
+	return 0;
+}

+ 299 - 0
img_tga.c

@@ -0,0 +1,299 @@
+/* TGA: uncompressed and RLE truecolor, grayscale and colormapped images. */
+
+#include "img_internal.h"
+
+struct tga_hdr {
+	unsigned int idlen, cmap_type, type;
+	unsigned int cmap_first, cmap_len, cmap_bits;
+	unsigned int w, h, bpp, desc;
+	unsigned int data_off;
+	unsigned int pal_off;
+};
+
+static int tga_parse(const unsigned char *d, unsigned int n,
+		     struct tga_hdr *t)
+{
+	unsigned int cmap_bytes;
+
+	if (n < 18)
+		return -1;
+	t->idlen = d[0];
+	t->cmap_type = d[1];
+	t->type = d[2];
+	t->cmap_first = img_le16(d + 3);
+	t->cmap_len = img_le16(d + 5);
+	t->cmap_bits = d[7];
+	t->w = img_le16(d + 12);
+	t->h = img_le16(d + 14);
+	t->bpp = d[16];
+	t->desc = d[17];
+
+	if (t->type != 1 && t->type != 2 && t->type != 3 &&
+	    t->type != 9 && t->type != 10 && t->type != 11)
+		return -1;
+	if (t->w == 0 || t->h == 0 || t->w > 32768 || t->h > 32768)
+		return -1;
+	if (t->cmap_type != 0 && t->cmap_type != 1)
+		return -1;
+	if (t->type == 1 || t->type == 9) {
+		if (t->cmap_type != 1 || t->bpp != 8)
+			return -1;
+	} else if (t->type == 3 || t->type == 11) {
+		if (t->bpp != 8 && t->bpp != 16)
+			return -1;
+	} else {
+		if (t->bpp != 15 && t->bpp != 16 && t->bpp != 24 &&
+		    t->bpp != 32)
+			return -1;
+	}
+	if (t->cmap_type == 1) {
+		if (t->cmap_bits != 15 && t->cmap_bits != 16 &&
+		    t->cmap_bits != 24 && t->cmap_bits != 32)
+			return -1;
+		if (t->cmap_len == 0 || t->cmap_len > 256)
+			return -1;
+	}
+	cmap_bytes = t->cmap_len * ((t->cmap_bits + 7) / 8);
+	t->pal_off = 18 + t->idlen;
+	t->data_off = t->pal_off + cmap_bytes;
+	if (t->pal_off > n || t->data_off > n)
+		return -1;
+	if (t->type != 9 && t->type != 10 && t->type != 11) {
+		unsigned long long bytes = (unsigned long long)t->w * t->h *
+					   ((t->bpp + 7) / 8);
+		if (bytes > (unsigned long long)(n - t->data_off))
+			return -1;
+	}
+	return 0;
+}
+
+int img_sniff_tga(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	struct tga_hdr t;
+
+	if (tga_parse(d, n, &t))
+		return IMG_FMT_UNKNOWN;
+	out->format = IMG_FMT_TGA;
+	out->width = t.w;
+	out->height = t.h;
+	out->has_alpha = 0;
+	if ((t.type == 2 || t.type == 10) && t.bpp == 32 && (t.desc & 15))
+		out->has_alpha = 1;
+	if ((t.type == 2 || t.type == 10) && t.bpp == 16 && (t.desc & 15))
+		out->has_alpha = 1;
+	if ((t.type == 3 || t.type == 11) && t.bpp == 16)
+		out->has_alpha = 1;
+	if ((t.type == 1 || t.type == 9) && t.cmap_bits == 32 && (t.desc & 15))
+		out->has_alpha = 1;
+	return IMG_FMT_TGA;
+}
+
+struct tga_px {
+	unsigned int r, g, b, a;
+};
+
+static void tga_palette_entry(const unsigned char *p, unsigned int bits,
+			      struct tga_px *px)
+{
+	px->a = 255;
+	if (bits == 15 || bits == 16) {
+		unsigned int v = img_le16(p);
+		px->b = (v & 31) * 255 / 31;
+		px->g = ((v >> 5) & 31) * 255 / 31;
+		px->r = ((v >> 10) & 31) * 255 / 31;
+		if (bits == 16)
+			px->a = (v & 0x8000) ? 255 : 0;
+	} else if (bits == 24) {
+		px->b = p[0];
+		px->g = p[1];
+		px->r = p[2];
+	} else {
+		px->b = p[0];
+		px->g = p[1];
+		px->r = p[2];
+		px->a = p[3];
+	}
+}
+
+int img_decode_tga(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out)
+{
+	struct tga_hdr t;
+	struct tga_px pal[256];
+	unsigned int i, x = 0, y = 0, pos;
+	int rle, alpha, rcode;
+
+	if (tga_parse(d, n, &t))
+		return IMG_ERR_FORMAT;
+	if (!img_size_ok(t.w, t.h, opt))
+		return IMG_ERR_TOOBIG;
+	rle = (t.type == 9 || t.type == 10 || t.type == 11);
+	alpha = 0;
+	if ((t.type == 2 || t.type == 10) && t.bpp == 32 && (t.desc & 15))
+		alpha = 1;
+	if ((t.type == 2 || t.type == 10) && t.bpp == 16 && (t.desc & 15))
+		alpha = 1;
+	if ((t.type == 3 || t.type == 11) && t.bpp == 16)
+		alpha = 1;
+	if ((t.type == 1 || t.type == 9) && t.cmap_bits == 32 && (t.desc & 15))
+		alpha = 1;
+
+	for (i = 0; i < 256; i++) {
+		pal[i].r = pal[i].g = pal[i].b = 0;
+		pal[i].a = 255;
+	}
+	if (t.cmap_type == 1) {
+		unsigned int es = (t.cmap_bits + 7) / 8;
+
+		for (i = 0; i < t.cmap_len && i < 256; i++)
+			tga_palette_entry(d + t.pal_off + i * es, t.cmap_bits,
+					  &pal[i]);
+	}
+
+	rcode = img_alloc(m, t.w, t.h, IMG_FMT_TGA, alpha, out);
+	if (rcode)
+		return rcode;
+
+	pos = t.data_off;
+	while (y < t.h && x < t.w) {
+		unsigned int count = 1, rep = 0;
+
+		if (rle) {
+			unsigned int hdr;
+
+			if (pos >= n)
+				return IMG_ERR_CORRUPT;
+			hdr = d[pos++];
+			count = (hdr & 0x7F) + 1;
+			rep = (hdr & 0x80) != 0;
+		}
+		if (rep) {
+			struct tga_px px;
+			unsigned int k;
+
+			/* read one pixel */
+			if (t.type == 1 || t.type == 9) {
+				unsigned int idx;
+
+				if (pos >= n)
+					return IMG_ERR_CORRUPT;
+				idx = d[pos++];
+				idx = idx >= t.cmap_first ? idx - t.cmap_first : 0;
+				px = (idx >= 256) ? pal[0] : pal[idx];
+			} else if (t.type == 3 || t.type == 11) {
+				if (pos + (t.bpp == 16 ? 2 : 1) > n)
+					return IMG_ERR_CORRUPT;
+				px.r = px.g = px.b = d[pos++];
+				px.a = 255;
+				if (t.bpp == 16) {
+					px.a = d[pos++];
+					if (!alpha)
+						px.a = 255;
+				}
+			} else if (t.bpp == 15 || t.bpp == 16) {
+				unsigned int v;
+
+				if (pos + 2 > n)
+					return IMG_ERR_CORRUPT;
+				v = img_le16(d + pos);
+				pos += 2;
+				px.b = (v & 31) * 255 / 31;
+				px.g = ((v >> 5) & 31) * 255 / 31;
+				px.r = ((v >> 10) & 31) * 255 / 31;
+				px.a = (t.bpp == 16 && alpha && !(v & 0x8000)) ? 0 : 255;
+			} else if (t.bpp == 24) {
+				if (pos + 3 > n)
+					return IMG_ERR_CORRUPT;
+				px.b = d[pos++];
+				px.g = d[pos++];
+				px.r = d[pos++];
+				px.a = 255;
+			} else {
+				if (pos + 4 > n)
+					return IMG_ERR_CORRUPT;
+				px.b = d[pos++];
+				px.g = d[pos++];
+				px.r = d[pos++];
+				px.a = alpha ? d[pos] : 255;
+				pos++;
+			}
+			for (k = 0; k < count && y < t.h; k++) {
+				unsigned int ox = (t.desc & 0x10) ? t.w - 1 - x : x;
+				unsigned int oy = (t.desc & 0x20) ? y : t.h - 1 - y;
+				unsigned int oi = oy * t.w + ox;
+
+				out->px[oi] = img_rgb565(px.r, px.g, px.b);
+				if (out->alpha)
+					out->alpha[oi] = (unsigned char)px.a;
+				if (++x >= t.w) {
+					x = 0;
+					y++;
+				}
+			}
+		} else {
+			unsigned int k;
+
+			for (k = 0; k < count && y < t.h; k++) {
+				struct tga_px px;
+				unsigned int ox = (t.desc & 0x10) ? t.w - 1 - x : x;
+				unsigned int oy = (t.desc & 0x20) ? y : t.h - 1 - y;
+				unsigned int oi = oy * t.w + ox;
+
+				if (t.type == 1 || t.type == 9) {
+					unsigned int idx;
+
+					if (pos >= n)
+						return IMG_ERR_CORRUPT;
+					idx = d[pos++];
+					idx = idx >= t.cmap_first ? idx - t.cmap_first : 0;
+					px = (idx >= 256) ? pal[0] : pal[idx];
+				} else if (t.type == 3 || t.type == 11) {
+					if (pos + (t.bpp == 16 ? 2 : 1) > n)
+						return IMG_ERR_CORRUPT;
+					px.r = px.g = px.b = d[pos++];
+					px.a = 255;
+					if (t.bpp == 16) {
+						px.a = d[pos++];
+						if (!alpha)
+							px.a = 255;
+					}
+				} else if (t.bpp == 15 || t.bpp == 16) {
+					unsigned int v;
+
+					if (pos + 2 > n)
+						return IMG_ERR_CORRUPT;
+					v = img_le16(d + pos);
+					pos += 2;
+					px.b = (v & 31) * 255 / 31;
+					px.g = ((v >> 5) & 31) * 255 / 31;
+					px.r = ((v >> 10) & 31) * 255 / 31;
+					px.a = (t.bpp == 16 && alpha && !(v & 0x8000)) ? 0 : 255;
+				} else if (t.bpp == 24) {
+					if (pos + 3 > n)
+						return IMG_ERR_CORRUPT;
+					px.b = d[pos++];
+					px.g = d[pos++];
+					px.r = d[pos++];
+					px.a = 255;
+				} else {
+					if (pos + 4 > n)
+						return IMG_ERR_CORRUPT;
+					px.b = d[pos++];
+					px.g = d[pos++];
+					px.r = d[pos++];
+					px.a = alpha ? d[pos] : 255;
+					pos++;
+				}
+				out->px[oi] = img_rgb565(px.r, px.g, px.b);
+				if (out->alpha)
+					out->alpha[oi] = (unsigned char)px.a;
+				if (++x >= t.w) {
+					x = 0;
+					y++;
+				}
+			}
+		}
+	}
+	return y >= t.h ? 0 : IMG_ERR_CORRUPT;
+}

+ 659 - 0
inflate.c

@@ -0,0 +1,659 @@
+/* inflate: see inflate.h.  A compact, bounds-checked DEFLATE decoder.
+ *
+ * The Huffman decoder is the canonical-code bit-at-a-time form; the LZ77
+ * history is a 32 KB circular window that is also used as the output staging
+ * area, so the caller's sink is called in chunks (never per byte). */
+
+#include "inflate.h"
+
+#define MAXBITS   INFLATE_MAXBITS
+#define MAXLCODES 286
+#define MAXDCODES 30
+#define MAXCODES  (MAXLCODES + MAXDCODES)
+#define FIXLCODES 288
+#define FASTBITS  9
+
+static unsigned int crc_table[256];
+static int crc_table_ready;
+
+static void crc_table_init(void)
+{
+	unsigned int n, k, c;
+
+	if (crc_table_ready)
+		return;
+	for (n = 0; n < 256; n++) {
+		c = n;
+		for (k = 0; k < 8; k++)
+			c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
+		crc_table[n] = c;
+	}
+	crc_table_ready = 1;
+}
+
+static unsigned int crc_update(unsigned int crc, const unsigned char *p,
+			       unsigned int len)
+{
+	unsigned int i;
+
+	for (i = 0; i < len; i++)
+		crc ^= p[i], crc = (crc >> 8) ^ crc_table[crc & 0xFF];
+	return crc;
+}
+
+static void adler_update(unsigned int *a, unsigned int *b,
+			 const unsigned char *p, unsigned int len)
+{
+	unsigned int n;
+
+	while (len) {
+		n = len > 5552 ? 5552 : len;
+		len -= n;
+		while (n--) {
+			*a += *p++;
+			*b += *a;
+		}
+		*a %= 65521;
+		*b %= 65521;
+	}
+}
+
+unsigned int crc32_bytes(const void *data, unsigned int len)
+{
+	crc_table_init();
+	return crc_update(0xFFFFFFFFu, (const unsigned char *)data, len) ^
+	       0xFFFFFFFFu;
+}
+
+unsigned int adler32_bytes(const void *data, unsigned int len)
+{
+	unsigned int a = 1, b = 0;
+
+	adler_update(&a, &b, (const unsigned char *)data, len);
+	return (b << 16) | a;
+}
+
+/* ---- source ---------------------------------------------------------- */
+
+static int src_byte(struct inflate_src *s, unsigned int *out)
+{
+	while (s->len == 0) {
+		const unsigned char *p;
+		unsigned int len;
+
+		if (!s->more || !s->more(s->ctx, &p, &len) || len == 0)
+			return -1;
+		s->p = p;
+		s->len = len;
+	}
+	*out = *s->p++;
+	s->len--;
+	return 0;
+}
+
+/* ---- output ---------------------------------------------------------- */
+
+static int flush_out(struct inflate *z)
+{
+	unsigned int start, first, rest;
+	int r;
+
+	if (z->pending == 0)
+		return 0;
+	start = (z->wpos + 32768u - z->pending) & 32767u;
+	first = z->pending;
+	if (start + first > 32768u)
+		first = 32768u - start;
+	rest = z->pending - first;
+
+	z->crc = crc_update(z->crc, z->win + start, first);
+	adler_update(&z->adler_a, &z->adler_b, z->win + start, first);
+	if (rest) {
+		z->crc = crc_update(z->crc, z->win, rest);
+		adler_update(&z->adler_a, &z->adler_b, z->win, rest);
+	}
+
+	r = z->sink.write(z->sink.ctx, z->win + start, first);
+	if (!r && rest)
+		r = z->sink.write(z->sink.ctx, z->win, rest);
+	if (r)
+		return -1;
+	z->pending = 0;
+	return 0;
+}
+
+static int put_byte(struct inflate *z, unsigned int b)
+{
+	z->win[z->wpos] = (unsigned char)b;
+	z->wpos = (z->wpos + 1) & 32767u;
+	z->total++;
+	if (++z->pending >= 16384)
+		return flush_out(z);
+	return 0;
+}
+
+/* ---- bit reader ------------------------------------------------------ */
+
+static int need_bits(struct inflate *z, int n)
+{
+	while (z->bitcnt < n) {
+		unsigned int b;
+
+		if (src_byte(&z->src, &b))
+			return -1;
+		z->bitbuf |= b << z->bitcnt;
+		z->bitcnt += 8;
+	}
+	return 0;
+}
+
+static int get_bits(struct inflate *z, int n)
+{
+	unsigned int v;
+
+	if (n == 0)
+		return 0;
+	if (need_bits(z, n))
+		return -1;
+	v = z->bitbuf & ((1u << n) - 1u);
+	z->bitbuf >>= n;
+	z->bitcnt -= n;
+	z->total_bits += (unsigned int)n;
+	return (int)v;
+}
+
+static int align_byte(struct inflate *z)
+{
+	int pad = (int)((8u - (unsigned int)(z->total_bits & 7u)) & 7u);
+
+	if (pad && get_bits(z, pad) < 0)
+		return -1;
+	return 0;
+}
+
+/* ---- Huffman --------------------------------------------------------- */
+
+static int huff_build(struct inflate_huff *h, const unsigned char *lengths,
+		      int n)
+{
+	unsigned short offs[MAXBITS + 1];
+	int len, sym, left;
+
+	for (len = 0; len <= MAXBITS; len++)
+		h->count[len] = 0;
+	for (sym = 0; sym < n; sym++)
+		h->count[lengths[sym]]++;
+	if (h->count[0] == n)
+		return 0;       /* no codes: caller rejects if it needs one */
+
+	left = 1;
+	for (len = 1; len <= MAXBITS; len++) {
+		left <<= 1;
+		left -= h->count[len];
+		if (left < 0)
+			return -1;  /* over-subscribed */
+	}
+
+	offs[1] = 0;
+	for (len = 1; len < MAXBITS; len++)
+		offs[len + 1] = (unsigned short)(offs[len] + h->count[len]);
+	for (sym = 0; sym < n; sym++)
+		if (lengths[sym])
+			h->symbol[offs[lengths[sym]]++] = (unsigned short)sym;
+	return 1;
+}
+
+static int huff_decode(struct inflate *z, const struct inflate_huff *h)
+{
+	int len, code = 0, first = 0, index = 0;
+
+	for (len = 1; len <= MAXBITS; len++) {
+		int b = get_bits(z, 1);
+		int count;
+
+		if (b < 0)
+			return -1;
+		code |= b;
+		count = h->count[len];
+		if (code - count < first)
+			return h->symbol[index + (code - first)];
+		index += count;
+		first += count;
+		first <<= 1;
+		code <<= 1;
+	}
+	return -1;
+}
+
+/* ---- DEFLATE blocks -------------------------------------------------- */
+
+static const unsigned short len_base[29] = {
+	3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+	35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258
+};
+static const unsigned char len_ext[29] = {
+	0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+	3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0
+};
+static const unsigned short dist_base[30] = {
+	1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129,
+	193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097,
+	6145, 8193, 12289, 16385, 24577
+};
+static const unsigned char dist_ext[30] = {
+	0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
+	7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13
+};
+
+static int copy_match(struct inflate *z, unsigned int len, unsigned int dist)
+{
+	if (dist == 0 || dist > 32768u || len > 258u)
+		return -1;
+	while (len--) {
+		unsigned int src = (z->wpos + 32768u - dist) & 32767u;
+
+		if (put_byte(z, z->win[src]))
+			return -1;
+	}
+	return 0;
+}
+
+static int codes(struct inflate *z, const struct inflate_huff *lencode,
+		 const struct inflate_huff *distcode)
+{
+	for (;;) {
+		int sym = huff_decode(z, lencode);
+		int len, dsym, dist;
+
+		if (sym < 0)
+			return -1;
+		if (sym < 256) {
+			if (put_byte(z, (unsigned int)sym))
+				return -1;
+		} else if (sym == 256) {
+			return 0;
+		} else {
+			sym -= 257;
+			if (sym >= 29)
+				return -1;
+			len = len_base[sym];
+			if (len_ext[sym]) {
+				int e = get_bits(z, len_ext[sym]);
+
+				if (e < 0)
+					return -1;
+				len += e;
+			}
+			dsym = huff_decode(z, distcode);
+			if (dsym < 0 || dsym >= 30)
+				return -1;
+			dist = dist_base[dsym];
+			if (dist_ext[dsym]) {
+				int e = get_bits(z, dist_ext[dsym]);
+
+				if (e < 0)
+					return -1;
+				dist += e;
+			}
+			if (copy_match(z, (unsigned int)len, (unsigned int)dist))
+				return -1;
+		}
+	}
+}
+
+static int stored_block(struct inflate *z)
+{
+	int len, nlen, i;
+
+	len = get_bits(z, 16);
+	nlen = get_bits(z, 16);
+	if (len < 0 || nlen < 0 || (len ^ nlen) != 0xFFFF)
+		return -1;
+	for (i = 0; i < len; i++) {
+		int b = get_bits(z, 8);
+
+		if (b < 0 || put_byte(z, (unsigned int)b))
+			return -1;
+	}
+	return 0;
+}
+
+static int fixed_block(struct inflate *z)
+{
+	unsigned char lengths[FIXLCODES];
+	static const unsigned char dist_lengths[30] = {
+		5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
+		5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
+	};
+	struct inflate_huff lencode, distcode;
+	int i;
+
+	for (i = 0; i < 144; i++)
+		lengths[i] = 8;
+	for (; i < 256; i++)
+		lengths[i] = 9;
+	for (; i < 280; i++)
+		lengths[i] = 7;
+	for (; i < 288; i++)
+		lengths[i] = 8;
+	if (huff_build(&lencode, lengths, 288) < 0 ||
+	    huff_build(&distcode, dist_lengths, 30) < 0)
+		return -1;
+	return codes(z, &lencode, &distcode);
+}
+
+static int dynamic_block(struct inflate *z)
+{
+	static const unsigned char order[19] = {
+		16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
+	};
+	unsigned char lengths[MAXCODES];
+	struct inflate_huff lencode, distcode;
+	int hlit, hdist, hclen, i, total;
+
+	hlit = get_bits(z, 5);
+	hdist = get_bits(z, 5);
+	hclen = get_bits(z, 4);
+	if (hlit < 0 || hdist < 0 || hclen < 0)
+		return -1;
+	hlit += 257;
+	hdist += 1;
+	hclen += 4;
+	if (hlit > MAXLCODES || hdist > MAXDCODES)
+		return -1;
+
+	for (i = 0; i < 19; i++)
+		lengths[i] = 0;
+	for (i = 0; i < hclen; i++) {
+		int v = get_bits(z, 3);
+
+		if (v < 0)
+			return -1;
+		lengths[order[i]] = (unsigned char)v;
+	}
+	if (huff_build(&lencode, lengths, 19) < 0)
+		return -1;
+
+	total = hlit + hdist;
+	for (i = 0; i < total; ) {
+		int sym = huff_decode(z, &lencode);
+		int rep, val;
+
+		if (sym < 0)
+			return -1;
+		if (sym < 16) {
+			lengths[i++] = (unsigned char)sym;
+			continue;
+		}
+		if (sym == 16) {
+			if (i == 0)
+				return -1;
+			rep = get_bits(z, 2);
+			if (rep < 0)
+				return -1;
+			rep += 3;
+			val = lengths[i - 1];
+		} else if (sym == 17) {
+			rep = get_bits(z, 3);
+			if (rep < 0)
+				return -1;
+			rep += 3;
+			val = 0;
+		} else if (sym == 18) {
+			rep = get_bits(z, 7);
+			if (rep < 0)
+				return -1;
+			rep += 11;
+			val = 0;
+		} else {
+			return -1;
+		}
+		if (i + rep > total)
+			return -1;
+		while (rep--)
+			lengths[i++] = (unsigned char)val;
+	}
+
+	if (huff_build(&lencode, lengths, hlit) < 0)
+		return -1;
+	if (huff_build(&distcode, lengths + hlit, hdist) < 0)
+		return -1;
+	return codes(z, &lencode, &distcode);
+}
+
+void inflate_init(struct inflate *z, struct inflate_src *src,
+		  struct inflate_sink *sink)
+{
+	unsigned char *p = (unsigned char *)z;
+	unsigned int i;
+
+	crc_table_init();
+	for (i = 0; i < sizeof(*z); i++)
+		p[i] = 0;
+	z->src = *src;
+	z->sink = *sink;
+	z->crc = 0xFFFFFFFFu;
+	z->adler_a = 1;
+	z->adler_b = 0;
+}
+
+static int inflate_blocks(struct inflate *z)
+{
+	for (;;) {
+		int last = get_bits(z, 1);
+		int type = get_bits(z, 2);
+		int r;
+
+		if (last < 0 || type < 0)
+			return -1;
+		if (type == 0) {
+			if (align_byte(z))
+				return -1;
+			r = stored_block(z);
+		} else if (type == 1) {
+			r = fixed_block(z);
+		} else if (type == 2) {
+			r = dynamic_block(z);
+		} else {
+			return -1;
+		}
+		if (r)
+			return -1;
+		if (last)
+			break;
+	}
+	return flush_out(z);
+}
+
+int inflate_raw(struct inflate *z, unsigned int *out_len)
+{
+	if (inflate_blocks(z))
+		return -1;
+	if (out_len)
+		*out_len = (unsigned int)z->total;
+	return 0;
+}
+
+int inflate_zlib(struct inflate *z, unsigned int *out_len)
+{
+	unsigned int cmf, flg, want;
+	int i;
+
+	if (src_byte(&z->src, &cmf) || src_byte(&z->src, &flg))
+		return -1;
+	if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7)
+		return -1;
+	if (((cmf << 8) | flg) % 31 != 0)
+		return -1;
+	if (flg & 0x20)         /* preset dictionary: not supported */
+		return -1;
+
+	if (inflate_blocks(z))
+		return -1;
+	if (align_byte(z))
+		return -1;
+	want = 0;
+	for (i = 0; i < 4; i++) {
+		int b = get_bits(z, 8);
+
+		if (b < 0)
+			return -1;
+		want = (want << 8) | (unsigned int)b;   /* zlib is big-endian */
+	}
+	if (want != ((z->adler_b << 16) | z->adler_a))
+		return -1;
+	if (out_len)
+		*out_len = (unsigned int)z->total;
+	return 0;
+}
+
+int inflate_gzip(struct inflate *z, unsigned int *out_len)
+{
+	unsigned int id1, id2, cm, flg, b, skip, want_crc, want_size;
+	int i;
+
+	if (src_byte(&z->src, &id1) || src_byte(&z->src, &id2) ||
+	    src_byte(&z->src, &cm) || src_byte(&z->src, &flg))
+		return -1;
+	if (id1 != 0x1F || id2 != 0x8B || cm != 8)
+		return -1;
+	for (i = 0; i < 6; i++)       /* MTIME, XFL, OS */
+		if (src_byte(&z->src, &b))
+			return -1;
+	if (flg & 0x04) {             /* FEXTRA */
+		unsigned int lo, hi;
+
+		if (src_byte(&z->src, &lo) || src_byte(&z->src, &hi))
+			return -1;
+		skip = lo | (hi << 8);
+		while (skip--)
+			if (src_byte(&z->src, &b))
+				return -1;
+	}
+	if (flg & 0x08) {             /* FNAME */
+		do {
+			if (src_byte(&z->src, &b))
+				return -1;
+		} while (b);
+	}
+	if (flg & 0x10) {             /* FCOMMENT */
+		do {
+			if (src_byte(&z->src, &b))
+				return -1;
+		} while (b);
+	}
+	if (flg & 0x02) {             /* FHCRC */
+		if (src_byte(&z->src, &b) || src_byte(&z->src, &b))
+			return -1;
+	}
+
+	if (inflate_blocks(z))
+		return -1;
+	if (align_byte(z))
+		return -1;
+
+	/* The trailer: CRC32 then ISIZE, both little-endian. */
+	want_crc = 0;
+	for (i = 0; i < 4; i++) {
+		int v = get_bits(z, 8);
+
+		if (v < 0)
+			return -1;
+		want_crc |= (unsigned int)v << (8 * i);
+	}
+	want_size = 0;
+	for (i = 0; i < 4; i++) {
+		int v = get_bits(z, 8);
+
+		if (v < 0)
+			return -1;
+		want_size |= (unsigned int)v << (8 * i);
+	}
+	if ((want_crc ^ 0xFFFFFFFFu) != z->crc)
+		return -1;
+	if (want_size != (unsigned int)z->total)
+		return -1;
+	if (out_len)
+		*out_len = (unsigned int)z->total;
+	return 0;
+}
+
+/* ---- whole-buffer helpers ------------------------------------------- */
+
+struct mem_sink {
+	unsigned char *dst;
+	unsigned int cap, pos;
+};
+
+static int mem_write(void *ctx, const unsigned char *data, unsigned int len)
+{
+	struct mem_sink *m = (struct mem_sink *)ctx;
+
+	if (len > m->cap - m->pos)
+		return -1;
+	{
+		unsigned int i;
+
+		for (i = 0; i < len; i++)
+			m->dst[m->pos + i] = data[i];
+	}
+	m->pos += len;
+	return 0;
+}
+
+static int mem_inflate(const void *src, unsigned int len, void *dst,
+		       unsigned int cap, unsigned int *out_len, void *ws,
+		       int gzip)
+{
+	struct inflate *z = (struct inflate *)ws;
+	struct inflate_src s;
+	struct inflate_sink sink;
+	struct mem_sink m;
+
+	s.p = (const unsigned char *)src;
+	s.len = len;
+	s.more = 0;
+	s.ctx = 0;
+	m.dst = (unsigned char *)dst;
+	m.cap = cap;
+	m.pos = 0;
+	sink.write = mem_write;
+	sink.ctx = &m;
+	inflate_init(z, &s, &sink);
+	if (gzip ? inflate_gzip(z, out_len) : inflate_zlib(z, out_len))
+		return -1;
+	return 0;
+}
+
+int inflate_zlib_mem(const void *src, unsigned int len, void *dst,
+		     unsigned int cap, unsigned int *out_len, void *ws)
+{
+	return mem_inflate(src, len, dst, cap, out_len, ws, 0);
+}
+
+int inflate_gzip_mem(const void *src, unsigned int len, void *dst,
+		     unsigned int cap, unsigned int *out_len, void *ws)
+{
+	return mem_inflate(src, len, dst, cap, out_len, ws, 1);
+}
+
+int inflate_raw_mem(const void *src, unsigned int len, void *dst,
+		    unsigned int cap, unsigned int *out_len, void *ws)
+{
+	struct inflate *z = (struct inflate *)ws;
+	struct inflate_src s;
+	struct inflate_sink sink;
+	struct mem_sink m;
+
+	s.p = (const unsigned char *)src;
+	s.len = len;
+	s.more = 0;
+	s.ctx = 0;
+	m.dst = (unsigned char *)dst;
+	m.cap = cap;
+	m.pos = 0;
+	sink.write = mem_write;
+	sink.ctx = &m;
+	inflate_init(z, &s, &sink);
+	return inflate_raw(z, out_len);
+}

+ 75 - 0
inflate.h

@@ -0,0 +1,75 @@
+/* inflate: freestanding DEFLATE / zlib / gzip decoder.
+ *
+ * No libc, no allocation: the caller provides the workspace (struct inflate,
+ * about 33 KB) and an output sink.  The compressed input is a sequence of
+ * memory segments, so a PNG decoder can feed consecutive IDAT chunks without
+ * copying them.
+ *
+ * Used by the image library (PNG) and by the kernel's compressed command pack
+ * (gzip).  See img_png.c and ramfs.c. */
+#ifndef INFLATE_H
+#define INFLATE_H
+
+#define INFLATE_MAXBITS 15
+
+struct inflate_src {
+	const unsigned char *p;
+	unsigned int len;
+	/* Called when p/len are exhausted: return 1 and set a new segment,
+	 * or 0 at the end of the input. */
+	int (*more)(void *ctx, const unsigned char **p, unsigned int *len);
+	void *ctx;
+};
+
+struct inflate_sink {
+	int (*write)(void *ctx, const unsigned char *data, unsigned int len);
+	void *ctx;
+};
+
+struct inflate_huff {
+	unsigned short count[INFLATE_MAXBITS + 1];
+	unsigned short symbol[288];
+};
+
+struct inflate {
+	struct inflate_src src;
+	struct inflate_sink sink;
+
+	unsigned int bitbuf;
+	int bitcnt;
+	unsigned long long total_bits;
+
+	unsigned char win[32768];   /* LZ77 history / pending output */
+	unsigned int wpos;
+	unsigned int pending;
+
+	unsigned long long total;   /* bytes produced */
+	unsigned int crc;           /* running CRC32 (pre-inverted) */
+	unsigned int adler_a, adler_b;
+};
+
+void inflate_init(struct inflate *z, struct inflate_src *src,
+		  struct inflate_sink *sink);
+
+/* Raw DEFLATE stream from the current source position. */
+int inflate_raw(struct inflate *z, unsigned int *out_len);
+
+/* zlib stream (2-byte header, DEFLATE, Adler-32). */
+int inflate_zlib(struct inflate *z, unsigned int *out_len);
+
+/* gzip stream (10+ byte header, DEFLATE, CRC32 + ISIZE). */
+int inflate_gzip(struct inflate *z, unsigned int *out_len);
+
+/* Entire in-memory helpers.  `ws` must point at sizeof(struct inflate) bytes
+ * with at least 16-byte alignment.  Return 0 on success. */
+int inflate_zlib_mem(const void *src, unsigned int len, void *dst,
+		     unsigned int cap, unsigned int *out_len, void *ws);
+int inflate_gzip_mem(const void *src, unsigned int len, void *dst,
+		     unsigned int cap, unsigned int *out_len, void *ws);
+int inflate_raw_mem(const void *src, unsigned int len, void *dst,
+		    unsigned int cap, unsigned int *out_len, void *ws);
+
+unsigned int crc32_bytes(const void *data, unsigned int len);
+unsigned int adler32_bytes(const void *data, unsigned int len);
+
+#endif

+ 11 - 6
kernel.c

@@ -282,16 +282,21 @@ void kernel_main(void)
 	vfs_mount_all();
 	/* The command pack: read-only, mounted at /ramfs (see ramfs.c). */
 	{
-		extern unsigned char _binary_cmds_pack_start[];
-		extern unsigned char _binary_cmds_pack_end[];
-		unsigned int pack_len = (unsigned int)(_binary_cmds_pack_end -
-						       _binary_cmds_pack_start);
-		if (ramfs_init(_binary_cmds_pack_start, pack_len) != 0)
+		extern unsigned char _binary_cmds_pack_gz_bin_start[];
+		extern unsigned char _binary_cmds_pack_gz_bin_end[];
+		unsigned int pack_len =
+			(unsigned int)(_binary_cmds_pack_gz_bin_end -
+				       _binary_cmds_pack_gz_bin_start);
+		if (ramfs_init(_binary_cmds_pack_gz_bin_start, pack_len) != 0)
 			serial_puts(SERIAL_COM1, "ramfs: bad pack\n");
 		else {
 			serial_puts(SERIAL_COM1, "ramfs: pack ok, ");
 			serial_putdec(SERIAL_COM1, ramfs_count());
-			serial_puts(SERIAL_COM1, " files\n");
+			serial_puts(SERIAL_COM1, " files, ");
+			serial_putdec(SERIAL_COM1, pack_len);
+			serial_puts(SERIAL_COM1, " -> ");
+			serial_putdec(SERIAL_COM1, ramfs_pack_size());
+			serial_puts(SERIAL_COM1, " bytes\n");
 			vfs_mount_ramfs();
 		}
 	}

+ 7 - 2
ngui.c

@@ -242,9 +242,9 @@ int ngui_begin(struct ngui *ui)
 	return want;
 }
 
-void ngui_end(struct ngui *ui)
+void ngui_end_ex(struct ngui *ui, int present)
 {
-	if (u_win_present() != 0)
+	if (present && u_win_present() != 0)
 		ui->dirty = 1;
 
 	if (ui->clicked && !ui->focus_claimed)
@@ -259,6 +259,11 @@ void ngui_end(struct ngui *ui)
 	ui->release_x = ui->release_y = 0;
 }
 
+void ngui_end(struct ngui *ui)
+{
+	ngui_end_ex(ui, 1);
+}
+
 struct ngui_rect ngui_cut_top(struct ngui_rect *r, int h)
 {
 	struct ngui_rect out = *r;

+ 3 - 0
ngui.h

@@ -125,6 +125,9 @@ struct ngui {
 void ngui_init(struct ngui *ui, unsigned short *fb, int w, int h);
 int  ngui_begin(struct ngui *ui);       /* 1 = app should redraw */
 void ngui_end(struct ngui *ui);
+/* Same bookkeeping, but only publish the canvas when `present` is nonzero.
+ * Lets an app poll input without copying an unchanged frame every loop. */
+void ngui_end_ex(struct ngui *ui, int present);
 void ngui_invalidate(struct ngui *ui);
 void ngui_set_focus(struct ngui *ui, unsigned int id);
 unsigned int ngui_focus(struct ngui *ui);

+ 3 - 1
process.c

@@ -16,6 +16,7 @@
 #include "smp.h"
 #include "sys_fs.h"
 #include "sys_gfx.h"
+#include "sys_mem.h"
 #include "sys_net.h"
 #include "syscall.h"
 #include "timer.h"
@@ -665,6 +666,7 @@ void process_reap_dead(void)
 				USER_BASE, USER_STACK_TOP - USER_BASE, 1);
 			paging_release_user_range(p->cr3,
 				USER_GFX_BASE, USER_GFX_RANGE, 0);
+			sys_mem_release(p);
 			/* WM surface mappings: page tables only; the shadow/
 			 * terminal/canvas pages belong to the window server. */
 			paging_release_user_range(p->cr3,
@@ -819,7 +821,7 @@ int process_procinfo(unsigned int index, struct sys_procinfo *out)
 		out->life_ticks = life ? life : 1;
 		/* Kernel stack page + page directory + user pages (the WM shares
 		 * the kernel directory; counting one is close enough). */
-		out->pages      = 2 + count_user_pages(p->cr3);
+		out->pages      = 2 + count_user_pages(p->cr3) + p->heap_pages;
 		out->weight     = p->weight;
 		out->cpu        = p->on_cpu;
 		name_copy(out->name, p->name);

+ 5 - 0
process.h

@@ -43,6 +43,7 @@ struct process {
 	struct text_screen *screen;  /* output target for io_putchar & co. */
 	unsigned int stack_base;     /* page to free on exit, or 0 (bootstrap/fallback) */
 	unsigned int cr3;            /* physical address of this process's page dir */
+	unsigned int heap_pages;     /* pages mapped at USER_HEAP_BASE, or 0 */
 	unsigned int kstack_top;     /* ring-0 stack top (for TSS esp0) */
 	unsigned int wake_ms;        /* tick deadline when PROC_SLEEPING */
 	char cwd[PROC_CWD_MAX];      /* working directory (ring-3 commands) */
@@ -90,6 +91,10 @@ struct process {
  * gfx session owns those. */
 #define USER_GFX_BASE    0x50000000
 #define USER_GFX_RANGE   0x00400000   /* one 4 MB slot */
+/* Anonymous per-process heap (SYS_MEM_ALLOC/GROW/FREE): one growable arena
+ * above the WM mappings.  Freed by the reaper. */
+#define USER_HEAP_BASE   0x60000000u
+#define USER_HEAP_MAX    (32u * 1024u * 1024u)
 
 /* Stable, sparse process table (see process.c). */
 extern struct process *procs[PROC_MAX];

+ 63 - 1
ramfs.c

@@ -6,9 +6,12 @@
  */
 
 #include "ramfs.h"
+#include "inflate.h"
 #include "mm.h"
 #include "serial.h"
 
+#define RAMFS_MAX_DECOMPRESSED (8u * 1024u * 1024u)
+
 struct ramfs_hdr {
 	char magic[8];
 	unsigned int count;
@@ -129,8 +132,67 @@ static const struct ramfs_hdr *ramfs_validate(const void *pack, unsigned int siz
 
 int ramfs_init(const void *pack, unsigned int size)
 {
-	const struct ramfs_hdr *h = ramfs_validate(pack, size);
+	const struct ramfs_hdr *h;
+	const unsigned char *p = (const unsigned char *)pack;
+
+	/* The embedded pack is gzip-compressed (the same inflate code that the
+	 * PNG decoder uses); a raw pack is still accepted, which is what the
+	 * cmds-dev path passes to ramfs_replace(). */
+	if (size >= 18 && p[0] == 0x1F && p[1] == 0x8B) {
+		unsigned int isize = (unsigned int)p[size - 4] |
+				     ((unsigned int)p[size - 3] << 8) |
+				     ((unsigned int)p[size - 2] << 16) |
+				     ((unsigned int)p[size - 1] << 24);
+		unsigned int pages, wpages, olen = 0;
+		unsigned char *out, *ws;
+
+		if (isize == 0 || isize > RAMFS_MAX_DECOMPRESSED)
+			return -1;
+		pages = (isize + 0xFFF) >> 12;
+		wpages = (sizeof(struct inflate) + 0xFFF) >> 12;
+		out = (unsigned char *)mm_alloc_pages(pages);
+		if (!out)
+			return -1;
+		ws = (unsigned char *)mm_alloc_pages(wpages);
+		if (!ws) {
+			unsigned int i;
+
+			for (i = 0; i < pages; i++)
+				mm_free_page((unsigned int)out + i * 0x1000);
+			return -1;
+		}
+		if (inflate_gzip_mem(pack, size, out, isize, &olen, ws) != 0 ||
+		    olen != isize) {
+			unsigned int i;
+
+			for (i = 0; i < pages; i++)
+				mm_free_page((unsigned int)out + i * 0x1000);
+			for (i = 0; i < wpages; i++)
+				mm_free_page((unsigned int)ws + i * 0x1000);
+			return -1;
+		}
+		{
+			unsigned int i;
+
+			for (i = 0; i < wpages; i++)
+				mm_free_page((unsigned int)ws + i * 0x1000);
+		}
+		h = ramfs_validate(out, isize);
+		if (!h) {
+			unsigned int i;
+
+			for (i = 0; i < pages; i++)
+				mm_free_page((unsigned int)out + i * 0x1000);
+			return -1;
+		}
+		pack_base = out;
+		pack_size = isize;
+		pack_hdr = h;
+		pack_pages = pages;
+		return 0;
+	}
 
+	h = ramfs_validate(pack, size);
 	if (!h)
 		return -1;
 	pack_base = (const unsigned char *)pack;

+ 107 - 0
sys_mem.c

@@ -0,0 +1,107 @@
+/* Per-process user heap: see sys_mem.h. */
+
+#include "sys_mem.h"
+#include "mm.h"
+#include "paging.h"
+#include "process.h"
+
+static void invlpg_va(unsigned int va)
+{
+	__asm__ volatile ("invlpg (%0)" : : "r"(va) : "memory");
+}
+
+static void zero_page(unsigned int phys)
+{
+	unsigned int *p = (unsigned int *)phys;
+	unsigned int i;
+
+	for (i = 0; i < PAGE_SIZE / 4; i++)
+		p[i] = 0;
+}
+
+/* Map new pages [from, to) of the arena.  On failure release only the pages
+ * mapped by this call; the caller's existing arena is untouched. */
+static int map_pages(struct process *p, unsigned int from, unsigned int to)
+{
+	unsigned int i;
+
+	for (i = from; i < to; i++) {
+		unsigned int phys = mm_alloc_page();
+		unsigned int va = USER_HEAP_BASE + i * PAGE_SIZE;
+
+		if (!phys)
+			break;
+		zero_page(phys);
+		if (!paging_map_page(p->cr3, va, phys,
+				     PTE_USER | PTE_WRITABLE | PTE_PRESENT)) {
+			mm_free_page(phys);
+			break;
+		}
+		invlpg_va(va);
+	}
+	if (i < to) {
+		if (i > from)
+			paging_release_user_range(p->cr3,
+						  USER_HEAP_BASE + from * PAGE_SIZE,
+						  (i - from) * PAGE_SIZE, 1);
+		return -1;
+	}
+	return 0;
+}
+
+int sys_mem_alloc(unsigned int bytes)
+{
+	struct process *p = current_proc();
+	unsigned int pages;
+
+	if (!p || !p->cr3 || bytes == 0 || p->heap_pages != 0)
+		return -1;
+	if (bytes > USER_HEAP_MAX)
+		return -1;
+	pages = (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
+	if (pages == 0 || pages > USER_HEAP_MAX / PAGE_SIZE)
+		return -1;
+	if (map_pages(p, 0, pages))
+		return -1;
+	p->heap_pages = pages;
+	return (int)USER_HEAP_BASE;
+}
+
+int sys_mem_grow(unsigned int bytes)
+{
+	struct process *p = current_proc();
+	unsigned int pages;
+
+	if (!p || !p->cr3 || bytes == 0 || bytes > USER_HEAP_MAX)
+		return -1;
+	pages = (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
+	if (pages <= p->heap_pages)
+		return 0;              /* shrinking is deliberately unsupported */
+	if (pages > USER_HEAP_MAX / PAGE_SIZE)
+		return -1;
+	if (map_pages(p, p->heap_pages, pages))
+		return -1;
+	p->heap_pages = pages;
+	return 0;
+}
+
+int sys_mem_free(void)
+{
+	struct process *p = current_proc();
+
+	if (!p || !p->cr3 || !p->heap_pages)
+		return -1;
+	paging_release_user_range(p->cr3, USER_HEAP_BASE,
+				  p->heap_pages * PAGE_SIZE, 1);
+	p->heap_pages = 0;
+	return 0;
+}
+
+void sys_mem_release(struct process *p)
+{
+	if (!p || !p->cr3 || !p->heap_pages)
+		return;
+	paging_release_user_range(p->cr3, USER_HEAP_BASE,
+				  p->heap_pages * PAGE_SIZE, 1);
+	p->heap_pages = 0;
+}

+ 17 - 0
sys_mem.h

@@ -0,0 +1,17 @@
+/* Per-process anonymous heap (SYS_MEM_ALLOC/GROW/FREE).
+ *
+ * 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. */
+#ifndef SYS_MEM_H
+#define SYS_MEM_H
+
+struct process;
+
+int sys_mem_alloc(unsigned int bytes);
+int sys_mem_grow(unsigned int bytes);
+int sys_mem_free(void);
+void sys_mem_release(struct process *p);
+
+#endif

+ 7 - 0
syscall.c

@@ -9,6 +9,7 @@
 #include "sys_fs.h"
 #include "sys_gfx.h"
 #include "sys_info.h"
+#include "sys_mem.h"
 #include "sys_net.h"
 #include "sys_wm.h"
 #include "terminal.h"
@@ -243,6 +244,12 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		return sys_win_pointer((struct win_pointer *)a1);
 	case SYS_WIN_EVENT:
 		return sys_win_event((struct win_event *)a1);
+	case SYS_MEM_ALLOC:
+		return sys_mem_alloc((unsigned int)a1);
+	case SYS_MEM_GROW:
+		return sys_mem_grow((unsigned int)a1);
+	case SYS_MEM_FREE:
+		return sys_mem_free();
 	case SYS_WIN_KEY_WAIT:
 		return sys_win_key_wait((unsigned int)a1);
 	case SYS_SCHEDINFO:

+ 7 - 0
syscall.h

@@ -109,6 +109,13 @@
 #define SYS_WIN_POINTER    86  /* (struct win_pointer *out) -> 0/-1 */
 #define SYS_WIN_EVENT      87  /* (struct win_event *out) -> 1 event, 0 none */
 
+/* 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. */
+#define SYS_MEM_ALLOC      88  /* (unsigned bytes) -> VA or <0 */
+#define SYS_MEM_GROW       89  /* (unsigned total_bytes) -> 0/-1 */
+#define SYS_MEM_FREE       90  /* () -> 0/-1 */
+
 /* Terminal / process services used by the ring-3 shell. */
 #define SYS_TTY_CREATE     73  /* () -> tty id 1..TTY_MAX / -1 */
 #define SYS_TTY_READ       74  /* (id, buf, max) -> bytes / 0 / -1 */

BIN
testdata/images/anim.gif


Разница между файлами не показана из-за своего большого размера
+ 3 - 0
testdata/images/ascii.ppm


BIN
testdata/images/bw.bmp


BIN
testdata/images/bw.pbm


BIN
testdata/images/bw.png


+ 44 - 0
testdata/images/expected.h

@@ -0,0 +1,44 @@
+/* Generated by tools/gen_img_tests.py. */
+static const struct img_exp {
+	const char *path;
+	unsigned int w, h;
+	unsigned int hash;
+	int alpha;
+} img_exp[] = {
+	{ "anim.gif", 97, 61, 0xc1cef470u, 1 },
+	{ "ascii.ppm", 97, 61, 0xcba8344eu, 0 },
+	{ "bw.bmp", 97, 61, 0x9e9c1161u, 0 },
+	{ "bw.pbm", 97, 61, 0x9e9c1161u, 0 },
+	{ "bw.png", 97, 61, 0x9e9c1161u, 0 },
+	{ "gray.pgm", 97, 61, 0xea937d55u, 0 },
+	{ "gray.png", 97, 61, 0xea937d55u, 0 },
+	{ "gray16.png", 97, 61, 0x054b5854u, 0 },
+	{ "gray_inter.png", 97, 61, 0xea937d55u, 0 },
+	{ "inter.gif", 97, 61, 0x1458d06eu, 0 },
+	{ "pal.bmp", 97, 61, 0x1458d06eu, 0 },
+	{ "pal.png", 97, 61, 0xc1cef470u, 1 },
+	{ "pal4.png", 97, 61, 0xa802a287u, 0 },
+	{ "plain.gif", 97, 61, 0x1458d06eu, 0 },
+	{ "rgb.bmp", 97, 61, 0xcba8344eu, 0 },
+	{ "rgb.png", 97, 61, 0xcba8344eu, 0 },
+	{ "rgb.ppm", 97, 61, 0xcba8344eu, 0 },
+	{ "rgb.tga", 97, 61, 0xcba8344eu, 0 },
+	{ "rgb_inter.png", 97, 61, 0xcba8344eu, 0 },
+	{ "rgba.bmp", 97, 61, 0xcba8344eu, 0 },
+	{ "rgba.png", 97, 61, 0xaebae43eu, 1 },
+	{ "rgba.tga", 97, 61, 0xaebae43eu, 1 },
+	{ "rgba_inter.png", 97, 61, 0xaebae43eu, 1 },
+	{ "rle.tga", 97, 61, 0xcba8344eu, 0 },
+	{ "rle8.bmp", 97, 61, 0x732c2d74u, 0 },
+	{ "topdown.bmp", 97, 61, 0xcba8344eu, 0 },
+	{ "trans.gif", 97, 61, 0xaa93ddb2u, 1 },
+};
+#define IMG_EXP_COUNT (sizeof(img_exp) / sizeof(img_exp[0]))
+static const char *const img_jpeg[] = {
+	"j444.jpg",
+	"j422.jpg",
+	"j420.jpg",
+	"jgray.jpg",
+	"jrst.jpg",
+};
+#define IMG_JPEG_COUNT (sizeof(img_jpeg) / sizeof(img_jpeg[0]))

BIN
testdata/images/gray.pgm


BIN
testdata/images/gray.png


BIN
testdata/images/gray16.png


BIN
testdata/images/gray_inter.png


BIN
testdata/images/inflate.gz


+ 581 - 0
testdata/images/inflate.raw

@@ -0,0 +1,581 @@
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+the quick brown fox jumps over the lazy dog
+	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����	
+
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€亗儎厗噲墛媽崕彁憭摂晼棙櫄洔潪煚、¥ウЖ┆���辈炒刀犯购患骄坷谅媚牌侨墒颂臀闲岩釉罩棕仝圮蒉哙徕沅彐玷殛腱眍镳耱篝貊鼬����

BIN
testdata/images/inflate.z


BIN
testdata/images/inter.gif


BIN
testdata/images/j420.jpg


BIN
testdata/images/j422.jpg


BIN
testdata/images/j444.jpg


BIN
testdata/images/jgray.jpg


BIN
testdata/images/jrst.jpg


BIN
testdata/images/pal.bmp


BIN
testdata/images/pal.png


BIN
testdata/images/pal4.png


BIN
testdata/images/plain.gif


BIN
testdata/images/prog.jpg


BIN
testdata/images/ref/j420.jpg.ppm


BIN
testdata/images/ref/j422.jpg.ppm


BIN
testdata/images/ref/j444.jpg.ppm


BIN
testdata/images/ref/jgray.jpg.ppm


BIN
testdata/images/ref/jrst.jpg.ppm


BIN
testdata/images/rgb.bmp


BIN
testdata/images/rgb.png


BIN
testdata/images/rgb.ppm


BIN
testdata/images/rgb.tga


BIN
testdata/images/rgb_inter.png


BIN
testdata/images/rgba.bmp


BIN
testdata/images/rgba.png


BIN
testdata/images/rgba.tga


BIN
testdata/images/rgba_inter.png


BIN
testdata/images/rle.tga


BIN
testdata/images/rle8.bmp


BIN
testdata/images/topdown.bmp


BIN
testdata/images/trans.gif


+ 178 - 0
tools/gen_img_tests.py

@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""Generate the image-library host test corpus (development only).
+
+The generated images and expected hashes are committed; `make test-images`
+does not need PIL.  Run this script after changing the decoder or corpus.
+"""
+import gzip
+import os
+import struct
+import zlib
+from PIL import Image, ImageDraw
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+OUT = os.path.join(ROOT, "testdata", "images")
+
+def fnv(im, alpha=False):
+    h = 2166136261
+    for r, g, b, a in im.convert("RGBA").getdata():
+        # RGB under a fully transparent pixel is not meaningful.
+        if not alpha or a != 0:
+            px = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)
+            h = ((h ^ (px & 255)) * 16777619) & 0xffffffff
+            h = ((h ^ ((px >> 8) & 255)) * 16777619) & 0xffffffff
+        if alpha:
+            h = ((h ^ a) * 16777619) & 0xffffffff
+    return h
+
+def main():
+    os.makedirs(os.path.join(OUT, "ref"), exist_ok=True)
+    w, h = 97, 61
+    rgb = Image.new("RGB", (w, h))
+    p = rgb.load()
+    for y in range(h):
+        for x in range(w):
+            p[x, y] = ((x * 3 + y * 7) % 256, (x * 5) % 256, (y * 11) % 256)
+    rgba = rgb.convert("RGBA")
+    q = rgba.load()
+    for y in range(h):
+        for x in range(w):
+            q[x, y] = (q[x, y][0], q[x, y][1], q[x, y][2], (x * 9) % 256)
+    gray = rgb.convert("L")
+    bw = rgb.convert("1")
+    pal = Image.new("P", (w, h))
+    pal.putpalette([i % 256 for i in range(768)])
+    pp = pal.load()
+    for y in range(h):
+        for x in range(w):
+            pp[x, y] = (x + y) % 16
+    pal16 = pal.copy()
+    pal_inter = pal.copy()
+    rgb_inter = rgb.copy()
+    rgba_inter = rgba.copy()
+    gray_inter = gray.copy()
+
+    files = {}
+    def save(im, name, alpha=False, **kw):
+        im.save(os.path.join(OUT, name), **kw)
+        files[name] = (im, alpha)
+
+    save(rgb, "rgb.png")
+    save(rgba, "rgba.png", True)
+    save(gray, "gray.png")
+    save(bw, "bw.png")
+    save(pal, "pal.png", True, transparency=5)
+    files["pal.png"] = (Image.open(os.path.join(OUT, "pal.png")).convert("RGBA"), True)
+    save(pal16, "pal4.png")
+    save(rgb_inter, "rgb_inter.png", interlace=1)
+    save(rgba_inter, "rgba_inter.png", True, interlace=1)
+    save(gray_inter, "gray_inter.png", interlace=1)
+    # 16-bit grayscale: values are multiples of 257, so high byte is the
+    # 8-bit gradient.  Expected hash comes from the 8-bit image.
+    g16 = Image.new("I;16", (w, h))
+    g8 = Image.new("L", (w, h))
+    gg = g16.load()
+    g8p = g8.load()
+    for y in range(h):
+        for x in range(w):
+            v = (x * 3 + y * 7) % 256
+            gg[x, y] = v * 257
+            g8p[x, y] = v
+    g16.save(os.path.join(OUT, "gray16.png"))
+    files["gray16.png"] = (g8, False)
+
+    save(rgb, "rgb.bmp")
+    if os.path.exists(os.path.join(OUT, "rle8.bmp")):
+        files["rle8.bmp"] = (Image.open(os.path.join(OUT, "rle8.bmp")).convert("RGB"), False)
+    # Top-down BMP: reverse the stored rows and make the DIB height negative.
+    src = open(os.path.join(OUT, "rgb.bmp"), "rb").read()
+    off = struct.unpack_from("<I", src, 10)[0]
+    bpp = struct.unpack_from("<H", src, 28)[0]
+    hh = struct.unpack_from("<i", src, 22)[0]
+    stride = ((w * bpp + 31) // 32) * 4
+    out = bytearray(src[:off])
+    for yy in range(hh - 1, -1, -1):
+        out += src[off + yy * stride:off + (yy + 1) * stride]
+    struct.pack_into("<i", out, 22, -hh)
+    open(os.path.join(OUT, "topdown.bmp"), "wb").write(out)
+    files["topdown.bmp"] = (rgb, False)
+    save(bw, "bw.bmp")
+    save(rgb.convert("P", palette=Image.ADAPTIVE, colors=256), "pal.bmp")
+    rgb32 = rgba.copy()
+    rgb32.save(os.path.join(OUT, "rgba.bmp"))
+    files["rgba.bmp"] = (rgb32, False)   # BI_RGB alpha is ignored
+    save(rgb, "rgb.tga")
+    rgb.save(os.path.join(OUT, "rle.tga"), compression="tga_rle")
+    files["rle.tga"] = (rgb, False)
+    rgba.save(os.path.join(OUT, "rgba.tga"))
+    files["rgba.tga"] = (rgba, True)
+    save(rgb, "rgb.ppm")
+    save(gray, "gray.pgm")
+    save(bw, "bw.pbm")
+    with open(os.path.join(OUT, "ascii.ppm"), "w") as f:
+        f.write("P3\n%d %d\n255\n" % (w, h))
+        for y in range(h):
+            for x in range(w):
+                f.write("%d %d %d " % p[x, y])
+    files["ascii.ppm"] = (rgb, False)
+
+    gif_src = rgb.convert("P", palette=Image.ADAPTIVE, colors=256)
+    save(gif_src, "plain.gif")
+    save(gif_src, "inter.gif", interlace=True)
+    gif_src.save(os.path.join(OUT, "trans.gif"), transparency=5)
+    files["trans.gif"] = (Image.open(os.path.join(OUT, "trans.gif")).convert("RGBA"), True)
+    # Our decoder shows the first frame; PIL's first frame matches this source.
+    frames = [pal.copy()]
+    p2 = pal.copy()
+    for y in range(h):
+        for x in range(w):
+            p2.putpixel((x, y), (x + y + 3) % 16)
+    frames.append(p2)
+    pal.save(os.path.join(OUT, "anim.gif"), save_all=True,
+             append_images=frames[1:], duration=100, loop=0, transparency=5)
+    files["anim.gif"] = (Image.open(os.path.join(OUT, "anim.gif")).convert("RGBA"), True)
+
+    jpegs = []
+    for name, kw in [("j444.jpg", dict(quality=90, subsampling=0)),
+                     ("j422.jpg", dict(quality=90, subsampling=1)),
+                     ("j420.jpg", dict(quality=90, subsampling=2)),
+                     ("jgray.jpg", None)]:
+        src = gray if kw is None else rgb
+        src.save(os.path.join(OUT, name), **(kw or {"quality": 90}))
+        ref = src.convert("RGB")
+        ref.save(os.path.join(OUT, "ref", name + ".ppm"))
+        jpegs.append(name)
+    rgb.save(os.path.join(OUT, "jrst.jpg"), quality=90, restart_marker_blocks=2)
+    rgb.save(os.path.join(OUT, "ref", "jrst.jpg.ppm"))
+    jpegs.append("jrst.jpg")
+    rgb.save(os.path.join(OUT, "prog.jpg"), quality=90, progressive=True)
+
+    # inflate vectors
+    raw = (b"the quick brown fox jumps over the lazy dog\n" * 500) + bytes(range(256)) * 80
+    open(os.path.join(OUT, "inflate.raw"), "wb").write(raw)
+    open(os.path.join(OUT, "inflate.z"), "wb").write(zlib.compress(raw, 9))
+    open(os.path.join(OUT, "inflate.gz"), "wb").write(gzip.compress(raw, 9))
+
+    exp = []
+    for name, (im, alpha) in files.items():
+        exp.append((name, im.width, im.height, fnv(im, alpha), 1 if alpha else 0))
+    with open(os.path.join(OUT, "expected.h"), "w") as f:
+        f.write("/* Generated by tools/gen_img_tests.py. */\n")
+        f.write("static const struct img_exp {\n"
+                "\tconst char *path;\n"
+                "\tunsigned int w, h;\n"
+                "\tunsigned int hash;\n"
+                "\tint alpha;\n"
+                "} img_exp[] = {\n")
+        for name, ww, hh, hhsh, aa in sorted(exp):
+            f.write("\t{ \"%s\", %d, %d, 0x%08xu, %d },\n" % (name, ww, hh, hhsh, aa))
+        f.write("};\n")
+        f.write("#define IMG_EXP_COUNT (sizeof(img_exp) / sizeof(img_exp[0]))\n")
+        f.write("static const char *const img_jpeg[] = {\n")
+        for name in jpegs:
+            f.write("\t\"%s\",\n" % name)
+        f.write("};\n")
+        f.write("#define IMG_JPEG_COUNT (sizeof(img_jpeg) / sizeof(img_jpeg[0]))\n")
+
+if __name__ == "__main__":
+    main()

+ 41 - 0
ucmd_files.c

@@ -6,6 +6,7 @@
 
 #include "ucmd_lib.h"
 #include "ngui.h"
+#include "img.h"
 
 #define FM_PATH_MAX     128
 #define FM_MAX_ENTRIES  256
@@ -153,6 +154,33 @@ static int is_root(const char *p)
 	return p && p[0] == '/' && p[1] == '\0';
 }
 
+static int ext_is(const char *name, const char *ext)
+{
+	unsigned int n = s_len(name), e = s_len(ext), i;
+
+	if (n < e)
+		return 0;
+	for (i = 0; i < e; i++) {
+		unsigned char a = (unsigned char)name[n - e + i];
+		unsigned char b = (unsigned char)ext[i];
+
+		if (a >= 'A' && a <= 'Z')
+			a = (unsigned char)(a + 32);
+		if (a != b)
+			return 0;
+	}
+	return 1;
+}
+
+static int is_image_name(const char *name)
+{
+	return ext_is(name, ".png") || ext_is(name, ".jpg") ||
+	       ext_is(name, ".jpeg") || ext_is(name, ".gif") ||
+	       ext_is(name, ".bmp") || ext_is(name, ".tga") ||
+	       ext_is(name, ".ppm") || ext_is(name, ".pgm") ||
+	       ext_is(name, ".pbm");
+}
+
 static void path_join(const char *dir, const char *name, char *out,
 		      unsigned int cap)
 {
@@ -499,6 +527,19 @@ static void open_selected(void)
 		load_path(path);
 		return;
 	}
+	if (is_image_name(e->name)) {
+		if (e->size > IMG_FILE_MAX) {
+			set_status("Image is larger than 4 MB", 1);
+			return;
+		}
+		path_join(cwd, e->name, path, sizeof(path));
+		pid = u_spawn("/ramfs/bin/view", path, 0, cwd);
+		if (pid <= 0)
+			set_status("Cannot launch the viewer", 1);
+		else
+			set_status("Opened in the viewer", 0);
+		return;
+	}
 	if (e->size > FM_EDIT_MAX) {
 		set_status("File too large for the editor", 1);
 		return;

+ 18 - 0
ucmd_lib.h

@@ -387,4 +387,22 @@ static inline int u_schedinfo(struct sys_schedinfo *out)
 	return u_syscall1(SYS_SCHEDINFO, (int)out);
 }
 
+/* Per-process anonymous heap: one growable arena, freed at exit. */
+static inline void *u_mem_alloc(unsigned int bytes)
+{
+	int r = u_syscall1(SYS_MEM_ALLOC, (int)bytes);
+
+	return r < 0 ? 0 : (void *)r;
+}
+
+static inline int u_mem_grow(unsigned int bytes)
+{
+	return u_syscall1(SYS_MEM_GROW, (int)bytes);
+}
+
+static inline int u_mem_free(void)
+{
+	return u_syscall0(SYS_MEM_FREE);
+}
+
 #endif

+ 648 - 0
ucmd_view.c

@@ -0,0 +1,648 @@
+/* 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. */
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+#include "img.h"
+#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
+#define VIEW_BAR_H      (VIEW_TOOLBAR_H + VIEW_STATUS_H)
+
+#define VIEW_ID_FIT    1
+#define VIEW_ID_ONE    2
+#define VIEW_ID_OUT    3
+#define VIEW_ID_IN     4
+
+#define VIEW_BG        NGUI_RGB(24, 26, 32)
+#define VIEW_VIEW_BG   NGUI_RGB(16, 17, 21)
+#define VIEW_CHK1      NGUI_RGB(46, 48, 54)
+#define VIEW_CHK2      NGUI_RGB(58, 60, 67)
+
+struct viewer {
+	struct ngui ui;
+	struct img_image img;
+	struct img_mem mem;
+	unsigned char *heap;
+	unsigned int heap_size;
+
+	unsigned int file_size;
+	unsigned int iw, ih;
+	unsigned int format;
+	unsigned int zoom;          /* 16.16 when fit == 0 */
+	int fit;
+	int off_x, off_y;           /* destination top-left inside the viewport */
+	int dragging;
+	int drag_x, drag_y;
+	int have_img;
+	int loading;
+	int error;
+	int last_w, last_h;
+	char err[64];
+	char name[20];
+	char title[20];
+	int dirty;
+};
+
+static struct viewer v;
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
+{
+	while (s && *s && *n + 1 < cap)
+		d[(*n)++] = *s++;
+	d[*n] = '\0';
+}
+
+static void s_append_uint(char *d, unsigned int *n, unsigned int v,
+			  unsigned int cap)
+{
+	char tmp[12];
+	unsigned int i = 0, j;
+
+	do {
+		tmp[i++] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v && i < sizeof(tmp));
+	for (j = 0; j < i && *n + 1 < cap; j++)
+		d[(*n)++] = tmp[i - 1 - j];
+	d[*n] = '\0';
+}
+
+static void base_name(const char *path, char *out, unsigned int cap)
+{
+	unsigned int n = 0, i, start = 0;
+
+	if (!path)
+		path = "";
+	for (i = 0; path[i]; i++)
+		if (path[i] == '/')
+			start = i + 1;
+	for (i = start; path[i] && n + 1 < cap; i++)
+		out[n++] = path[i];
+	out[n] = '\0';
+	if (!n)
+		s_copy(out, "image", cap);
+}
+
+struct ngui_rect view_body(struct ngui *ui)
+{
+	struct ngui_rect r = {0, 0, ui->w, ui->h};
+	struct ngui_rect top, bottom;
+
+	top = ngui_cut_top(&r, ui->h >= 140 ? VIEW_TOOLBAR_H : 22);
+	bottom = ngui_cut_bottom(&r, ui->h >= 140 ? VIEW_STATUS_H : 14);
+	(void)top;
+	(void)bottom;
+	return r;
+}
+
+static unsigned int view_scale(struct ngui *ui)
+{
+	struct ngui_rect b = view_body(ui);
+	unsigned int s;
+
+	if (!v.have_img || b.w <= 0 || b.h <= 0)
+		return 65536;
+	if (!v.fit)
+		return v.zoom ? v.zoom : 65536;
+	s = img_fit_scale(v.iw, v.ih, (unsigned int)b.w, (unsigned int)b.h);
+	if (s > 65536)
+		s = 65536;              /* don't enlarge a smaller image */
+	return s ? s : 256;
+}
+
+static void clamp_view(struct ngui *ui, unsigned int scale)
+{
+	struct ngui_rect b = view_body(ui);
+	unsigned int sw, sh;
+
+	if (!v.have_img) {
+		v.off_x = v.off_y = 0;
+		return;
+	}
+	sw = (unsigned int)(((unsigned long long)v.iw * scale) >> 16);
+	sh = (unsigned int)(((unsigned long long)v.ih * scale) >> 16);
+	if (sw < 1) sw = 1;
+	if (sh < 1) sh = 1;
+	if (sw <= (unsigned int)b.w)
+		v.off_x = ((int)b.w - (int)sw) / 2;
+	else {
+		if (v.off_x > 0) v.off_x = 0;
+		if (v.off_x < (int)b.w - (int)sw)
+			v.off_x = (int)b.w - (int)sw;
+	}
+	if (sh <= (unsigned int)b.h)
+		v.off_y = ((int)b.h - (int)sh) / 2;
+	else {
+		if (v.off_y > 0) v.off_y = 0;
+		if (v.off_y < (int)b.h - (int)sh)
+			v.off_y = (int)b.h - (int)sh;
+	}
+	if (v.fit) {
+		v.off_x = ((int)b.w - (int)sw) / 2;
+		v.off_y = ((int)b.h - (int)sh) / 2;
+	}
+}
+
+static void view_set_scale(struct ngui *ui, unsigned int scale)
+{
+	struct ngui_rect b = view_body(ui);
+	unsigned int old = view_scale(ui);
+	unsigned int sx, sy;
+	int dx, dy;
+
+	if (!v.have_img || b.w <= 0 || b.h <= 0)
+		return;
+	if (scale < 256) scale = 256;
+	if (scale > 8u * 65536u) scale = 8u * 65536u;
+	dx = b.w / 2 - v.off_x;
+	dy = b.h / 2 - v.off_y;
+	sx = ((unsigned int)dx << 16) / old;
+	sy = ((unsigned int)dy << 16) / old;
+	v.fit = 0;
+	v.zoom = scale;
+	v.off_x = (int)(b.w / 2 - (int)(((unsigned long long)sx * scale) >> 16));
+	v.off_y = (int)(b.h / 2 - (int)(((unsigned long long)sy * scale) >> 16));
+	clamp_view(ui, scale);
+}
+
+static void view_fit(void)
+{
+	v.fit = 1;
+}
+
+static void view_one(struct ngui *ui)
+{
+	struct ngui_rect b = view_body(ui);
+	unsigned int sw;
+
+	v.fit = 0;
+	v.zoom = 65536;
+	sw = v.iw;
+	v.off_x = ((int)b.w - (int)sw) / 2;
+	v.off_y = ((int)b.h - (int)v.ih) / 2;
+	clamp_view(ui, v.zoom);
+}
+
+static void view_zoom_step(struct ngui *ui, int in)
+{
+	unsigned int s = view_scale(ui);
+
+	if (in)
+		s = s + s / 4;
+	else
+		s = s - s / 5;
+	view_set_scale(ui, s);
+}
+
+static void format_status(char *buf, unsigned int cap)
+{
+	unsigned int n = 0;
+
+	buf[0] = '\0';
+	if (v.have_img) {
+		unsigned int scale = view_scale(&v.ui);
+
+		s_append(buf, &n, img_format_name(v.format), cap);
+		s_append(buf, &n, "  ", cap);
+		s_append_uint(buf, &n, v.iw, cap);
+		s_append(buf, &n, "x", cap);
+		s_append_uint(buf, &n, v.ih, cap);
+		s_append(buf, &n, "  ", cap);
+		if (v.file_size >= 1024 * 1024) {
+			s_append_uint(buf, &n, v.file_size / (1024 * 1024), cap);
+			s_append(buf, &n, " MB", cap);
+		} else {
+			s_append_uint(buf, &n, (v.file_size + 1023) / 1024, cap);
+			s_append(buf, &n, " KB", cap);
+		}
+		s_append(buf, &n, "  ", cap);
+		if (v.fit)
+			s_append(buf, &n, "fit ", cap);
+		s_append_uint(buf, &n, (scale * 100u) >> 16, cap);
+		s_append(buf, &n, "%", cap);
+	} else {
+		s_append(buf, &n, "view  ", cap);
+		s_append(buf, &n, v.name, cap);
+	}
+}
+
+static void draw_message(struct ngui *ui, struct ngui_rect body,
+			 const char *msg)
+{
+	int tw = (int)ngui_text_width(msg);
+	int x = body.x + (body.w - tw) / 2;
+	int y = body.y + body.h / 2 - 8;
+
+	if (x < body.x + 6)
+		x = body.x + 6;
+	ngui_text(ui, x, y, msg, ui->theme.text);
+	if (!v.loading) {
+		const char *hint = "Esc closes";
+		int hw = (int)ngui_text_width(hint);
+
+		ngui_text(ui, body.x + (body.w - hw) / 2, y + 24, hint,
+			  ui->theme.text_dim);
+	}
+}
+
+static void draw_toolbar(struct ngui *ui, struct ngui_rect r)
+{
+	struct ngui_rect b;
+	int x = r.x + 6;
+	int by = r.y + (r.h - 20) / 2;
+	int bw;
+
+	ngui_fill_rect(ui, r, ui->theme.panel);
+	ngui_fill_rect(ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
+		       ui->theme.border);
+
+	bw = 40;
+	b = (struct ngui_rect){x, by, bw, 20};
+	if (ngui_button(ui, VIEW_ID_FIT, b, "Fit")) {
+		view_fit();
+		v.dirty = 1;
+	}
+	x += bw + 5;
+	b = (struct ngui_rect){x, by, 40, 20};
+	if (ngui_button(ui, VIEW_ID_ONE, b, "1:1")) {
+		view_one(ui);
+		v.dirty = 1;
+	}
+	x += 45;
+	b = (struct ngui_rect){x, by, 24, 20};
+	if (ngui_button(ui, VIEW_ID_OUT, b, "-")) {
+		view_zoom_step(ui, 0);
+		v.dirty = 1;
+	}
+	x += 29;
+	b = (struct ngui_rect){x, by, 24, 20};
+	if (ngui_button(ui, VIEW_ID_IN, b, "+")) {
+		view_zoom_step(ui, 1);
+		v.dirty = 1;
+	}
+	x += 32;
+	if (v.have_img && x + 70 < r.x + r.w) {
+		char z[16];
+		unsigned int n = 0;
+
+		z[0] = '\0';
+		s_append_uint(z, &n, (view_scale(ui) * 100u) >> 16, sizeof(z));
+		s_append(z, &n, "%", sizeof(z));
+		ngui_text(ui, x, r.y + (r.h - 16) / 2, z, ui->theme.text_dim);
+	}
+}
+
+static void draw(struct ngui *ui)
+{
+	struct ngui_rect all = {0, 0, ui->w, ui->h};
+	struct ngui_rect r = all;
+	struct ngui_rect toolbar, status, body;
+	char line[96];
+
+	toolbar = ngui_cut_top(&r, ui->h >= 140 ? VIEW_TOOLBAR_H : 22);
+	status = ngui_cut_bottom(&r, ui->h >= 140 ? VIEW_STATUS_H : 14);
+	body = r;
+
+	ngui_fill_rect(ui, all, VIEW_BG);
+	draw_toolbar(ui, toolbar);
+	ngui_fill_rect(ui, status, ui->theme.panel);
+	format_status(line, sizeof(line));
+	ngui_text_ellipsis(ui, status, status.x + 6,
+			   status.y + (status.h - 16) / 2, line,
+			   ui->theme.text_dim);
+
+	if (body.w <= 0 || body.h <= 0)
+		return;
+
+	ngui_fill_rect(ui, body, VIEW_VIEW_BG);
+
+	if (!v.have_img) {
+		if (v.error)
+			draw_message(ui, body, v.err);
+		else {
+			char msg[48];
+
+			s_copy(msg, "Loading ", sizeof(msg));
+			{
+				unsigned int n = s_len(msg);
+
+				s_append(msg, &n, v.name, sizeof(msg));
+				s_append(msg, &n, "...", sizeof(msg));
+			}
+			draw_message(ui, body, msg);
+		}
+		return;
+	}
+
+	{
+		unsigned int scale = view_scale(ui);
+		unsigned int sw =
+			(unsigned int)(((unsigned long long)v.iw * scale) >> 16);
+		unsigned int sh =
+			(unsigned int)(((unsigned long long)v.ih * scale) >> 16);
+		struct img_blit blit;
+
+		if (!sw) sw = 1;
+		if (!sh) sh = 1;
+		clamp_view(ui, scale);
+		blit.dst = ui->px;
+		blit.dst_w = ui->w;
+		blit.dst_h = ui->h;
+		blit.clip_x = body.x;
+		blit.clip_y = body.y;
+		blit.clip_w = body.w;
+		blit.clip_h = body.h;
+		blit.x = body.x + v.off_x;
+		blit.y = body.y + v.off_y;
+		blit.scale = scale;
+		blit.bg = VIEW_CHK1;
+		blit.bg2 = VIEW_CHK2;
+		blit.flags = IMG_BLIT_CHECKER;
+		if (v.dragging)
+			blit.flags |= IMG_BLIT_FAST;
+		if (v.img.alpha)
+			img_draw(&v.img, &blit);
+		else {
+			blit.flags &= ~IMG_BLIT_CHECKER;
+			img_draw(&v.img, &blit);
+		}
+		(void)sw;
+		(void)sh;
+	}
+}
+
+static int create_window(unsigned int base_w, unsigned int base_h,
+			 const char *title, struct win_info *wi)
+{
+	unsigned int w = base_w, h = base_h;
+
+	if (w < 320) w = 320;
+	if (h < 200) h = 200;
+	if (w > 960) w = 960;
+	if (h > 640) h = 640;
+	for (;;) {
+		if (u_win_create(w, h + VIEW_BAR_H, title, wi) == 0)
+			return 0;
+		if (w <= 240 && h <= 160)
+			break;
+		w = w * 4 / 5;
+		h = h * 4 / 5;
+		if (w < 240) w = 240;
+		if (h < 160) h = 160;
+	}
+	return -1;
+}
+
+static void error_exit(const char *msg)
+{
+	struct win_info wi;
+	struct ngui ui;
+	int quit = 0;
+
+	if (u_win_create(480, 240 + VIEW_BAR_H, "view", &wi) != 0) {
+		u_puts("view: ");
+		u_puts(msg);
+		u_puts("\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	v.error = 1;
+	s_copy(v.err, msg, sizeof(v.err));
+	v.have_img = 0;
+	for (;;) {
+		if (!ngui_begin(&ui)) {
+			u_sleep_ms(10);
+			continue;
+		}
+		{
+			int k = ngui_key(&ui);
+
+			if (k == NGUI_KEY_ESC || k == 'q' || k == 0x03)
+				quit = 1;
+		}
+		draw(&ui);
+		ngui_end(&ui);
+		if (quit)
+			break;
+		u_sleep_ms(10);
+	}
+	u_win_close();
+	u_exit(1);
+}
+
+void _start(const char *arg)
+{
+	struct img_info info;
+	struct win_info wi;
+	struct img_options opt;
+	unsigned int n, arena_off, heap_size;
+	int r;
+
+	if (!arg || !arg[0]) {
+		u_puts("usage: view <file>\n");
+		u_exit(1);
+	}
+	base_name(arg, v.name, sizeof(v.name));
+	s_copy(v.title, "view ", sizeof(v.title));
+	{
+		unsigned int tn = s_len(v.title);
+
+		s_append(v.title, &tn, v.name, sizeof(v.title));
+	}
+
+	v.heap = (unsigned char *)u_mem_alloc(VIEW_INIT_HEAP);
+	if (!v.heap)
+		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);
+	if ((int)n < 0) {
+		if ((int)n == IMG_ERR_TOOBIG)
+			error_exit("Image file is larger than 4 MB");
+		error_exit(img_error_string((int)n));
+	}
+	v.file_size = n;
+
+	r = img_sniff(v.heap, 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)
+		error_exit("Not enough memory for the image");
+	img_mem_init(&v.mem, v.heap + arena_off, heap_size - arena_off);
+	v.iw = info.width;
+	v.ih = info.height;
+	v.format = info.format;
+
+	if (create_window(info.width, info.height, v.title, &wi) != 0) {
+		u_puts("view: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&v.ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	v.fit = 1;
+	v.zoom = 65536;
+	v.loading = 1;
+	v.dirty = 1;
+	v.last_w = (int)wi.width;
+	v.last_h = (int)wi.height;
+	{
+		struct ngui *ui = &v.ui;
+
+		/* Draw the loading frame once; the input loop starts after decode. */
+		ngui_begin(ui);
+		draw(ui);
+		ngui_end(ui);
+	}
+
+	opt.max_pixels = 0;
+	r = img_decode(v.heap, n, &opt, &v.mem, &v.img);
+	v.loading = 0;
+	if (r != 0) {
+		s_copy(v.err, img_error_string(r), sizeof(v.err));
+		v.error = 1;
+		v.have_img = 0;
+	} else {
+		v.have_img = 1;
+		v.error = 0;
+		v.iw = v.img.w;
+		v.ih = v.img.h;
+		v.format = v.img.format;
+		v.fit = 1;
+	}
+	v.dirty = 1;
+
+	for (;;) {
+		struct ngui *ui = &v.ui;
+		struct ngui_rect body = view_body(ui);
+		int close = 0;
+		int k;
+
+		ngui_begin(ui);
+		if (ui->w != v.last_w || ui->h != v.last_h) {
+			/* size changed; redraw at the new dimensions */
+			v.last_w = ui->w;
+			v.last_h = ui->h;
+			v.dirty = 1;
+		}
+
+		while ((k = ngui_key(ui)) != 0) {
+			if (k == NGUI_KEY_ESC || k == 'q' || k == 0x03) {
+				close = 1;
+				break;
+			} else if (k == 'f' || k == '0') {
+				view_fit();
+				v.dirty = 1;
+			} else if (k == '1') {
+				view_one(ui);
+				v.dirty = 1;
+			} else if (k == '+' || k == '=') {
+				view_zoom_step(ui, 1);
+				v.dirty = 1;
+			} else if (k == '-' || k == '_') {
+				view_zoom_step(ui, 0);
+				v.dirty = 1;
+			} else if (k == NGUI_KEY_LEFT || k == NGUI_KEY_RIGHT ||
+				   k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
+				if (v.have_img) {
+					if (v.fit)
+						view_set_scale(ui, view_scale(ui));
+					if (k == NGUI_KEY_LEFT)
+						v.off_x += 32;
+					if (k == NGUI_KEY_RIGHT)
+						v.off_x -= 32;
+					if (k == NGUI_KEY_UP)
+						v.off_y += 32;
+					if (k == NGUI_KEY_DOWN)
+						v.off_y -= 32;
+					clamp_view(ui, view_scale(ui));
+					v.dirty = 1;
+				}
+			}
+		}
+		if (close)
+			break;
+
+		if (ui->pressed && ui->press_x >= body.x && ui->press_y >= body.y &&
+		    ui->press_x < body.x + body.w && ui->press_y < body.y + body.h &&
+		    v.have_img) {
+			v.dragging = 1;
+			v.drag_x = ui->mouse_x;
+			v.drag_y = ui->mouse_y;
+			v.dirty = 1;
+		}
+		if (v.dragging) {
+			if (!(ui->buttons & 1) || ui->released) {
+				v.dragging = 0;
+				v.dirty = 1;
+			} else {
+				int dx = ui->mouse_x - v.drag_x;
+				int dy = ui->mouse_y - v.drag_y;
+
+				if (dx || dy) {
+					v.off_x += dx;
+					v.off_y += dy;
+					v.drag_x = ui->mouse_x;
+					v.drag_y = ui->mouse_y;
+					clamp_view(ui, view_scale(ui));
+					v.dirty = 1;
+				}
+			}
+		}
+		if (ui->pressed || ui->released)
+			v.dirty = 1;
+
+		if (v.dirty) {
+			v.dirty = 0;
+			draw(ui);
+			ngui_end_ex(ui, 1);
+		} else {
+			ngui_end_ex(ui, 0);
+		}
+		u_sleep_ms(10);
+	}
+	u_win_close();
+	u_exit(0);
+}

Некоторые файлы не были показаны из-за большого количества измененных файлов