master
 1const std = @import("std");
 2const assert = std.debug.assert;
 3const builtin = @import("builtin");
 4const log = std.log.scoped(.macho);
 5const macho = std.macho;
 6const mem = std.mem;
 7const native_endian = builtin.target.cpu.arch.endian();
 8
 9const MachO = @import("../MachO.zig");
10
11pub fn readFatHeader(file: std.fs.File) !macho.fat_header {
12    return readFatHeaderGeneric(macho.fat_header, file, 0);
13}
14
15fn readFatHeaderGeneric(comptime Hdr: type, file: std.fs.File, offset: usize) !Hdr {
16    var buffer: [@sizeOf(Hdr)]u8 = undefined;
17    const nread = try file.preadAll(&buffer, offset);
18    if (nread != buffer.len) return error.InputOutput;
19    var hdr = @as(*align(1) const Hdr, @ptrCast(&buffer)).*;
20    mem.byteSwapAllFields(Hdr, &hdr);
21    return hdr;
22}
23
24pub const Arch = struct {
25    tag: std.Target.Cpu.Arch,
26    offset: u32,
27    size: u32,
28};
29
30pub fn parseArchs(file: std.fs.File, fat_header: macho.fat_header, out: *[2]Arch) ![]const Arch {
31    var count: usize = 0;
32    var fat_arch_index: u32 = 0;
33    while (fat_arch_index < fat_header.nfat_arch and count < out.len) : (fat_arch_index += 1) {
34        const offset = @sizeOf(macho.fat_header) + @sizeOf(macho.fat_arch) * fat_arch_index;
35        const fat_arch = try readFatHeaderGeneric(macho.fat_arch, file, offset);
36        // If we come across an architecture that we do not know how to handle, that's
37        // fine because we can keep looking for one that might match.
38        const arch: std.Target.Cpu.Arch = switch (fat_arch.cputype) {
39            macho.CPU_TYPE_ARM64 => if (fat_arch.cpusubtype == macho.CPU_SUBTYPE_ARM_ALL) .aarch64 else continue,
40            macho.CPU_TYPE_X86_64 => if (fat_arch.cpusubtype == macho.CPU_SUBTYPE_X86_64_ALL) .x86_64 else continue,
41            else => continue,
42        };
43        out[count] = .{ .tag = arch, .offset = fat_arch.offset, .size = fat_arch.size };
44        count += 1;
45    }
46
47    return out[0..count];
48}