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