RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Wallpapers: decode in-process, never through GdkPixbuf
oxydizerb675254fccd3
diff --git a/AGENTS.md b/AGENTS.mdindex d184f06..6389bdc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -302,6 +302,16 @@ panel painting. The key rules:hand-declare the ABI. No runtime `parseColor()` in comptime defaults.* `std.os.linux.*` return `-errno` in `usize` (`std.os.linux.errno`);`std.posix.system.*` are libc (`std.posix.errno`).+* **The compositor never calls GdkPixbuf.** Current gdk-pixbuf starts a+ sandboxed glycin loader process per decode. Wallpapers (the loader, the+ Appearance strip, the desktop's own) decode in-process through+ `wallpaper_codec.c` (libjpeg, libpng, libwebp; `png.zig` stays the fast path+ for plain PNGs): PNG, JPEG and still WebP only, chosen by content, EXIF+ orientation ignored, at most 16384 px per edge and 100 Mpx. `nm -D+ --undefined-only` on `rediwm` must show no `gdk_pixbuf_*`;+ `python3 tests/wallpaper_codec.py` checks that and every variant against+ Pillow (`--sanitize` adds ASan/UBSan). The Files and Images apps still fall+ back to GdkPixbuf for formats their codecs lack (`files/AGENTS.md`).* **wlroots bindings** live in `src/wlr/`, backed by one translation ofthe installed headers (`src/wlr/c.h`, module `wlr_c`); read `src/wlr/AGENTS.md` before extending them.`ext.*`/`wp.*` Wayland types need their protocol in `build/protocols.zig`.diff --git a/build.zig b/build.zigindex 78e4365..b4ddfe8 100644--- a/build.zig+++ b/build.zig@@ -199,6 +199,7 @@ pub fn build(b: *std.Build) void {compositor.root_module.linkSystemLibrary("libinput", .{});compositor.root_module.linkSystemLibrary("libudev", .{});compositor.root_module.linkSystemLibrary("png16", .{});+ support.addWallpaperCodec(b, compositor.root_module);// PipeWire's PulseAudio-compat client library — see src/audio/pipewire.zig.compositor.root_module.linkSystemLibrary("libpulse", .{});addBass(b, compositor.root_module);diff --git a/build/support.zig b/build/support.zigindex 5af96a6..bfb4972 100644--- a/build/support.zig+++ b/build/support.zig@@ -110,6 +110,14 @@ pub fn addThumbCodec(b: *std.Build, module: *std.Build.Module) void {inline for (.{ "libjpeg", "libpng16" }) |lib| module.linkSystemLibrary(lib, .{});}+// Wallpapers decode in-process too (src/wallpaper_codec.c): the compositor never+// calls GdkPixbuf, which would start a sandboxed glycin loader per image.+pub fn addWallpaperCodec(b: *std.Build, module: *std.Build.Module) void {+ module.addCSourceFile(.{ .file = b.path("src/wallpaper_codec.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });+ module.addImport("c_wallpaper_codec", cHeader(b, module.resolved_target.?, module.optimize.?, b.path("src/wallpaper_codec.h"), &.{}));+ inline for (.{ "libjpeg", "libpng16", "libwebp" }) |lib| module.linkSystemLibrary(lib, .{});+}+// Pinned, Files-only emulator. No dependency on the compositor or distro ABI.pub fn addFilesTerminal(b: *std.Build, module: *std.Build.Module, for_tests: bool) void {const vterm = b.dependency("vterm", .{});diff --git a/build/tests.zig b/build/tests.zigindex d4e09f5..2362020 100644--- a/build/tests.zig+++ b/build/tests.zig@@ -71,6 +71,7 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {ui_tests_module.linkSystemLibrary("libinput", .{});ui_tests_module.linkSystemLibrary("libudev", .{});ui_tests_module.linkSystemLibrary("png16", .{});+ support.addWallpaperCodec(b, ui_tests_module);ui_tests_module.linkSystemLibrary("libpulse", .{});inline for (.{ .{ "c_pulse", ctx.c.pulse }, .{ "c_libinput", ctx.c.libinput }, .{ "c_png", ctx.c.png } }) |entry| ui_tests_module.addImport(entry[0], entry[1]);ui_tests_module.linkSystemLibrary("xcb", .{});@@ -160,6 +161,10 @@ pub fn addZig(ctx: Context, session: Session) ZigTests {printers_direct.addFileArg(b.path("tests/printers_direct.py"));printers_direct.step.dependOn(&printers_integration.step);printers_step.dependOn(&printers_direct.step);+ const wallpaper_codec_check = b.addSystemCommand(&.{"python3"});+ wallpaper_codec_check.addFileArg(b.path("tests/wallpaper_codec.py"));+ wallpaper_codec_check.step.dependOn(b.getInstallStep());+ b.step("test-wallpaper-codec", "Test the native wallpaper decoder against Pillow and hand-written PNGs").dependOn(&wallpaper_codec_check.step);// Dependency-module tests are not collected by the executable's test root.const shared_ui_tests = b.addTest(.{ .root_module = ui_mod });const shared_config_tests = b.addTest(.{ .root_module = config_mod });diff --git a/src/desktop/wallpaper.zig b/src/desktop/wallpaper.zigindex 40af6cf..c6a705b 100644--- a/src/desktop/wallpaper.zig+++ b/src/desktop/wallpaper.zig@@ -1,40 +1,18 @@-//! GdkPixbuf is already in librsvg's link closure. Keep GLib headers out of translate-c.+//! The desktop's own wallpaper, decoded by the shared native codec (never+//! GdkPixbuf, which starts a sandboxed loader process per image) and drawn+//! with Cairo.const std = @import("std");const c = @import("c.zig").api;-const Pixbuf = opaque {};-const GError = opaque {};-extern fn gdk_pixbuf_new_from_file([*:0]const u8, ?*?*GError) ?*Pixbuf;-extern fn gdk_pixbuf_get_width(*Pixbuf) c_int;-extern fn gdk_pixbuf_get_height(*Pixbuf) c_int;-extern fn gdk_pixbuf_get_rowstride(*Pixbuf) c_int;-extern fn gdk_pixbuf_get_n_channels(*Pixbuf) c_int;-extern fn gdk_pixbuf_get_pixels(*Pixbuf) [*]const u8;-extern fn g_object_unref(*anyopaque) void;-extern fn g_error_free(*GError) void;+const codec = @import("../wallpaper_codec.zig");pub const Mode = enum { fill, fit, stretch, center, tile };pub const Image = struct { pixels: []u32, w: i32, h: i32, mode: Mode };-pub fn load(a: std.mem.Allocator, path: []const u8, mode: Mode) !Image {- const z = try a.dupeSentinel(u8, path, 0);- defer a.free(z);- var err: ?*GError = null;- const pixbuf = gdk_pixbuf_new_from_file(z, &err) orelse {- if (err) |e| g_error_free(e);- return error.DecodeFailed;- };- defer g_object_unref(pixbuf);- const w = gdk_pixbuf_get_width(pixbuf);- const h = gdk_pixbuf_get_height(pixbuf);- const stride = gdk_pixbuf_get_rowstride(pixbuf);- const channels = gdk_pixbuf_get_n_channels(pixbuf);- if (w <= 0 or h <= 0 or w > 16384 or h > 16384 or (channels != 3 and channels != 4)) return error.InvalidImage;- const pixels = try a.alloc(u32, @intCast(w * h));- const data = gdk_pixbuf_get_pixels(pixbuf);- for (pixels, 0..) |*p, i| {- const offset = @divTrunc(i, @as(usize, @intCast(w))) * @as(usize, @intCast(stride)) + i % @as(usize, @intCast(w)) * @as(usize, @intCast(channels));- const alpha: u32 = if (channels == 4) data[offset + 3] else 255;- p.* = alpha << 24 | (@as(u32, data[offset]) * alpha / 255) << 16 | (@as(u32, data[offset + 1]) * alpha / 255) << 8 | (@as(u32, data[offset + 2]) * alpha / 255);- }- return .{ .pixels = pixels, .w = w, .h = h, .mode = mode };+/// Larger files are not wallpapers; this also bounds the read.+const max_file_bytes = 256 << 20;+pub fn load(a: std.mem.Allocator, io: std.Io, path: []const u8, mode: Mode) !Image {+ const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(max_file_bytes));+ defer a.free(bytes);+ const image = try codec.decode(a, bytes);+ return .{ .pixels = image.pixels, .w = image.width, .h = image.height, .mode = mode };}pub fn render(image: Image, cr: *c.cairo_t, w: i32, h: i32) void {const surface = c.cairo_image_surface_create_for_data(@ptrCast(image.pixels.ptr), c.CAIRO_FORMAT_ARGB32, image.w, image.h, image.w * 4);diff --git a/src/desktop/watcher.zig b/src/desktop/watcher.zigindex 1f22201..26cc25d 100644--- a/src/desktop/watcher.zig+++ b/src/desktop/watcher.zig@@ -328,7 +328,7 @@ pub const Worker = struct {wallpaper_path = parsed.value;} else if (std.mem.eql(u8, key, "wallpaper_mode")) wallpaper_mode = std.meta.stringToEnum(@import("wallpaper.zig").Mode, std.mem.trim(u8, value, "\"")) orelse .fill else if (std.mem.eql(u8, key, "bottom_exclusion")) snap.bottom = std.math.clamp(std.fmt.parseInt(i32, value, 10) catch 64, 0, 4096) else if (std.mem.eql(u8, key, "icon_only_input")) snap.icon_only = std.mem.eql(u8, value, "true");}- if (wallpaper_path.len > 0) snap.wallpaper = @import("wallpaper.zig").load(mem, wallpaper_path, wallpaper_mode) catch null;+ if (wallpaper_path.len > 0) snap.wallpaper = @import("wallpaper.zig").load(mem, self.io, wallpaper_path, wallpaper_mode) catch null;const saved = std.Io.Dir.cwd().readFileAlloc(self.io, self.layout, mem, .limited(4 * 1024 * 1024)) catch "";try self.appendBuiltins(mem, &list, saved);diff --git a/src/wallpaper_codec.c b/src/wallpaper_codec.cnew file mode 100644index 0000000..9297bfe--- /dev/null+++ b/src/wallpaper_codec.c@@ -0,0 +1,298 @@+#define _GNU_SOURCE+#include "wallpaper_codec.h"++#include <limits.h>+#include <setjmp.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+/* After <stdio.h>: jpeglib.h uses FILE without including it. */+#include <jpeglib.h>+#include <png.h>+#include <webp/decode.h>++#if !defined(__BYTE_ORDER__) || __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__+#error "pixels are decoded as B, G, R, A bytes, which are 0xAARRGGBB words only on a little-endian host"+#endif++enum { K_NONE, K_PNG, K_JPEG, K_WEBP };++/* The format by its signature: a misnamed file still loads. */+static int sniff(const uint8_t *d, size_t n) {+ if (n >= 8 && png_sig_cmp(d, 0, 8) == 0) return K_PNG;+ if (n >= 3 && d[0] == 0xff && d[1] == 0xd8 && d[2] == 0xff) return K_JPEG;+ if (n >= 12 && memcmp(d, "RIFF", 4) == 0 && memcmp(d + 8, "WEBP", 4) == 0) return K_WEBP;+ return K_NONE;+}++/* Straight B, G, R, A words to premultiplied, rounded as png.zig does.+ * Returns whether any pixel is not opaque. */+static int premultiply(uint32_t *px, size_t n) {+ int translucent = 0;+ for (size_t i = 0; i < n; i++) {+ uint32_t p = px[i], a = p >> 24;+ if (a == 255) continue;+ translucent = 1;+ if (a == 0) {+ px[i] = 0;+ continue;+ }+ uint32_t r = (((p >> 16) & 0xff) * a + 127) / 255;+ uint32_t g = (((p >> 8) & 0xff) * a + 127) / 255;+ uint32_t b = ((p & 0xff) * a + 127) / 255;+ px[i] = a << 24 | r << 16 | g << 8 | b;+ }+ return translucent;+}++/* ---- JPEG --------------------------------------------------------------- */++typedef struct {+ struct jpeg_error_mgr pub;+ jmp_buf jump;+} jpeg_errors;++static void jpeg_fail(j_common_ptr cinfo) {+ longjmp(((jpeg_errors *)cinfo->err)->jump, 1);+}++static void jpeg_quiet(j_common_ptr cinfo, int level) {+ (void)cinfo;+ (void)level;+}++static void jpeg_silent(j_common_ptr cinfo) {+ (void)cinfo;+}++/* Four ink channels to opaque RGB. Adobe writes them inverted (255 is no+ * ink), so there the channels already are intensities. */+static void cmyk_row(const uint8_t *s, uint32_t *dst, int w, int inverted) {+ for (int x = 0; x < w; x++, s += 4) {+ uint32_t c = s[0], m = s[1], y = s[2], k = s[3];+ if (!inverted) {+ c = 255 - c;+ m = 255 - m;+ y = 255 - y;+ k = 255 - k;+ }+ uint32_t r = (c * k + 127) / 255, g = (m * k + 127) / 255, b = (y * k + 127) / 255;+ dst[x] = 0xff000000u | r << 16 | g << 8 | b;+ }+}++/* Reads the header into `size`, or, when `pixels` is set, decodes into it. */+static int jpeg_run(const uint8_t *data, size_t len, uint32_t *pixels, int w, int h, wc_info *size) {+ struct jpeg_decompress_struct cinfo;+ jpeg_errors errors;+ unsigned char *volatile row = NULL;+ cinfo.err = jpeg_std_error(&errors.pub);+ errors.pub.error_exit = jpeg_fail;+ errors.pub.emit_message = jpeg_quiet;+ errors.pub.output_message = jpeg_silent;+ if (setjmp(errors.jump)) {+ jpeg_destroy_decompress(&cinfo);+ free(row);+ return WC_CORRUPT;+ }+ jpeg_create_decompress(&cinfo);+ jpeg_mem_src(&cinfo, data, (unsigned long)len);+ jpeg_read_header(&cinfo, TRUE);+ if (cinfo.image_width == 0 || cinfo.image_height == 0 || cinfo.image_width > INT_MAX || cinfo.image_height > INT_MAX) {+ jpeg_destroy_decompress(&cinfo);+ return WC_CORRUPT;+ }+ if (!pixels) {+ size->w = (int)cinfo.image_width;+ size->h = (int)cinfo.image_height;+ jpeg_destroy_decompress(&cinfo);+ return WC_OK;+ }+ if ((int)cinfo.image_width != w || (int)cinfo.image_height != h) {+ jpeg_destroy_decompress(&cinfo);+ return WC_CORRUPT;+ }+ int cmyk = cinfo.jpeg_color_space == JCS_CMYK || cinfo.jpeg_color_space == JCS_YCCK;+ int inverted = cinfo.saw_Adobe_marker;+ /* Gray and YCbCr become opaque BGRA in the decoder itself. The default+ * (accurate) DCT and fancy chroma upsampling stay: this is a wallpaper. */+ cinfo.out_color_space = cmyk ? JCS_CMYK : JCS_EXT_BGRA;+ jpeg_start_decompress(&cinfo);+ if (cinfo.output_components != 4 || cinfo.output_width != (unsigned)w) {+ jpeg_destroy_decompress(&cinfo);+ return WC_CORRUPT;+ }+ if (cmyk) {+ row = malloc((size_t)w * 4);+ if (!row) {+ jpeg_destroy_decompress(&cinfo);+ return WC_NOMEM;+ }+ }+ while (cinfo.output_scanline < cinfo.output_height) {+ uint32_t *dst = pixels + (size_t)cinfo.output_scanline * (size_t)w;+ JSAMPROW rows[1] = {cmyk ? (JSAMPROW)row : (JSAMPROW)dst};+ if (jpeg_read_scanlines(&cinfo, rows, 1) != 1) break;+ if (cmyk) cmyk_row((const uint8_t *)row, dst, w, inverted);+ }+ int complete = cinfo.output_scanline == cinfo.output_height;+ jpeg_destroy_decompress(&cinfo);+ free(row);+ return complete ? WC_OK : WC_CORRUPT;+}++/* ---- PNG ---------------------------------------------------------------- */++typedef struct {+ const uint8_t *data;+ size_t len, pos;+} mem_source;++static void png_mem_read(png_structp png, png_bytep out, size_t n) {+ mem_source *src = png_get_io_ptr(png);+ if (src->len - src->pos < n) png_error(png, "truncated");+ memcpy(out, src->data + src->pos, n);+ src->pos += n;+}++/* libpng's own error handler prints to stderr when ours returns, so ours must+ * not return: it unwinds to the setjmp in png_run. */+static void png_fail(png_structp png, png_const_charp message) {+ (void)message;+ png_longjmp(png, 1);+}++static void png_quiet(png_structp png, png_const_charp message) {+ (void)png;+ (void)message;+}++static int png_run(const uint8_t *data, size_t len, uint32_t *pixels, int w, int h, wc_info *size, int *has_alpha) {+ png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, png_fail, png_quiet);+ if (!png) return WC_NOMEM;+ png_infop info = png_create_info_struct(png);+ if (!info) {+ png_destroy_read_struct(&png, NULL, NULL);+ return WC_NOMEM;+ }+ png_bytep *volatile rows = NULL;+ volatile int status = WC_CORRUPT;+ if (setjmp(png_jmpbuf(png))) {+ png_destroy_read_struct(&png, &info, NULL);+ free(rows);+ return status;+ }+ mem_source src = {data, len, 8};+ png_set_read_fn(png, &src, png_mem_read);+ png_set_sig_bytes(png, 8);+ png_read_info(png, info);+ png_uint_32 pw = 0, ph = 0;+ int depth = 0, color = 0;+ png_get_IHDR(png, info, &pw, &ph, &depth, &color, NULL, NULL, NULL);+ if (pw == 0 || ph == 0 || pw > INT_MAX / 4 || ph > INT_MAX) {+ status = WC_TOO_LARGE;+ png_destroy_read_struct(&png, &info, NULL);+ return status;+ }+ if (!pixels) {+ size->w = (int)pw;+ size->h = (int)ph;+ png_destroy_read_struct(&png, &info, NULL);+ return WC_OK;+ }+ if ((int)pw != w || (int)ph != h) {+ png_destroy_read_struct(&png, &info, NULL);+ return WC_CORRUPT;+ }+ int translucent = (color & PNG_COLOR_MASK_ALPHA) || png_get_valid(png, info, PNG_INFO_tRNS);+ if (color == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);+ if (color == PNG_COLOR_TYPE_GRAY && depth < 8) png_set_expand_gray_1_2_4_to_8(png);+ if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);+ if (depth == 16) png_set_scale_16(png);+ if (color == PNG_COLOR_TYPE_GRAY || color == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png);+ png_set_bgr(png);+ png_set_add_alpha(png, 0xff, PNG_FILLER_AFTER);+ /* Adam7 passes are merged by libpng into the rows we hand it. */+ png_set_interlace_handling(png);+ png_read_update_info(png, info);+ if (png_get_rowbytes(png, info) != (size_t)w * 4) {+ status = WC_UNSUPPORTED;+ png_destroy_read_struct(&png, &info, NULL);+ return status;+ }+ status = WC_NOMEM;+ rows = malloc((size_t)h * sizeof *rows);+ if (!rows) {+ png_destroy_read_struct(&png, &info, NULL);+ return status;+ }+ for (int y = 0; y < h; y++) rows[y] = (png_bytep)(pixels + (size_t)y * (size_t)w);+ status = WC_CORRUPT;+ png_read_image(png, rows);+ png_destroy_read_struct(&png, &info, NULL);+ free(rows);+ if (translucent && premultiply(pixels, (size_t)w * (size_t)h)) *has_alpha = 1;+ return WC_OK;+}++/* ---- WebP --------------------------------------------------------------- */++static int webp_run(const uint8_t *data, size_t len, uint32_t *pixels, int w, int h, wc_info *size, int *has_alpha) {+ WebPBitstreamFeatures features;+ VP8StatusCode status = WebPGetFeatures(data, len, &features);+ if (status == VP8_STATUS_UNSUPPORTED_FEATURE) return WC_UNSUPPORTED;+ if (status != VP8_STATUS_OK) return WC_CORRUPT;+ /* A still frame is all a wallpaper can be. */+ if (features.has_animation) return WC_UNSUPPORTED;+ if (features.width <= 0 || features.height <= 0 || features.width > INT_MAX / 4) return WC_TOO_LARGE;+ if (!pixels) {+ size->w = features.width;+ size->h = features.height;+ return WC_OK;+ }+ if (features.width != w || features.height != h) return WC_CORRUPT;+ WebPDecoderConfig config;+ if (!WebPInitDecoderConfig(&config)) return WC_NOMEM;+ /* Premultiplied B, G, R, A in the caller's memory. */+ config.output.colorspace = MODE_bgrA;+ config.output.is_external_memory = 1;+ config.output.u.RGBA.rgba = (uint8_t *)pixels;+ config.output.u.RGBA.stride = w * 4;+ config.output.u.RGBA.size = (size_t)w * 4 * (size_t)h;+ status = WebPDecode(data, len, &config);+ if (status != VP8_STATUS_OK) return WC_CORRUPT;+ if (features.has_alpha) {+ for (size_t i = 0, n = (size_t)w * (size_t)h; i < n; i++) {+ if (pixels[i] >> 24 != 0xff) {+ *has_alpha = 1;+ break;+ }+ }+ }+ return WC_OK;+}++/* ---- entry points ------------------------------------------------------- */++int wc_probe(const uint8_t *data, size_t len, wc_info *info) {+ memset(info, 0, sizeof *info);+ int unused = 0;+ switch (sniff(data, len)) {+ case K_PNG: return png_run(data, len, NULL, 0, 0, info, &unused);+ case K_JPEG: return jpeg_run(data, len, NULL, 0, 0, info);+ case K_WEBP: return webp_run(data, len, NULL, 0, 0, info, &unused);+ default: return WC_UNSUPPORTED;+ }+}++int wc_decode(const uint8_t *data, size_t len, uint32_t *pixels, int w, int h, int *has_alpha) {+ *has_alpha = 0;+ if (!pixels || w <= 0 || h <= 0) return WC_CORRUPT;+ wc_info unused;+ switch (sniff(data, len)) {+ case K_PNG: return png_run(data, len, pixels, w, h, &unused, has_alpha);+ case K_JPEG: return jpeg_run(data, len, pixels, w, h, &unused);+ case K_WEBP: return webp_run(data, len, pixels, w, h, &unused, has_alpha);+ default: return WC_UNSUPPORTED;+ }+}diff --git a/src/wallpaper_codec.h b/src/wallpaper_codec.hnew file mode 100644index 0000000..ba73f40--- /dev/null+++ b/src/wallpaper_codec.h@@ -0,0 +1,40 @@+/* Full-size wallpaper decoding straight from libjpeg(-turbo), libpng and libwebp.+ *+ * GdkPixbuf 2.44 decodes through sandboxed glycin loader processes: every+ * wallpaper (and every Appearance strip thumbnail) would start one. Here the+ * three formats a wallpaper can be (png, jpg, webp) decode in-process, at full+ * quality (accurate DCT, fancy chroma upsampling), whatever their variant:+ * palette, grayscale, 16-bit and interlaced PNG, progressive and CMYK JPEG.+ *+ * Two steps, so the caller allocates the raster with its own allocator:+ * `wc_probe` reads the header, `wc_decode` fills a `w * h` buffer. The format+ * is sniffed from the content, never the file name. Output pixels are+ * premultiplied 0xAARRGGBB (Cairo ARGB32), which needs a little-endian host.+ * Animated WebP and anything else is reported unsupported. Thread-safe: no+ * state is shared between calls. No GLib headers here: see AGENTS.md. */+#ifndef REDIWM_WALLPAPER_CODEC_H+#define REDIWM_WALLPAPER_CODEC_H++#include <stddef.h>+#include <stdint.h>++enum {+ WC_OK = 0,+ WC_UNSUPPORTED = 1, /* not a PNG, JPEG or still WebP */+ WC_TOO_LARGE = 2, /* dimensions the format allows but an int cannot hold */+ WC_CORRUPT = 3,+ WC_NOMEM = 4,+};++typedef struct {+ int w, h;+} wc_info;++/* The image's size, from its header alone. */+int wc_probe(const uint8_t *data, size_t len, wc_info *info);++/* Decodes into `pixels`, which holds `w * h` words and must match `wc_probe`'s+ * size. `*has_alpha` is set when any pixel is not opaque. */+int wc_decode(const uint8_t *data, size_t len, uint32_t *pixels, int w, int h, int *has_alpha);++#endifdiff --git a/src/wallpaper_codec.zig b/src/wallpaper_codec.zignew file mode 100644index 0000000..59b6435--- /dev/null+++ b/src/wallpaper_codec.zig@@ -0,0 +1,80 @@+//! Wallpaper decoding without GdkPixbuf: `wallpaper_codec.c` reads PNG, JPEG+//! and WebP in-process (GdkPixbuf 2.44 starts a sandboxed glycin loader+//! process for every decode). The raster is allocated here, with the caller's+//! allocator, and the codec fills it. Safe from any thread.+const std = @import("std");+const png = @import("png.zig");+const c = @import("c_wallpaper_codec");++/// Per edge, as a texture can be no larger, and in total (about 400 MiB of+/// pixels): a hostile header must not be able to ask for more.+pub const max_edge = 16384;+pub const max_pixels = 100 << 20;++pub const Error = error{ UnsupportedImage, ImageTooLarge, InvalidImage };++/// Premultiplied 0xAARRGGBB pixels of a PNG, JPEG or still WebP, chosen by+/// content. The caller owns `pixels`.+pub fn decode(allocator: std.mem.Allocator, bytes: []const u8) !png.Image {+ var size: c.wc_info = undefined;+ try check(c.wc_probe(bytes.ptr, bytes.len, &size));+ if (size.w <= 0 or size.h <= 0 or size.w > max_edge or size.h > max_edge or @as(u64, @intCast(size.w)) * @as(u64, @intCast(size.h)) > max_pixels) return error.ImageTooLarge;+ const pixels = try allocator.alloc(u32, @as(usize, @intCast(size.w)) * @as(usize, @intCast(size.h)));+ errdefer allocator.free(pixels);+ var has_alpha: c_int = 0;+ try check(c.wc_decode(bytes.ptr, bytes.len, pixels.ptr, size.w, size.h, &has_alpha));+ return .{ .width = size.w, .height = size.h, .pixels = pixels, .has_alpha = has_alpha != 0 };+}++fn check(status: c_int) Error!void {+ return switch (status) {+ c.WC_OK => {},+ c.WC_UNSUPPORTED => error.UnsupportedImage,+ c.WC_TOO_LARGE => error.ImageTooLarge,+ else => error.InvalidImage,+ };+}++test "content that is not a still PNG, JPEG or WebP is unsupported, not decoded" {+ const a = std.testing.allocator;+ try std.testing.expectError(error.UnsupportedImage, decode(a, ""));+ try std.testing.expectError(error.UnsupportedImage, decode(a, "GIF89a\x01\x00\x01\x00"));+ try std.testing.expectError(error.UnsupportedImage, decode(a, "<svg xmlns='http://www.w3.org/2000/svg'/>"));+ // A signature alone is a corrupt image, never a crash.+ try std.testing.expectError(error.InvalidImage, decode(a, "\x89PNG\r\n\x1a\n"));+ try std.testing.expectError(error.InvalidImage, decode(a, "\xff\xd8\xff\xe0"));+ try std.testing.expectError(error.InvalidImage, decode(a, "RIFF\x04\x00\x00\x00WEBP"));+}++/// A PNG that stops after its first IDAT header: enough for a size, no pixels.+fn claiming(buffer: *[45]u8, width: u32, height: u32) []const u8 {+ var ihdr: [13]u8 = @splat(0);+ std.mem.writeInt(u32, ihdr[0..4], width, .big);+ std.mem.writeInt(u32, ihdr[4..8], height, .big);+ ihdr[8] = 8;+ ihdr[9] = 6;+ @memcpy(buffer[0..8], "\x89PNG\r\n\x1a\n");+ var out: usize = 8;+ inline for (.{ .{ "IHDR", ihdr[0..] }, .{ "IDAT", ihdr[0..0] } }) |chunk| {+ std.mem.writeInt(u32, buffer[out..][0..4], chunk[1].len, .big);+ @memcpy(buffer[out + 4 ..][0..4], chunk[0]);+ @memcpy(buffer[out + 8 ..][0..chunk[1].len], chunk[1]);+ var crc: std.hash.Crc32 = .init();+ crc.update(chunk[0]);+ crc.update(chunk[1]);+ std.mem.writeInt(u32, buffer[out + 8 + chunk[1].len ..][0..4], crc.final(), .big);+ out += 12 + chunk[1].len;+ }+ return buffer[0..out];+}++test "a header claiming too large an image is refused before anything is allocated" {+ // The testing allocator would fail the test on a leak, and a failing+ // allocator proves no allocation was attempted at all.+ var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });+ var buffer: [45]u8 = undefined;+ try std.testing.expectError(error.ImageTooLarge, decode(failing.allocator(), claiming(&buffer, max_edge + 1, 8)));+ try std.testing.expectError(error.ImageTooLarge, decode(failing.allocator(), claiming(&buffer, 8, max_edge + 1)));+ // Each edge within bounds, the area not: 16000 x 16000 is 256 million pixels.+ try std.testing.expectError(error.ImageTooLarge, decode(failing.allocator(), claiming(&buffer, 16000, 16000)));+}diff --git a/src/wallpaper_load.zig b/src/wallpaper_load.zigindex d7b8f93..f457d00 100644--- a/src/wallpaper_load.zig+++ b/src/wallpaper_load.zig@@ -9,7 +9,7 @@ const posix = std.posix;const c = std.posix.system;const png = @import("png.zig");-const pixbuf = @import("desktop/wallpaper.zig");+const codec = @import("wallpaper_codec.zig");const startup = @import("startup.zig");const stats = @import("ipc/stats.zig");const wallpapers = @import("wallpapers.zig");@@ -166,25 +166,18 @@ pub fn freeResult(allocator: Allocator, result: Result) void {if (result.thumb) |thumb| thumb.deinit(allocator);}-/// png.zig's decoder for the PNGs it supports (the bundled one included),-/// GdkPixbuf for everything else.+/// png.zig's decoder for the PNGs it supports (the bundled one included), the+/// native codec (libjpeg, libpng, libwebp: never GdkPixbuf, which starts a+/// sandboxed loader process per decode) for everything else.pub fn decodeFile(allocator: Allocator, io: std.Io, path: []const u8) !png.Image {+ const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(max_file_bytes));+ defer allocator.free(bytes);if (std.ascii.endsWithIgnoreCase(path, ".png")) {- const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(max_file_bytes));- defer allocator.free(bytes);if (png.decode(allocator, bytes)) |image| return image else |err| switch (err) {- // GdkPixbuf sniffs content, so misnamed files still load.+ // The codec sniffs content, so misnamed files still load.error.UnsupportedPng, error.InvalidPng => {},else => return err,}}- const image = try pixbuf.load(allocator, path, .fill);- var opaque_pixels = true;- for (image.pixels) |p| {- if (p >> 24 != 0xff) {- opaque_pixels = false;- break;- }- }- return .{ .width = image.w, .height = image.h, .pixels = image.pixels, .has_alpha = !opaque_pixels };+ return codec.decode(allocator, bytes);}diff --git a/src/wallpapers.zig b/src/wallpapers.zigindex 04529db..0022617 100644--- a/src/wallpapers.zig+++ b/src/wallpapers.zig@@ -9,7 +9,7 @@ const std = @import("std");pub const default_name = "default.png";-/// Decoded by png.zig when it can, otherwise GdkPixbuf (wallpaper_load.zig).+/// Decoded by png.zig when it can, otherwise wallpaper_codec.c (wallpaper_load.zig).const extensions = [_][]const u8{ ".png", ".jpg", ".jpeg", ".webp" };pub const Entry = struct {diff --git a/tests/appearance_wallpaper.py b/tests/appearance_wallpaper.pyindex 5ca51f9..73d9900 100644--- a/tests/appearance_wallpaper.py+++ b/tests/appearance_wallpaper.py@@ -1,10 +1,11 @@#!/usr/bin/env python3"""Appearance > Wallpaper: lists the bundled wallpaper plus images in-$XDG_DATA_HOME/rediwm/wallpapers, switches live (PNG and GdkPixbuf-decoded-JPEG), persists `[compositor] wallpaper`, follows hand edits to a path, and-falls back to the bundled image when the chosen file is missing. A scrolling-strip of thumbnails with a tick box on the current image selects too, shows-the folder a path wallpaper lives in, and "Choose folder" picks another."""+$XDG_DATA_HOME/rediwm/wallpapers, switches live (PNG; JPEG, WebP and palette+PNG through the native codec, never GdkPixbuf), persists `[compositor]+wallpaper`, follows hand edits to a path, and falls back to the bundled image+when the chosen file is missing. A scrolling strip of thumbnails with a tick+box on the current image selects too, shows the folder a path wallpaper lives+in, and "Choose folder" picks another."""from pathlib import Pathimport tempfileimport time@@ -21,6 +22,8 @@ ROOT = Path(__file__).resolve().parents[1]AQUA = (20, 200, 190)STRIPES = (200, 60, 30)OUTSIDE = (90, 40, 160)+WEBP = (230, 120, 20)+INDEXED = (40, 160, 90)def run():@@ -33,6 +36,13 @@ def run():(user_dir / "notes.txt").write_text("not an image\n")outside = tmp / "elsewhere.png"Image.new("RGB", (64, 36), OUTSIDE).save(outside)+ # Formats png.zig cannot read: they reach the native codec.+ webp = tmp / "elsewhere.webp"+ Image.new("RGB", (64, 36), WEBP).save(webp, lossless=True)+ indexed = tmp / "elsewhere_indexed.png"+ palette_image = Image.new("P", (64, 36), 1)+ palette_image.putpalette([0, 0, 0, *INDEXED])+ palette_image.save(indexed)pictures = tmp / "pictures"pictures.mkdir()colors = [(10 + 20 * i, 240 - 15 * i, 60 + 10 * i) for i in range(12)]@@ -193,6 +203,10 @@ def run():# missing file, which falls back to the bundled image.config_path.write_text(f'[compositor]\nxwayland = false\nwallpaper = "{outside}"\n')wait_color(OUTSIDE, "configured path")+ config_path.write_text(f'[compositor]\nxwayland = false\nwallpaper = "{webp}"\n')+ wait_color(WEBP, "WebP wallpaper")+ config_path.write_text(f'[compositor]\nxwayland = false\nwallpaper = "{indexed}"\n')+ wait_color(INDEXED, "palette PNG wallpaper")# A path wallpaper shows its own folder: a scrolling row, the# current image ticked and scrolled into view.config_path.write_text(f'[compositor]\nxwayland = false\nwallpaper = "{pictures}/img07.png"\n')diff --git a/tests/wallpaper_codec.py b/tests/wallpaper_codec.pynew file mode 100644index 0000000..1d7f380--- /dev/null+++ b/tests/wallpaper_codec.py@@ -0,0 +1,312 @@+#!/usr/bin/env python3+"""src/wallpaper_codec.c against independent references: every PNG, JPEG and+WebP variant a wallpaper can be, checked pixel for pixel against Pillow, or+against the exact values a hand-written PNG encodes (Pillow cannot write+interlaced or 16-bit colour PNGs). The codec is built as a shared object and+driven through ctypes, so no compositor runs. `--sanitize` builds it with+ASan and UBSan and preloads libasan into Python.++ python3 tests/wallpaper_codec.py [--sanitize]++When zig-out/bin/rediwm exists it also checks that the compositor no longer+calls GdkPixbuf (which starts a sandboxed glycin loader process per decode).+"""+import ctypes+import io+import os+import struct+import subprocess+import sys+import tempfile+import zlib+from pathlib import Path++from PIL import Image++ROOT = Path(__file__).resolve().parents[1]+WC_OK, WC_UNSUPPORTED, WC_TOO_LARGE, WC_CORRUPT = 0, 1, 2, 3+++class Info(ctypes.Structure):+ _fields_ = [('w', ctypes.c_int), ('h', ctypes.c_int)]+++def build(directory, sanitize):+ flags = ['-fsanitize=address,undefined', '-fno-sanitize-recover=undefined'] if sanitize else []+ library = directory / 'wallpaper_codec.so'+ subprocess.run(['cc', '-shared', '-fPIC', '-g', '-O1', '-std=c11', '-Wall', '-Wextra', '-Werror', *flags,+ '-o', str(library), str(ROOT / 'src/wallpaper_codec.c'), '-ljpeg', '-lpng16', '-lwebp'], check=True)+ lib = ctypes.CDLL(str(library))+ lib.wc_probe.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(Info)]+ lib.wc_decode.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_uint32), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int)]+ return lib+++def probe(lib, data):+ info = Info()+ status = lib.wc_probe(data, len(data), ctypes.byref(info))+ return status, (info.w, info.h)+++def decode(lib, data):+ """(status, (w, h, premultiplied words, has_alpha))."""+ status, (w, h) = probe(lib, data)+ if status != WC_OK:+ return status, None+ pixels = (ctypes.c_uint32 * (w * h))()+ alpha = ctypes.c_int()+ status = lib.wc_decode(data, len(data), pixels, w, h, ctypes.byref(alpha))+ return status, (w, h, list(pixels), bool(alpha.value))+++def premultiplied(rgba):+ """Straight (r, g, b, a) tuples to the codec's premultiplied 0xAARRGGBB."""+ out = []+ for r, g, b, a in rgba:+ if a == 255:+ out.append(0xff000000 | r << 16 | g << 8 | b)+ elif a == 0:+ out.append(0)+ else:+ out.append(a << 24 | ((r * a + 127) // 255) << 16 | ((g * a + 127) // 255) << 8 | (b * a + 127) // 255)+ return out+++def check(lib, data, expected, size, tolerance, label):+ status, result = decode(lib, data)+ assert status == WC_OK, f'{label}: status {status}'+ w, h, pixels, has_alpha = result+ assert (w, h) == size, f'{label}: size {(w, h)} != {size}'+ assert len(pixels) == len(expected)+ worst = max((abs(((x >> s) & 255) - ((y >> s) & 255)) for x, y in zip(pixels, expected) for s in (24, 16, 8, 0)), default=0)+ assert worst <= tolerance, f'{label}: worst channel difference {worst} > {tolerance}'+ translucent = any(p >> 24 != 255 for p in expected)+ assert has_alpha == translucent, f'{label}: has_alpha {has_alpha}, expected {translucent}'+++# ---- hand-written PNGs -------------------------------------------------------++CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}+ADAM7 = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)]+++def chunk(kind, body):+ return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body))+++def pack_row(values, depth):+ if depth == 16:+ return b''.join(struct.pack('>H', v) for v in values)+ if depth == 8:+ return bytes(values)+ bits = ''.join(format(v, f'0{depth}b') for v in values)+ bits += '0' * (-len(bits) % 8)+ return bytes(int(bits[i:i + 8], 2) for i in range(0, len(bits), 8))+++def sample(x, y, channel, depth):+ return (x * 31 + y * 17 + channel * 101) % (1 << depth)+++def png_bytes(w, h, depth, color, interlace, plte=None, trns=None):+ passes = ADAM7 if interlace else [(0, 0, 1, 1)]+ raw = b''+ for x0, y0, dx, dy in passes:+ xs = list(range(x0, w, dx))+ if not xs:+ continue+ for y in range(y0, h, dy):+ values = [sample(x, y, c, depth) for x in xs for c in range(CHANNELS[color])]+ if color == 3:+ values = [v % len(plte) for v in values]+ raw += b'\0' + pack_row(values, depth)+ out = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, depth, color, 0, 0, int(interlace)))+ if plte:+ out += chunk(b'PLTE', bytes(v for entry in plte for v in entry))+ if trns is not None:+ out += chunk(b'tRNS', trns)+ return out + chunk(b'IDAT', zlib.compress(raw)) + chunk(b'IEND', b'')+++def scale(value, depth):+ return value * 255 // ((1 << depth) - 1) if depth < 16 else round(value * 255 / 65535)+++def expected_png(w, h, depth, color, plte, trns_value, trns_alpha):+ out = []+ for y in range(h):+ for x in range(w):+ s = [sample(x, y, c, depth) for c in range(CHANNELS[color])]+ if color == 3:+ index = s[0] % len(plte)+ r, g, b = plte[index]+ a = trns_alpha[index] if index < len(trns_alpha) else 255+ elif color in (0, 4):+ r = g = b = scale(s[0], depth)+ a = scale(s[1], depth) if color == 4 else 255+ if trns_value is not None and s[0] == trns_value[0]:+ a = 0+ else:+ r, g, b = (scale(v, depth) for v in s[:3])+ a = scale(s[3], depth) if color == 6 else 255+ if trns_value is not None and tuple(s) == trns_value:+ a = 0+ out.append((r, g, b, a))+ return premultiplied(out)+++def png_cases(lib):+ w, h = 19, 13 # Odd sizes: partial Adam7 passes and bit-packed row padding.+ cases = 0+ palette = [(i * 16, 255 - i * 16, (i * 77) % 256) for i in range(16)]+ for interlace in (False, True):+ for color, depths in ((0, (1, 2, 4, 8, 16)), (2, (8, 16)), (3, (1, 2, 4, 8)), (4, (8, 16)), (6, (8, 16))):+ for depth in depths:+ plte = palette[:min(16, 1 << depth)] if color == 3 else None+ data = png_bytes(w, h, depth, color, interlace, plte=plte)+ label = f'png color={color} depth={depth} interlace={interlace}'+ check(lib, data, expected_png(w, h, depth, color, plte, None, []), (w, h), 1 if depth == 16 else 0, label)+ cases += 1+ # tRNS: a colour key (gray, truecolour) and per-index alpha (palette).+ for color, depth in ((0, 8), (0, 16), (0, 2), (2, 8), (2, 16)):+ key = tuple(sample(0, 0, c, depth) for c in range(CHANNELS[color]))+ body = b''.join(struct.pack('>H', v) for v in key)+ data = png_bytes(w, h, depth, color, interlace, trns=body)+ label = f'png tRNS color={color} depth={depth} interlace={interlace}'+ check(lib, data, expected_png(w, h, depth, color, None, key, []), (w, h), 1 if depth == 16 else 0, label)+ cases += 1+ for depth in (4, 8):+ plte = palette[:min(16, 1 << depth)]+ alphas = [255 - 17 * i for i in range(0, len(plte) - 3)] # The last three entries stay opaque.+ data = png_bytes(w, h, depth, 3, interlace, plte=plte, trns=bytes(alphas))+ check(lib, data, expected_png(w, h, depth, 3, plte, None, alphas), (w, h), 0, f'png tRNS palette depth={depth} interlace={interlace}')+ cases += 1+ return cases+++# ---- Pillow-written files, read back by Pillow ---------------------------------++def pattern(w, h, mode='RGBA'):+ image = Image.new('RGBA', (w, h))+ image.putdata([(x * 255 // max(w - 1, 1), y * 255 // max(h - 1, 1), (x * 7 + y * 13) % 256, (x * y * 5) % 256 if mode == 'RGBA' else 255)+ for y in range(h) for x in range(w)])+ return image if mode == 'RGBA' else image.convert('RGB')+++def save(image, fmt, **options):+ out = io.BytesIO()+ image.save(out, fmt, **options)+ return out.getvalue()+++def reference(data):+ with Image.open(io.BytesIO(data)) as image:+ raw = image.convert('RGBA').tobytes()+ return premultiplied([tuple(raw[i:i + 4]) for i in range(0, len(raw), 4)]), image.size+++def pillow_cases(lib):+ cases = 0+ for w, h in ((64, 48), (37, 29), (1, 1)):+ rgba, rgb = pattern(w, h), pattern(w, h, 'RGB')+ for label, data, tolerance in (+ ('png rgb', save(rgb, 'PNG'), 0),+ ('png rgba', save(rgba, 'PNG'), 0),+ ('png palette', save(rgb.convert('P', palette=Image.Palette.ADAPTIVE, colors=40), 'PNG'), 0),+ ('png palette+transparency', save(rgba.convert('P', palette=Image.Palette.ADAPTIVE, colors=40), 'PNG', transparency=3), 0),+ ('png gray', save(rgb.convert('L'), 'PNG'), 0),+ ('png gray+alpha', save(rgba.convert('LA'), 'PNG'), 0),+ ('png 1-bit', save(rgb.convert('1'), 'PNG'), 0),+ ('jpeg 4:2:0', save(rgb, 'JPEG', quality=90), 1),+ ('jpeg 4:4:4', save(rgb, 'JPEG', quality=95, subsampling=0), 1),+ ('jpeg 4:2:2', save(rgb, 'JPEG', quality=85, subsampling=1), 1),+ ('jpeg progressive', save(rgb, 'JPEG', quality=90, progressive=True), 1),+ ('jpeg optimized', save(rgb, 'JPEG', quality=90, optimize=True), 1),+ ('jpeg gray', save(rgb.convert('L'), 'JPEG', quality=90), 1),+ ('jpeg cmyk', save(rgb.convert('CMYK'), 'JPEG', quality=95), 2),+ ('webp lossless', save(rgb, 'WEBP', lossless=True), 0),+ ('webp lossless alpha', save(rgba, 'WEBP', lossless=True), 1),+ ('webp lossy', save(rgb, 'WEBP', quality=80), 0),+ ('webp lossy alpha', save(rgba, 'WEBP', quality=80), 1),+ ):+ expected, size = reference(data)+ check(lib, data, expected, size, tolerance, f'{label} {w}x{h}')+ cases += 1+ # EXIF orientation is not applied (a wallpaper never was): the stored size stays.+ exif = Image.Exif()+ exif[0x0112] = 6+ data = save(pattern(40, 24, 'RGB'), 'JPEG', exif=exif)+ expected, size = reference(data)+ check(lib, data, expected, size, 1, 'jpeg with EXIF orientation')+ assert probe(lib, data) == (WC_OK, (40, 24))+ return cases + 1+++def failure_cases(lib):+ rgb = pattern(32, 24, 'RGB')+ png = save(rgb, 'PNG')+ webp = save(rgb, 'WEBP', lossless=True)+ jpeg = save(rgb, 'JPEG')+ for label, data in (('empty', b''), ('text', b'not an image at all'), ('svg', b"<svg xmlns='http://www.w3.org/2000/svg'/>"),+ ('gif', save(rgb.convert('P'), 'GIF')), ('bmp', save(rgb, 'BMP')), ('tiff', save(rgb, 'TIFF'))):+ assert probe(lib, data)[0] == WC_UNSUPPORTED, label+ # Animated WebP: a still frame is all a wallpaper can be.+ try:+ animated = save(rgb, 'WEBP', save_all=True, append_images=[pattern(32, 24, 'RGB').transpose(Image.Transpose.FLIP_LEFT_RIGHT)], duration=100, lossless=True)+ except Exception as err: # Pillow built without animated WebP.+ print('skipping animated WebP:', err)+ else:+ if b'ANIM' in animated:+ assert probe(lib, animated)[0] == WC_UNSUPPORTED, 'animated webp'+ # Truncated and damaged files fail cleanly.+ for label, data in (('png', png), ('webp', webp)):+ for cut in (len(data) // 2, len(data) - 40):+ assert decode(lib, data[:cut])[0] == WC_CORRUPT, f'truncated {label} at {cut}'+ for label, data in (('png', png[:8]), ('jpeg', jpeg[:4]), ('webp', webp[:12])):+ assert decode(lib, data)[0] == WC_CORRUPT, f'{label} signature only'+ damaged = bytearray(png)+ damaged[len(damaged) // 2] ^= 0xff+ assert decode(lib, bytes(damaged))[0] in (WC_CORRUPT, WC_OK) # Never a crash; a flipped IDAT bit usually fails the checksum.+ # A header that claims a huge image is reported, not allocated: the caller+ # bounds it. libpng reads up to the first IDAT before it reports a size.+ def claiming(w, h):+ return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b'')+ assert probe(lib, claiming(70000, 70000)) == (WC_OK, (70000, 70000))+ assert probe(lib, claiming(0x7fffffff, 1))[0] in (WC_TOO_LARGE, WC_CORRUPT)+ assert probe(lib, claiming(0, 1))[0] == WC_CORRUPT+ # A buffer that does not match the file's own size is refused before any write.+ pixels = (ctypes.c_uint32 * (64 * 64))()+ alpha = ctypes.c_int()+ for w, h in ((31, 24), (33, 24), (32, 23), (32, 25), (64, 64)):+ assert lib.wc_decode(png, len(png), pixels, w, h, ctypes.byref(alpha)) == WC_CORRUPT, (w, h)+ assert lib.wc_decode(webp, len(webp), pixels, w, h, ctypes.byref(alpha)) == WC_CORRUPT, (w, h)+ assert lib.wc_decode(jpeg, len(jpeg), pixels, w, h, ctypes.byref(alpha)) == WC_CORRUPT, (w, h)+ assert lib.wc_decode(png, len(png), None, 32, 24, ctypes.byref(alpha)) == WC_CORRUPT+ return 8+++def compositor_does_not_call_pixbuf():+ binary = ROOT / 'zig-out/bin/rediwm'+ if not binary.exists():+ print('zig-out/bin/rediwm not built: skipping the GdkPixbuf symbol check')+ return+ undefined = subprocess.run(['nm', '-D', '--undefined-only', str(binary)], capture_output=True, text=True, check=True).stdout+ calls = [line.split()[-1] for line in undefined.splitlines() if 'gdk_pixbuf' in line or 'glycin' in line]+ assert not calls, f'the compositor must not call GdkPixbuf or glycin: {calls}'+ print('The compositor calls no GdkPixbuf or glycin function')+++def main():+ sanitize = '--sanitize' in sys.argv+ if sanitize and 'libasan' not in os.environ.get('LD_PRELOAD', ''):+ asan = subprocess.run(['cc', '-print-file-name=libasan.so'], capture_output=True, text=True, check=True).stdout.strip()+ os.execvpe(sys.executable, [sys.executable, *sys.argv], {**os.environ, 'LD_PRELOAD': asan, 'ASAN_OPTIONS': 'detect_leaks=0'})+ with tempfile.TemporaryDirectory(prefix='rediwm-wallpaper-codec-') as directory:+ lib = build(Path(directory), sanitize)+ total = png_cases(lib) + pillow_cases(lib) + failure_cases(lib)+ print(f'Wallpaper codec: {total} cases passed' + (' under ASan and UBSan' if sanitize else ''))+ compositor_does_not_call_pixbuf()+++if __name__ == '__main__':+ main()