// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Zig implementations of the C allocation functions, exported under their C //! names when this module is built without libc. //! //! WUFFS generates a `wuffs_*__decoder__alloc` constructor for every decoder, //! and those call `calloc` and `free`. Nothing in this library calls one -- //! `decoder.zig` allocates the decoder with a Zig allocator instead, for the //! reason recorded there -- but they are compiled in all the same, so a link //! against a target with no libc has to resolve the symbols somehow. Leaving //! it to `--gc-sections` works on wasm and in ELF release builds and not in //! ELF Debug, which is a confusing thing for a library to be sensitive to. //! Defining the functions is simpler, and it means WUFFS' own constructors //! actually work on a target with no libc rather than merely linking. //! //! They are exported only when `builtin.link_libc` is false, so that they //! cannot collide with the real ones. Take that as a rule rather than a //! detail: do not build *this* module without libc inside a program that //! links libc. The link would succeed -- a definition in an object file wins //! over one in an archive, which is how a program swaps in jemalloc -- and //! these would quietly become the whole program's allocator. const std = @import("std"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; /// The allocator the exported C functions allocate from. /// /// On wasm this is `std.heap.wasm_allocator`, which needs nothing set up and /// grows linear memory as required. Everywhere else there is no heap a /// library may assume, so it starts as null and every allocation fails -- /// which `wuffs_*__decoder__alloc` reports by returning NULL, its ordinary /// out-of-memory answer, so nothing is worse off than it was. A program that /// wants those constructors on such a target sets this first, before any /// call that could allocate. pub var allocator: ?Allocator = if (builtin.target.cpu.arch.isWasm()) std.heap.wasm_allocator else null; /// C promises memory aligned for any fundamental type. Sixteen bytes covers /// every target this builds for, and over-aligning is never wrong. const alignment: std.mem.Alignment = .fromByteUnits(16); /// Every block is allocated with this many bytes in front of it, holding the /// size that `free` and `realloc` are not given. It is a whole alignment so /// that the pointer handed back is still aligned. const prefix = alignment.toByteUnits(); comptime { std.debug.assert(prefix >= @sizeOf(usize)); } fn allocate(size: usize) ?[*]u8 { const gpa = allocator orelse return null; const total = std.math.add(usize, prefix, size) catch return null; const raw = gpa.alignedAlloc(u8, alignment, total) catch return null; std.mem.bytesAsValue(usize, raw[0..@sizeOf(usize)]).* = size; return raw.ptr + prefix; } /// The whole allocation behind a pointer `allocate` returned, prefix and all, /// which is what the allocator has to be given back. fn block(ptr: [*]u8) []align(alignment.toByteUnits()) u8 { const raw: [*]align(alignment.toByteUnits()) u8 = @alignCast(ptr - prefix); const size = std.mem.bytesAsValue(usize, raw[0..@sizeOf(usize)]).*; return raw[0 .. prefix + size]; } fn malloc(size: usize) callconv(.c) ?*anyopaque { return @ptrCast(allocate(size)); } fn calloc(count: usize, size: usize) callconv(.c) ?*anyopaque { const total = std.math.mul(usize, count, size) catch return null; const ptr = allocate(total) orelse return null; @memset(ptr[0..total], 0); return @ptrCast(ptr); } fn realloc(maybe_ptr: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { const ptr: [*]u8 = @ptrCast(maybe_ptr orelse return malloc(size)); const old = block(ptr); const old_size = old.len - prefix; if (old_size == size) return @ptrCast(ptr); // Allocate before freeing, so that a failure leaves the old block intact // -- which is what C requires of realloc. const new = allocate(size) orelse return null; @memcpy(new[0..@min(old_size, size)], ptr[0..@min(old_size, size)]); const gpa = allocator orelse unreachable; gpa.free(old); return @ptrCast(new); } fn free(maybe_ptr: ?*anyopaque) callconv(.c) void { const ptr: [*]u8 = @ptrCast(maybe_ptr orelse return); const gpa = allocator orelse return; gpa.free(block(ptr)); } comptime { if (!builtin.link_libc) { @export(&malloc, .{ .name = "malloc" }); @export(&calloc, .{ .name = "calloc" }); @export(&realloc, .{ .name = "realloc" }); @export(&free, .{ .name = "free" }); } } const testing = std.testing; /// Run `body` with the C functions pointed at the testing allocator, which /// then proves on the way out that everything allocated was handed back. fn withTestingAllocator(body: fn () anyerror!void) !void { const previous = allocator; defer allocator = previous; allocator = testing.allocator; try body(); } test "malloc and free round trip" { try withTestingAllocator(struct { fn f() anyerror!void { const p: [*]u8 = @ptrCast(malloc(64) orelse return error.OutOfMemory); try testing.expect(std.mem.isAligned(@intFromPtr(p), 16)); @memset(p[0..64], 0xAA); try testing.expectEqual(@as(u8, 0xAA), p[63]); free(p); } }.f); } test "calloc zeroes and free accepts null" { try withTestingAllocator(struct { fn f() anyerror!void { const p: [*]u8 = @ptrCast(calloc(8, 8) orelse return error.OutOfMemory); try testing.expectEqualSlices(u8, &@as([64]u8, @splat(0)), p[0..64]); free(p); free(null); } }.f); } test "calloc refuses a product that overflows" { try withTestingAllocator(struct { fn f() anyerror!void { try testing.expectEqual(@as(?*anyopaque, null), calloc(std.math.maxInt(usize), 2)); } }.f); } test "realloc keeps the contents it can" { try withTestingAllocator(struct { fn f() anyerror!void { const p: [*]u8 = @ptrCast(malloc(4) orelse return error.OutOfMemory); @memcpy(p[0..4], "wuff"); const grown: [*]u8 = @ptrCast(realloc(p, 16) orelse return error.OutOfMemory); try testing.expectEqualSlices(u8, "wuff", grown[0..4]); const shrunk: [*]u8 = @ptrCast(realloc(grown, 2) orelse return error.OutOfMemory); try testing.expectEqualSlices(u8, "wu", shrunk[0..2]); free(shrunk); } }.f); } test "realloc of null is malloc" { try withTestingAllocator(struct { fn f() anyerror!void { const p = realloc(null, 32) orelse return error.OutOfMemory; free(p); } }.f); } test "allocation fails rather than panicking when no allocator is set" { const previous = allocator; defer allocator = previous; allocator = null; try testing.expectEqual(@as(?*anyopaque, null), malloc(1)); try testing.expectEqual(@as(?*anyopaque, null), calloc(1, 1)); free(null); } test "WUFFS' own allocating constructor goes through these" { // The whole point of the exports: `wuffs_png__decoder__alloc` is C code // calling calloc, and on a target with no libc the calloc it reaches is // the one above. Where libc is linked they are not exported and this // proves nothing, so it does not run. if (builtin.link_libc) return error.SkipZigTest; const c = @import("wuffs_c"); const previous = allocator; defer allocator = previous; allocator = testing.allocator; const decoder = c.wuffs_png__decoder__alloc(); try testing.expect(decoder != null); // Allocated by WUFFS, freed by us, which is what its C API asks for. free(decoder); }