aboutsummaryrefslogtreecommitdiff
path: root/src/link/MachO/commands.zig
blob: 93e6890a31ace0f23bf2d009728ce05eb8a28087 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
const std = @import("std");
const fs = std.fs;
const io = std.io;
const mem = std.mem;
const meta = std.meta;
const macho = std.macho;
const testing = std.testing;
const assert = std.debug.assert;

const Allocator = std.mem.Allocator;
const MachO = @import("../MachO.zig");
const makeStaticString = MachO.makeStaticString;
const padToIdeal = MachO.padToIdeal;

pub const LoadCommand = union(enum) {
    Segment: SegmentCommand,
    DyldInfoOnly: macho.dyld_info_command,
    Symtab: macho.symtab_command,
    Dysymtab: macho.dysymtab_command,
    Dylinker: GenericCommandWithData(macho.dylinker_command),
    Dylib: GenericCommandWithData(macho.dylib_command),
    Main: macho.entry_point_command,
    VersionMin: macho.version_min_command,
    SourceVersion: macho.source_version_command,
    Uuid: macho.uuid_command,
    LinkeditData: macho.linkedit_data_command,
    Rpath: GenericCommandWithData(macho.rpath_command),
    Unknown: GenericCommandWithData(macho.load_command),

    pub fn read(allocator: *Allocator, reader: anytype) !LoadCommand {
        const header = try reader.readStruct(macho.load_command);
        var buffer = try allocator.alloc(u8, header.cmdsize);
        defer allocator.free(buffer);
        mem.copy(u8, buffer, mem.asBytes(&header));
        try reader.readNoEof(buffer[@sizeOf(macho.load_command)..]);
        var stream = io.fixedBufferStream(buffer);

        return switch (header.cmd) {
            macho.LC_SEGMENT_64 => LoadCommand{
                .Segment = try SegmentCommand.read(allocator, stream.reader()),
            },
            macho.LC_DYLD_INFO,
            macho.LC_DYLD_INFO_ONLY,
            => LoadCommand{
                .DyldInfoOnly = try stream.reader().readStruct(macho.dyld_info_command),
            },
            macho.LC_SYMTAB => LoadCommand{
                .Symtab = try stream.reader().readStruct(macho.symtab_command),
            },
            macho.LC_DYSYMTAB => LoadCommand{
                .Dysymtab = try stream.reader().readStruct(macho.dysymtab_command),
            },
            macho.LC_ID_DYLINKER,
            macho.LC_LOAD_DYLINKER,
            macho.LC_DYLD_ENVIRONMENT,
            => LoadCommand{
                .Dylinker = try GenericCommandWithData(macho.dylinker_command).read(allocator, stream.reader()),
            },
            macho.LC_ID_DYLIB,
            macho.LC_LOAD_WEAK_DYLIB,
            macho.LC_LOAD_DYLIB,
            macho.LC_REEXPORT_DYLIB,
            => LoadCommand{
                .Dylib = try GenericCommandWithData(macho.dylib_command).read(allocator, stream.reader()),
            },
            macho.LC_MAIN => LoadCommand{
                .Main = try stream.reader().readStruct(macho.entry_point_command),
            },
            macho.LC_VERSION_MIN_MACOSX,
            macho.LC_VERSION_MIN_IPHONEOS,
            macho.LC_VERSION_MIN_WATCHOS,
            macho.LC_VERSION_MIN_TVOS,
            => LoadCommand{
                .VersionMin = try stream.reader().readStruct(macho.version_min_command),
            },
            macho.LC_SOURCE_VERSION => LoadCommand{
                .SourceVersion = try stream.reader().readStruct(macho.source_version_command),
            },
            macho.LC_UUID => LoadCommand{
                .Uuid = try stream.reader().readStruct(macho.uuid_command),
            },
            macho.LC_FUNCTION_STARTS,
            macho.LC_DATA_IN_CODE,
            macho.LC_CODE_SIGNATURE,
            => LoadCommand{
                .LinkeditData = try stream.reader().readStruct(macho.linkedit_data_command),
            },
            macho.LC_RPATH => LoadCommand{
                .Rpath = try GenericCommandWithData(macho.rpath_command).read(allocator, stream.reader()),
            },
            else => LoadCommand{
                .Unknown = try GenericCommandWithData(macho.load_command).read(allocator, stream.reader()),
            },
        };
    }

    pub fn write(self: LoadCommand, writer: anytype) !void {
        return switch (self) {
            .DyldInfoOnly => |x| writeStruct(x, writer),
            .Symtab => |x| writeStruct(x, writer),
            .Dysymtab => |x| writeStruct(x, writer),
            .Main => |x| writeStruct(x, writer),
            .VersionMin => |x| writeStruct(x, writer),
            .SourceVersion => |x| writeStruct(x, writer),
            .Uuid => |x| writeStruct(x, writer),
            .LinkeditData => |x| writeStruct(x, writer),
            .Segment => |x| x.write(writer),
            .Dylinker => |x| x.write(writer),
            .Dylib => |x| x.write(writer),
            .Rpath => |x| x.write(writer),
            .Unknown => |x| x.write(writer),
        };
    }

    pub fn cmd(self: LoadCommand) u32 {
        return switch (self) {
            .DyldInfoOnly => |x| x.cmd,
            .Symtab => |x| x.cmd,
            .Dysymtab => |x| x.cmd,
            .Main => |x| x.cmd,
            .VersionMin => |x| x.cmd,
            .SourceVersion => |x| x.cmd,
            .Uuid => |x| x.cmd,
            .LinkeditData => |x| x.cmd,
            .Segment => |x| x.inner.cmd,
            .Dylinker => |x| x.inner.cmd,
            .Dylib => |x| x.inner.cmd,
            .Rpath => |x| x.inner.cmd,
            .Unknown => |x| x.inner.cmd,
        };
    }

    pub fn cmdsize(self: LoadCommand) u32 {
        return switch (self) {
            .DyldInfoOnly => |x| x.cmdsize,
            .Symtab => |x| x.cmdsize,
            .Dysymtab => |x| x.cmdsize,
            .Main => |x| x.cmdsize,
            .VersionMin => |x| x.cmdsize,
            .SourceVersion => |x| x.cmdsize,
            .LinkeditData => |x| x.cmdsize,
            .Uuid => |x| x.cmdsize,
            .Segment => |x| x.inner.cmdsize,
            .Dylinker => |x| x.inner.cmdsize,
            .Dylib => |x| x.inner.cmdsize,
            .Rpath => |x| x.inner.cmdsize,
            .Unknown => |x| x.inner.cmdsize,
        };
    }

    pub fn deinit(self: *LoadCommand, allocator: *Allocator) void {
        return switch (self.*) {
            .Segment => |*x| x.deinit(allocator),
            .Dylinker => |*x| x.deinit(allocator),
            .Dylib => |*x| x.deinit(allocator),
            .Rpath => |*x| x.deinit(allocator),
            .Unknown => |*x| x.deinit(allocator),
            else => {},
        };
    }

    fn writeStruct(command: anytype, writer: anytype) !void {
        return writer.writeAll(mem.asBytes(&command));
    }

    fn eql(self: LoadCommand, other: LoadCommand) bool {
        if (@as(meta.Tag(LoadCommand), self) != @as(meta.Tag(LoadCommand), other)) return false;
        return switch (self) {
            .DyldInfoOnly => |x| meta.eql(x, other.DyldInfoOnly),
            .Symtab => |x| meta.eql(x, other.Symtab),
            .Dysymtab => |x| meta.eql(x, other.Dysymtab),
            .Main => |x| meta.eql(x, other.Main),
            .VersionMin => |x| meta.eql(x, other.VersionMin),
            .SourceVersion => |x| meta.eql(x, other.SourceVersion),
            .Uuid => |x| meta.eql(x, other.Uuid),
            .LinkeditData => |x| meta.eql(x, other.LinkeditData),
            .Segment => |x| x.eql(other.Segment),
            .Dylinker => |x| x.eql(other.Dylinker),
            .Dylib => |x| x.eql(other.Dylib),
            .Rpath => |x| x.eql(other.Rpath),
            .Unknown => |x| x.eql(other.Unknown),
        };
    }
};

pub const SegmentCommand = struct {
    inner: macho.segment_command_64,
    sections: std.ArrayListUnmanaged(macho.section_64) = .{},

    pub fn empty(inner: macho.segment_command_64) SegmentCommand {
        return .{ .inner = inner };
    }

    pub fn addSection(self: *SegmentCommand, alloc: *Allocator, section: macho.section_64) !void {
        try self.sections.append(alloc, section);
        self.inner.cmdsize += @sizeOf(macho.section_64);
        self.inner.nsects += 1;
    }

    pub fn read(alloc: *Allocator, reader: anytype) !SegmentCommand {
        const inner = try reader.readStruct(macho.segment_command_64);
        var segment = SegmentCommand{
            .inner = inner,
        };
        try segment.sections.ensureCapacity(alloc, inner.nsects);

        var i: usize = 0;
        while (i < inner.nsects) : (i += 1) {
            const section = try reader.readStruct(macho.section_64);
            segment.sections.appendAssumeCapacity(section);
        }

        return segment;
    }

    pub fn write(self: SegmentCommand, writer: anytype) !void {
        try writer.writeAll(mem.asBytes(&self.inner));
        for (self.sections.items) |sect| {
            try writer.writeAll(mem.asBytes(&sect));
        }
    }

    pub fn deinit(self: *SegmentCommand, alloc: *Allocator) void {
        self.sections.deinit(alloc);
    }

    pub fn allocatedSize(self: SegmentCommand, start: u64) u64 {
        assert(start > 0);
        if (start == self.inner.fileoff)
            return 0;
        var min_pos: u64 = std.math.maxInt(u64);
        for (self.sections.items) |section| {
            if (section.offset <= start) continue;
            if (section.offset < min_pos) min_pos = section.offset;
        }
        return min_pos - start;
    }

    fn detectAllocCollision(self: SegmentCommand, start: u64, size: u64) ?u64 {
        const end = start + padToIdeal(size);
        for (self.sections.items) |section| {
            const increased_size = padToIdeal(section.size);
            const test_end = section.offset + increased_size;
            if (end > section.offset and start < test_end) {
                return test_end;
            }
        }
        return null;
    }

    pub fn findFreeSpace(self: SegmentCommand, object_size: u64, min_alignment: u16, start: ?u64) u64 {
        var st: u64 = if (start) |v| v else self.inner.fileoff;
        while (self.detectAllocCollision(st, object_size)) |item_end| {
            st = mem.alignForwardGeneric(u64, item_end, min_alignment);
        }
        return st;
    }

    fn eql(self: SegmentCommand, other: SegmentCommand) bool {
        if (!meta.eql(self.inner, other.inner)) return false;
        const lhs = self.sections.items;
        const rhs = other.sections.items;
        var i: usize = 0;
        while (i < self.inner.nsects) : (i += 1) {
            if (!meta.eql(lhs[i], rhs[i])) return false;
        }
        return true;
    }
};

pub fn emptyGenericCommandWithData(cmd: anytype) GenericCommandWithData(@TypeOf(cmd)) {
    return .{ .inner = cmd };
}

pub fn GenericCommandWithData(comptime Cmd: type) type {
    return struct {
        inner: Cmd,
        /// This field remains undefined until `read` is called.
        data: []u8 = undefined,

        const Self = @This();

        pub fn read(allocator: *Allocator, reader: anytype) !Self {
            const inner = try reader.readStruct(Cmd);
            var data = try allocator.alloc(u8, inner.cmdsize - @sizeOf(Cmd));
            errdefer allocator.free(data);
            try reader.readNoEof(data);
            return Self{
                .inner = inner,
                .data = data,
            };
        }

        pub fn write(self: Self, writer: anytype) !void {
            try writer.writeAll(mem.asBytes(&self.inner));
            try writer.writeAll(self.data);
        }

        pub fn deinit(self: *Self, allocator: *Allocator) void {
            allocator.free(self.data);
        }

        fn eql(self: Self, other: Self) bool {
            if (!meta.eql(self.inner, other.inner)) return false;
            return mem.eql(u8, self.data, other.data);
        }
    };
}

pub fn createLoadDylibCommand(
    allocator: *Allocator,
    name: []const u8,
    timestamp: u32,
    current_version: u32,
    compatibility_version: u32,
) !GenericCommandWithData(macho.dylib_command) {
    const cmdsize = @intCast(u32, mem.alignForwardGeneric(
        u64,
        @sizeOf(macho.dylib_command) + name.len,
        @sizeOf(u64),
    ));

    var dylib_cmd = emptyGenericCommandWithData(macho.dylib_command{
        .cmd = macho.LC_LOAD_DYLIB,
        .cmdsize = cmdsize,
        .dylib = .{
            .name = @sizeOf(macho.dylib_command),
            .timestamp = timestamp,
            .current_version = current_version,
            .compatibility_version = compatibility_version,
        },
    });
    dylib_cmd.data = try allocator.alloc(u8, cmdsize - dylib_cmd.inner.dylib.name);

    mem.set(u8, dylib_cmd.data, 0);
    mem.copy(u8, dylib_cmd.data, name);

    return dylib_cmd;
}

fn testRead(allocator: *Allocator, buffer: []const u8, expected: anytype) !void {
    var stream = io.fixedBufferStream(buffer);
    var given = try LoadCommand.read(allocator, stream.reader());
    defer given.deinit(allocator);
    try testing.expect(expected.eql(given));
}

fn testWrite(buffer: []u8, cmd: LoadCommand, expected: []const u8) !void {
    var stream = io.fixedBufferStream(buffer);
    try cmd.write(stream.writer());
    try testing.expect(mem.eql(u8, expected, buffer[0..expected.len]));
}

test "read-write segment command" {
    var gpa = testing.allocator;
    const in_buffer = &[_]u8{
        0x19, 0x00, 0x00, 0x00, // cmd
        0x98, 0x00, 0x00, 0x00, // cmdsize
        0x5f, 0x5f, 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // segname
        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // vmaddr
        0x00, 0x80, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // vmsize
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // fileoff
        0x00, 0x80, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, // filesize
        0x07, 0x00, 0x00, 0x00, // maxprot
        0x05, 0x00, 0x00, 0x00, // initprot
        0x01, 0x00, 0x00, 0x00, // nsects
        0x00, 0x00, 0x00, 0x00, // flags
        0x5f, 0x5f, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // sectname
        0x5f, 0x5f, 0x54, 0x45, 0x58, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // segname
        0x00, 0x40, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // address
        0xc0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // size
        0x00, 0x40, 0x00, 0x00, // offset
        0x02, 0x00, 0x00, 0x00, // alignment
        0x00, 0x00, 0x00, 0x00, // reloff
        0x00, 0x00, 0x00, 0x00, // nreloc
        0x00, 0x04, 0x00, 0x80, // flags
        0x00, 0x00, 0x00, 0x00, // reserved1
        0x00, 0x00, 0x00, 0x00, // reserved2
        0x00, 0x00, 0x00, 0x00, // reserved3
    };
    var cmd = SegmentCommand{
        .inner = .{
            .cmd = macho.LC_SEGMENT_64,
            .cmdsize = 152,
            .segname = makeStaticString("__TEXT"),
            .vmaddr = 4294967296,
            .vmsize = 294912,
            .fileoff = 0,
            .filesize = 294912,
            .maxprot = macho.VM_PROT_READ | macho.VM_PROT_WRITE | macho.VM_PROT_EXECUTE,
            .initprot = macho.VM_PROT_EXECUTE | macho.VM_PROT_READ,
            .nsects = 1,
            .flags = 0,
        },
    };
    try cmd.sections.append(gpa, .{
        .sectname = makeStaticString("__text"),
        .segname = makeStaticString("__TEXT"),
        .addr = 4294983680,
        .size = 448,
        .offset = 16384,
        .@"align" = 2,
        .reloff = 0,
        .nreloc = 0,
        .flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS,
        .reserved1 = 0,
        .reserved2 = 0,
        .reserved3 = 0,
    });
    defer cmd.deinit(gpa);
    try testRead(gpa, in_buffer, LoadCommand{ .Segment = cmd });

    var out_buffer: [in_buffer.len]u8 = undefined;
    try testWrite(&out_buffer, LoadCommand{ .Segment = cmd }, in_buffer);
}

test "read-write generic command with data" {
    var gpa = testing.allocator;
    const in_buffer = &[_]u8{
        0x0c, 0x00, 0x00, 0x00, // cmd
        0x20, 0x00, 0x00, 0x00, // cmdsize
        0x18, 0x00, 0x00, 0x00, // name
        0x02, 0x00, 0x00, 0x00, // timestamp
        0x00, 0x00, 0x00, 0x00, // current_version
        0x00, 0x00, 0x00, 0x00, // compatibility_version
        0x2f, 0x75, 0x73, 0x72, 0x00, 0x00, 0x00, 0x00, // data
    };
    var cmd = GenericCommandWithData(macho.dylib_command){
        .inner = .{
            .cmd = macho.LC_LOAD_DYLIB,
            .cmdsize = 32,
            .dylib = .{
                .name = 24,
                .timestamp = 2,
                .current_version = 0,
                .compatibility_version = 0,
            },
        },
    };
    cmd.data = try gpa.alloc(u8, 8);
    defer gpa.free(cmd.data);
    cmd.data[0] = 0x2f;
    cmd.data[1] = 0x75;
    cmd.data[2] = 0x73;
    cmd.data[3] = 0x72;
    cmd.data[4] = 0x0;
    cmd.data[5] = 0x0;
    cmd.data[6] = 0x0;
    cmd.data[7] = 0x0;
    try testRead(gpa, in_buffer, LoadCommand{ .Dylib = cmd });

    var out_buffer: [in_buffer.len]u8 = undefined;
    try testWrite(&out_buffer, LoadCommand{ .Dylib = cmd }, in_buffer);
}

test "read-write C struct command" {
    var gpa = testing.allocator;
    const in_buffer = &[_]u8{
        0x28, 0x00, 0x00, 0x80, // cmd
        0x18, 0x00, 0x00, 0x00, // cmdsize
        0x04, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // entryoff
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // stacksize
    };
    const cmd = .{
        .cmd = macho.LC_MAIN,
        .cmdsize = 24,
        .entryoff = 16644,
        .stacksize = 0,
    };
    try testRead(gpa, in_buffer, LoadCommand{ .Main = cmd });

    var out_buffer: [in_buffer.len]u8 = undefined;
    try testWrite(&out_buffer, LoadCommand{ .Main = cmd }, in_buffer);
}