Something went wrong. Try again.
A puzzle game of bent arrows sent off a board of dots, written in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Adds files to an APK that `aapt2 link` made, which has the manifest and//! resources and nothing else://!//! apk OUT BASE NAME=PATH...//!//! Every entry of BASE is copied as it is, and each PATH is added under//! NAME. Files added are stored rather than compressed, and stored entries//! are aligned, as `zipalign` would: native libraries to 16 KiB, so that//! Android can map them straight out of the APK on a device with 16 KiB//! pages, and everything else to 4 bytes. The result still has to be//! signed, and signing keeps the alignment.
const std = @import("std");const builtin = @import("builtin");const Allocator = std.mem.Allocator;const Io = std.Io;const zip = std.zip;
comptime { // The zip structures are read and written as they lie in memory. std.debug.assert(builtin.cpu.arch.endian() == .little);}
pub const Entry = struct { name: []const u8, data: []const u8,};
const library_alignment = 16 * 1024;const stored_alignment = 4;/// General purpose flag bit 3: sizes and checksum follow the data.const data_descriptor_flag: u16 = 1 << 3;/// 1980-01-01, the earliest a zip can say: an added file's time says/// nothing, and leaving it out keeps the APK the same from build to build.const dos_date: u16 = (0 << 9) | (1 << 5) | 1;
pub fn main(init: std.process.Init) !u8 { const gpa = init.gpa; const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len < 3) { std.log.err("usage: apk OUT BASE NAME=PATH...", .{}); return 2; } const cwd = Io.Dir.cwd(); const base = try cwd.readFileAlloc(io, args[2], gpa, .limited(256 * 1024 * 1024)); defer gpa.free(base);
var entries: std.ArrayList(Entry) = .empty; defer { for (entries.items) |e| gpa.free(e.data); entries.deinit(gpa); } for (args[3..]) |arg| { const eq = std.mem.findScalar(u8, arg, '=') orelse { std.log.err("{s}: not NAME=PATH", .{arg}); return 2; }; const data = try cwd.readFileAlloc(io, arg[eq + 1 ..], gpa, .limited(256 * 1024 * 1024)); errdefer gpa.free(data); try entries.append(gpa, .{ .name = arg[0..eq], .data = data }); }
var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try pack(gpa, base, entries.items, &out.writer); try cwd.writeFile(io, .{ .sub_path = args[1], .data = out.written() }); return 0;}
/// The end of central directory record, which is the last thing in a zip/// but for a comment of up to 64 KiB. (`std.zip.EndRecord.findBuffer` does/// this too, but in 0.17.0 does not compile.)fn findEnd(zip_bytes: []const u8) !zip.EndRecord { const size = @sizeOf(zip.EndRecord); if (zip_bytes.len < size) return error.ZipNoEndRecord; var at = zip_bytes.len - size; const lowest = zip_bytes.len -| (size + std.math.maxInt(u16)); while (true) : (at -= 1) { if (std.mem.eql(u8, zip_bytes[at..][0..4], &zip.end_record_sig)) { const end = std.mem.bytesToValue(zip.EndRecord, zip_bytes[at..][0..size]); if (at + size + end.comment_len == zip_bytes.len) return end; } if (at == lowest) return error.ZipNoEndRecord; }}
const Central = struct { header: zip.CentralDirectoryFileHeader, /// The name, extra field and comment that follow it. rest: []const u8,};
/// Writes `base` with `entries` added to `w`.pub fn pack(gpa: Allocator, base: []const u8, entries: []const Entry, w: *Io.Writer) !void { const end = try findEnd(base); if (end.need_zip64() or end.disk_number != 0) return error.UnsupportedZip;
var central: std.ArrayList(Central) = .empty; defer central.deinit(gpa); var offset: u64 = 0;
var at: usize = end.central_directory_offset; for (0..end.record_count_total) |_| { if (at + @sizeOf(zip.CentralDirectoryFileHeader) > base.len) return error.ZipTruncated; var c = std.mem.bytesToValue(zip.CentralDirectoryFileHeader, base[at..][0..@sizeOf(zip.CentralDirectoryFileHeader)]); if (!std.mem.eql(u8, &c.signature, &zip.central_file_header_sig)) return error.ZipBadCentralHeader; const rest_len = @as(usize, c.filename_len) + c.extra_len + c.comment_len; const rest_start = at + @sizeOf(zip.CentralDirectoryFileHeader); if (rest_start + rest_len > base.len) return error.ZipTruncated; const rest = base[rest_start..][0..rest_len]; at = rest_start + rest_len;
const lh_at: usize = c.local_file_header_offset; if (lh_at + @sizeOf(zip.LocalFileHeader) > base.len) return error.ZipTruncated; const local = std.mem.bytesToValue(zip.LocalFileHeader, base[lh_at..][0..@sizeOf(zip.LocalFileHeader)]); if (!std.mem.eql(u8, &local.signature, &zip.local_file_header_sig)) return error.ZipBadLocalHeader; const data_at = lh_at + @sizeOf(zip.LocalFileHeader) + local.filename_len + local.extra_len; if (data_at + c.compressed_size > base.len) return error.ZipTruncated; const name = base[lh_at + @sizeOf(zip.LocalFileHeader) ..][0..local.filename_len];
// The sizes and checksum go in the local header, from the central // directory, so no data descriptor follows the data. c.flags = @bitCast(@as(u16, @bitCast(c.flags)) & ~data_descriptor_flag); c.local_file_header_offset = std.math.cast(u32, offset) orelse return error.ZipTooBig; offset += try writeLocal(w, offset, .{ .header = c, .name = name, .data = base[data_at..][0..c.compressed_size], }); try central.append(gpa, .{ .header = c, .rest = rest }); }
for (entries) |e| { const size = std.math.cast(u32, e.data.len) orelse return error.ZipTooBig; const c: zip.CentralDirectoryFileHeader = .{ .signature = zip.central_file_header_sig, .version_made_by = 20, .version_needed_to_extract = 10, .flags = .{ .encrypted = false, ._ = 0 }, .compression_method = .store, .last_modification_time = 0, .last_modification_date = dos_date, .crc32 = std.hash.Crc32.hash(e.data), .compressed_size = size, .uncompressed_size = size, .filename_len = std.math.cast(u16, e.name.len) orelse return error.ZipNameTooLong, .extra_len = 0, .comment_len = 0, .disk_number = 0, .internal_file_attributes = 0, .external_file_attributes = 0, .local_file_header_offset = std.math.cast(u32, offset) orelse return error.ZipTooBig, }; offset += try writeLocal(w, offset, .{ .header = c, .name = e.name, .data = e.data }); try central.append(gpa, .{ .header = c, .rest = e.name }); }
const central_at = offset; for (central.items) |c| { try w.writeAll(std.mem.asBytes(&c.header)); try w.writeAll(c.rest); offset += @sizeOf(zip.CentralDirectoryFileHeader) + c.rest.len; } const count = std.math.cast(u16, central.items.len) orelse return error.ZipTooManyEntries; const record: zip.EndRecord = .{ .signature = zip.end_record_sig, .disk_number = 0, .central_directory_disk_number = 0, .record_count_disk = count, .record_count_total = count, .central_directory_size = std.math.cast(u32, offset - central_at) orelse return error.ZipTooBig, .central_directory_offset = std.math.cast(u32, central_at) orelse return error.ZipTooBig, .comment_len = 0, }; try w.writeAll(std.mem.asBytes(&record));}
const Local = struct { header: zip.CentralDirectoryFileHeader, name: []const u8, data: []const u8,};
/// Writes an entry's local header and data at `offset`, padding the header's/// extra field so that stored data is aligned; returns how much it wrote./// The extra field of an entry copied from `aapt2` is dropped, since it is/// only ever padding of its own.fn writeLocal(w: *Io.Writer, offset: u64, e: Local) !u64 { const unpadded = offset + @sizeOf(zip.LocalFileHeader) + e.name.len; const alignment: u64 = if (e.header.compression_method != .store) 1 else if (std.mem.endsWith(u8, e.name, ".so")) library_alignment else stored_alignment; const padding = std.mem.alignForward(u64, unpadded, alignment) - unpadded; const h = e.header; const local: zip.LocalFileHeader = .{ .signature = zip.local_file_header_sig, .version_needed_to_extract = h.version_needed_to_extract, .flags = h.flags, .compression_method = h.compression_method, .last_modification_time = h.last_modification_time, .last_modification_date = h.last_modification_date, .crc32 = h.crc32, .compressed_size = h.compressed_size, .uncompressed_size = h.uncompressed_size, .filename_len = h.filename_len, .extra_len = @intCast(padding), }; try w.writeAll(std.mem.asBytes(&local)); try w.writeAll(e.name); try w.splatByteAll(0, padding); try w.writeAll(e.data); return @sizeOf(zip.LocalFileHeader) + e.name.len + padding + e.data.len;}
const testing = std.testing;
/// The offset of the data of the entry called `name` in `apk`.fn dataOffset(apk: []const u8, name: []const u8) !usize { const end = try findEnd(apk); var at: usize = end.central_directory_offset; for (0..end.record_count_total) |_| { const c = std.mem.bytesToValue(zip.CentralDirectoryFileHeader, apk[at..][0..@sizeOf(zip.CentralDirectoryFileHeader)]); const n = apk[at + @sizeOf(zip.CentralDirectoryFileHeader) ..][0..c.filename_len]; at += @sizeOf(zip.CentralDirectoryFileHeader) + c.filename_len + c.extra_len + c.comment_len; if (!std.mem.eql(u8, n, name)) continue; const l = std.mem.bytesToValue(zip.LocalFileHeader, apk[c.local_file_header_offset..][0..@sizeOf(zip.LocalFileHeader)]); return c.local_file_header_offset + @sizeOf(zip.LocalFileHeader) + l.filename_len + l.extra_len; } return error.NotFound;}
test "entries are added to what was there, stored and aligned" { const gpa = testing.allocator; const empty = std.mem.asBytes(&zip.EndRecord{ .signature = zip.end_record_sig, .disk_number = 0, .central_directory_disk_number = 0, .record_count_disk = 0, .record_count_total = 0, .central_directory_size = 0, .central_directory_offset = 0, .comment_len = 0, }); var first: Io.Writer.Allocating = .init(gpa); defer first.deinit(); try pack(gpa, empty, &.{.{ .name = "AndroidManifest.xml", .data = "manifest" }}, &first.writer);
var second: Io.Writer.Allocating = .init(gpa); defer second.deinit(); try pack(gpa, first.written(), &.{ .{ .name = "lib/arm64-v8a/libpfeilstorch.so", .data = "\x7fELF library" }, }, &second.writer); const apk = second.written();
const manifest = try dataOffset(apk, "AndroidManifest.xml"); try testing.expectEqual(0, manifest % stored_alignment); try testing.expectEqualStrings("manifest", apk[manifest..][0..8]); const library = try dataOffset(apk, "lib/arm64-v8a/libpfeilstorch.so"); try testing.expectEqual(0, library % library_alignment); try testing.expectEqualStrings("\x7fELF library", apk[library..][0..12]);
// And it is a zip that Zig's own reader can list and check. var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const io = testing.io; try tmp.dir.writeFile(io, .{ .sub_path = "test.apk", .data = apk }); const file = try tmp.dir.openFile(io, "test.apk", .{}); defer file.close(io); var buf: [4096]u8 = undefined; var reader = file.reader(io, &buf); var it = try zip.Iterator.init(&reader); var names: usize = 0; while (try it.next()) |_| names += 1; try testing.expectEqual(2, names); try zip.extract(tmp.dir, &reader, .{}); var out: [32]u8 = undefined; try testing.expectEqualStrings("\x7fELF library", try tmp.dir.readFile(io, "lib/arm64-v8a/libpfeilstorch.so", &out));}