| ... | @@ -17,6 +17,7 @@ const aarch64 = @import("../arch/aarch64/bits.zig"); | ... | @@ -17,6 +17,7 @@ const aarch64 = @import("../arch/aarch64/bits.zig"); |
| 17 | const bind = @import("MachO/bind.zig"); | 17 | const bind = @import("MachO/bind.zig"); |
| 18 | const codegen = @import("../codegen.zig"); | 18 | const codegen = @import("../codegen.zig"); |
| 19 | const dead_strip = @import("MachO/dead_strip.zig"); | 19 | const dead_strip = @import("MachO/dead_strip.zig"); |
| | 20 | const fat = @import("MachO/fat.zig"); |
| 20 | const link = @import("../link.zig"); | 21 | const link = @import("../link.zig"); |
| 21 | const llvm_backend = @import("../codegen/llvm.zig"); | 22 | const llvm_backend = @import("../codegen/llvm.zig"); |
| 22 | const target_util = @import("../target.zig"); | 23 | const target_util = @import("../target.zig"); |
| ... | @@ -60,6 +61,29 @@ const SystemLib = struct { | ... | @@ -60,6 +61,29 @@ const SystemLib = struct { |
| 60 | weak: bool = false, | 61 | weak: bool = false, |
| 61 | }; | 62 | }; |
| 62 | | 63 | |
| | 64 | const Section = struct { |
| | 65 | header: macho.section_64, |
| | 66 | segment_index: u8, |
| | 67 | last_atom: ?*Atom = null, // TODO temporary hack; we really should shrink section to 0 |
| | 68 | |
| | 69 | /// A list of atoms that have surplus capacity. This list can have false |
| | 70 | /// positives, as functions grow and shrink over time, only sometimes being added |
| | 71 | /// or removed from the freelist. |
| | 72 | /// |
| | 73 | /// An atom has surplus capacity when its overcapacity value is greater than |
| | 74 | /// padToIdeal(minimum_atom_size). That is, when it has so |
| | 75 | /// much extra capacity, that we could fit a small new symbol in it, itself with |
| | 76 | /// ideal_capacity or more. |
| | 77 | /// |
| | 78 | /// Ideal capacity is defined by size + (size / ideal_factor). |
| | 79 | /// |
| | 80 | /// Overcapacity is measured by actual_capacity - ideal_capacity. Note that |
| | 81 | /// overcapacity can be negative. A simple way to have negative overcapacity is to |
| | 82 | /// allocate a fresh atom, which will have ideal capacity, and then grow it |
| | 83 | /// by 1 byte. It will then have -1 overcapacity. |
| | 84 | free_list: std.ArrayListUnmanaged(*Atom) = .{}, |
| | 85 | }; |
| | 86 | |
| 63 | base: File, | 87 | base: File, |
| 64 | | 88 | |
| 65 | /// If this is not null, an object file is created by LLVM and linked with LLD afterwards. | 89 | /// If this is not null, an object file is created by LLVM and linked with LLD afterwards. |
| ... | @@ -77,80 +101,67 @@ page_size: u16, | ... | @@ -77,80 +101,67 @@ page_size: u16, |
| 77 | /// fashion (default for LLVM backend). | 101 | /// fashion (default for LLVM backend). |
| 78 | mode: enum { incremental, one_shot }, | 102 | mode: enum { incremental, one_shot }, |
| 79 | | 103 | |
| 80 | /// The absolute address of the entry point. | 104 | uuid: macho.uuid_command = .{ |
| 81 | entry_addr: ?u64 = null, | 105 | .cmdsize = @sizeOf(macho.uuid_command), |
| 82 | | 106 | .uuid = undefined, |
| 83 | /// Code signature (if any) | 107 | }, |
| 84 | code_signature: ?CodeSignature = null, | | |
| 85 | | 108 | |
| 86 | objects: std.ArrayListUnmanaged(Object) = .{}, | 109 | objects: std.ArrayListUnmanaged(Object) = .{}, |
| 87 | archives: std.ArrayListUnmanaged(Archive) = .{}, | 110 | archives: std.ArrayListUnmanaged(Archive) = .{}, |
| 88 | | | |
| 89 | dylibs: std.ArrayListUnmanaged(Dylib) = .{}, | 111 | dylibs: std.ArrayListUnmanaged(Dylib) = .{}, |
| 90 | dylibs_map: std.StringHashMapUnmanaged(u16) = .{}, | 112 | dylibs_map: std.StringHashMapUnmanaged(u16) = .{}, |
| 91 | referenced_dylibs: std.AutoArrayHashMapUnmanaged(u16, void) = .{}, | 113 | referenced_dylibs: std.AutoArrayHashMapUnmanaged(u16, void) = .{}, |
| 92 | | 114 | |
| 93 | load_commands: std.ArrayListUnmanaged(macho.LoadCommand) = .{}, | 115 | segments: std.ArrayListUnmanaged(macho.segment_command_64) = .{}, |
| 94 | | 116 | sections: std.MultiArrayList(Section) = .{}, |
| 95 | pagezero_segment_cmd_index: ?u16 = null, | 117 | |
| 96 | text_segment_cmd_index: ?u16 = null, | 118 | pagezero_segment_cmd_index: ?u8 = null, |
| 97 | data_const_segment_cmd_index: ?u16 = null, | 119 | text_segment_cmd_index: ?u8 = null, |
| 98 | data_segment_cmd_index: ?u16 = null, | 120 | data_const_segment_cmd_index: ?u8 = null, |
| 99 | linkedit_segment_cmd_index: ?u16 = null, | 121 | data_segment_cmd_index: ?u8 = null, |
| 100 | dyld_info_cmd_index: ?u16 = null, | 122 | linkedit_segment_cmd_index: ?u8 = null, |
| 101 | symtab_cmd_index: ?u16 = null, | | |
| 102 | dysymtab_cmd_index: ?u16 = null, | | |
| 103 | dylinker_cmd_index: ?u16 = null, | | |
| 104 | data_in_code_cmd_index: ?u16 = null, | | |
| 105 | function_starts_cmd_index: ?u16 = null, | | |
| 106 | main_cmd_index: ?u16 = null, | | |
| 107 | dylib_id_cmd_index: ?u16 = null, | | |
| 108 | source_version_cmd_index: ?u16 = null, | | |
| 109 | build_version_cmd_index: ?u16 = null, | | |
| 110 | uuid_cmd_index: ?u16 = null, | | |
| 111 | code_signature_cmd_index: ?u16 = null, | | |
| 112 | | 123 | |
| 113 | // __TEXT segment sections | 124 | // __TEXT segment sections |
| 114 | text_section_index: ?u16 = null, | 125 | text_section_index: ?u8 = null, |
| 115 | stubs_section_index: ?u16 = null, | 126 | stubs_section_index: ?u8 = null, |
| 116 | stub_helper_section_index: ?u16 = null, | 127 | stub_helper_section_index: ?u8 = null, |
| 117 | text_const_section_index: ?u16 = null, | 128 | text_const_section_index: ?u8 = null, |
| 118 | cstring_section_index: ?u16 = null, | 129 | cstring_section_index: ?u8 = null, |
| 119 | ustring_section_index: ?u16 = null, | 130 | ustring_section_index: ?u8 = null, |
| 120 | gcc_except_tab_section_index: ?u16 = null, | 131 | gcc_except_tab_section_index: ?u8 = null, |
| 121 | unwind_info_section_index: ?u16 = null, | 132 | unwind_info_section_index: ?u8 = null, |
| 122 | eh_frame_section_index: ?u16 = null, | 133 | eh_frame_section_index: ?u8 = null, |
| 123 | | 134 | |
| 124 | objc_methlist_section_index: ?u16 = null, | 135 | objc_methlist_section_index: ?u8 = null, |
| 125 | objc_methname_section_index: ?u16 = null, | 136 | objc_methname_section_index: ?u8 = null, |
| 126 | objc_methtype_section_index: ?u16 = null, | 137 | objc_methtype_section_index: ?u8 = null, |
| 127 | objc_classname_section_index: ?u16 = null, | 138 | objc_classname_section_index: ?u8 = null, |
| 128 | | 139 | |
| 129 | // __DATA_CONST segment sections | 140 | // __DATA_CONST segment sections |
| 130 | got_section_index: ?u16 = null, | 141 | got_section_index: ?u8 = null, |
| 131 | mod_init_func_section_index: ?u16 = null, | 142 | mod_init_func_section_index: ?u8 = null, |
| 132 | mod_term_func_section_index: ?u16 = null, | 143 | mod_term_func_section_index: ?u8 = null, |
| 133 | data_const_section_index: ?u16 = null, | 144 | data_const_section_index: ?u8 = null, |
| 134 | | 145 | |
| 135 | objc_cfstring_section_index: ?u16 = null, | 146 | objc_cfstring_section_index: ?u8 = null, |
| 136 | objc_classlist_section_index: ?u16 = null, | 147 | objc_classlist_section_index: ?u8 = null, |
| 137 | objc_imageinfo_section_index: ?u16 = null, | 148 | objc_imageinfo_section_index: ?u8 = null, |
| 138 | | 149 | |
| 139 | // __DATA segment sections | 150 | // __DATA segment sections |
| 140 | tlv_section_index: ?u16 = null, | 151 | tlv_section_index: ?u8 = null, |
| 141 | tlv_data_section_index: ?u16 = null, | 152 | tlv_data_section_index: ?u8 = null, |
| 142 | tlv_bss_section_index: ?u16 = null, | 153 | tlv_bss_section_index: ?u8 = null, |
| 143 | tlv_ptrs_section_index: ?u16 = null, | 154 | tlv_ptrs_section_index: ?u8 = null, |
| 144 | la_symbol_ptr_section_index: ?u16 = null, | 155 | la_symbol_ptr_section_index: ?u8 = null, |
| 145 | data_section_index: ?u16 = null, | 156 | data_section_index: ?u8 = null, |
| 146 | bss_section_index: ?u16 = null, | 157 | bss_section_index: ?u8 = null, |
| 147 | | 158 | |
| 148 | objc_const_section_index: ?u16 = null, | 159 | objc_const_section_index: ?u8 = null, |
| 149 | objc_selrefs_section_index: ?u16 = null, | 160 | objc_selrefs_section_index: ?u8 = null, |
| 150 | objc_classrefs_section_index: ?u16 = null, | 161 | objc_classrefs_section_index: ?u8 = null, |
| 151 | objc_data_section_index: ?u16 = null, | 162 | objc_data_section_index: ?u8 = null, |
| 152 | | 163 | |
| 153 | rustc_section_index: ?u16 = null, | 164 | rustc_section_index: ?u8 = null, |
| 154 | rustc_section_size: u64 = 0, | 165 | rustc_section_size: u64 = 0, |
| 155 | | 166 | |
| 156 | locals: std.ArrayListUnmanaged(macho.nlist_64) = .{}, | 167 | locals: std.ArrayListUnmanaged(macho.nlist_64) = .{}, |
| ... | @@ -188,37 +199,12 @@ stubs_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, | ... | @@ -188,37 +199,12 @@ stubs_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, |
| 188 | | 199 | |
| 189 | error_flags: File.ErrorFlags = File.ErrorFlags{}, | 200 | error_flags: File.ErrorFlags = File.ErrorFlags{}, |
| 190 | | 201 | |
| 191 | load_commands_dirty: bool = false, | | |
| 192 | sections_order_dirty: bool = false, | | |
| 193 | | | |
| 194 | /// A helper var to indicate if we are at the start of the incremental updates, or | 202 | /// A helper var to indicate if we are at the start of the incremental updates, or |
| 195 | /// already somewhere further along the update-and-run chain. | 203 | /// already somewhere further along the update-and-run chain. |
| 196 | /// TODO once we add opening a prelinked output binary from file, this will become | 204 | /// TODO once we add opening a prelinked output binary from file, this will become |
| 197 | /// obsolete as we will carry on where we left off. | 205 | /// obsolete as we will carry on where we left off. |
| 198 | cold_start: bool = true, | 206 | cold_start: bool = true, |
| 199 | | 207 | |
| 200 | section_ordinals: std.AutoArrayHashMapUnmanaged(MatchingSection, void) = .{}, | | |
| 201 | | | |
| 202 | /// A list of atoms that have surplus capacity. This list can have false | | |
| 203 | /// positives, as functions grow and shrink over time, only sometimes being added | | |
| 204 | /// or removed from the freelist. | | |
| 205 | /// | | |
| 206 | /// An atom has surplus capacity when its overcapacity value is greater than | | |
| 207 | /// padToIdeal(minimum_atom_size). That is, when it has so | | |
| 208 | /// much extra capacity, that we could fit a small new symbol in it, itself with | | |
| 209 | /// ideal_capacity or more. | | |
| 210 | /// | | |
| 211 | /// Ideal capacity is defined by size + (size / ideal_factor). | | |
| 212 | /// | | |
| 213 | /// Overcapacity is measured by actual_capacity - ideal_capacity. Note that | | |
| 214 | /// overcapacity can be negative. A simple way to have negative overcapacity is to | | |
| 215 | /// allocate a fresh atom, which will have ideal capacity, and then grow it | | |
| 216 | /// by 1 byte. It will then have -1 overcapacity. | | |
| 217 | atom_free_lists: std.AutoHashMapUnmanaged(MatchingSection, std.ArrayListUnmanaged(*Atom)) = .{}, | | |
| 218 | | | |
| 219 | /// Pointer to the last allocated atom | | |
| 220 | atoms: std.AutoHashMapUnmanaged(MatchingSection, *Atom) = .{}, | | |
| 221 | | | |
| 222 | /// List of atoms that are either synthetic or map directly to the Zig source program. | 208 | /// List of atoms that are either synthetic or map directly to the Zig source program. |
| 223 | managed_atoms: std.ArrayListUnmanaged(*Atom) = .{}, | 209 | managed_atoms: std.ArrayListUnmanaged(*Atom) = .{}, |
| 224 | | 210 | |
| ... | @@ -250,7 +236,7 @@ unnamed_const_atoms: UnnamedConstTable = .{}, | ... | @@ -250,7 +236,7 @@ unnamed_const_atoms: UnnamedConstTable = .{}, |
| 250 | /// We store them here so that we can properly dispose of any allocated | 236 | /// We store them here so that we can properly dispose of any allocated |
| 251 | /// memory within the atom in the incremental linker. | 237 | /// memory within the atom in the incremental linker. |
| 252 | /// TODO consolidate this. | 238 | /// TODO consolidate this. |
| 253 | decls: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, ?MatchingSection) = .{}, | 239 | decls: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, ?u8) = .{}, |
| 254 | | 240 | |
| 255 | const Entry = struct { | 241 | const Entry = struct { |
| 256 | target: SymbolWithLoc, | 242 | target: SymbolWithLoc, |
| ... | @@ -408,12 +394,7 @@ pub fn openPath(allocator: Allocator, options: link.Options) !*MachO { | ... | @@ -408,12 +394,7 @@ pub fn openPath(allocator: Allocator, options: link.Options) !*MachO { |
| 408 | | 394 | |
| 409 | pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO { | 395 | pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO { |
| 410 | const cpu_arch = options.target.cpu.arch; | 396 | const cpu_arch = options.target.cpu.arch; |
| 411 | const os_tag = options.target.os.tag; | | |
| 412 | const abi = options.target.abi; | | |
| 413 | const page_size: u16 = if (cpu_arch == .aarch64) 0x4000 else 0x1000; | 397 | const page_size: u16 = if (cpu_arch == .aarch64) 0x4000 else 0x1000; |
| 414 | // Adhoc code signature is required when targeting aarch64-macos either directly or indirectly via the simulator | | |
| 415 | // ABI such as aarch64-ios-simulator, etc. | | |
| 416 | const requires_adhoc_codesig = cpu_arch == .aarch64 and (os_tag == .macos or abi == .simulator); | | |
| 417 | const use_llvm = build_options.have_llvm and options.use_llvm; | 398 | const use_llvm = build_options.have_llvm and options.use_llvm; |
| 418 | const use_stage1 = build_options.is_stage1 and options.use_stage1; | 399 | const use_stage1 = build_options.is_stage1 and options.use_stage1; |
| 419 | | 400 | |
| ... | @@ -428,10 +409,6 @@ pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO { | ... | @@ -428,10 +409,6 @@ pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO { |
| 428 | .file = null, | 409 | .file = null, |
| 429 | }, | 410 | }, |
| 430 | .page_size = page_size, | 411 | .page_size = page_size, |
| 431 | .code_signature = if (requires_adhoc_codesig) | | |
| 432 | CodeSignature.init(page_size) | | |
| 433 | else | | |
| 434 | null, | | |
| 435 | .mode = if (use_stage1 or use_llvm or options.module == null or options.cache_mode == .whole) | 412 | .mode = if (use_stage1 or use_llvm or options.module == null or options.cache_mode == .whole) |
| 436 | .one_shot | 413 | .one_shot |
| 437 | else | 414 | else |
| ... | @@ -562,8 +539,8 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No | ... | @@ -562,8 +539,8 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 562 | var dependent_libs = std.fifo.LinearFifo(struct { | 539 | var dependent_libs = std.fifo.LinearFifo(struct { |
| 563 | id: Dylib.Id, | 540 | id: Dylib.Id, |
| 564 | parent: u16, | 541 | parent: u16, |
| 565 | }, .Dynamic).init(self.base.allocator); | 542 | }, .Dynamic).init(arena); |
| 566 | defer dependent_libs.deinit(); | 543 | |
| 567 | try self.parseLibs(libs.keys(), libs.values(), self.base.options.sysroot, &dependent_libs); | 544 | try self.parseLibs(libs.keys(), libs.values(), self.base.options.sysroot, &dependent_libs); |
| 568 | try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs); | 545 | try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs); |
| 569 | } | 546 | } |
| ... | @@ -573,7 +550,6 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No | ... | @@ -573,7 +550,6 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 573 | try self.createDyldPrivateAtom(); | 550 | try self.createDyldPrivateAtom(); |
| 574 | try self.createStubHelperPreambleAtom(); | 551 | try self.createStubHelperPreambleAtom(); |
| 575 | try self.resolveSymbolsInDylibs(); | 552 | try self.resolveSymbolsInDylibs(); |
| 576 | try self.addCodeSignatureLC(); | | |
| 577 | | 553 | |
| 578 | if (self.unresolved.count() > 0) { | 554 | if (self.unresolved.count() > 0) { |
| 579 | return error.UndefinedSymbolReference; | 555 | return error.UndefinedSymbolReference; |
| ... | @@ -583,67 +559,91 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No | ... | @@ -583,67 +559,91 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 583 | | 559 | |
| 584 | if (build_options.enable_logging) { | 560 | if (build_options.enable_logging) { |
| 585 | self.logSymtab(); | 561 | self.logSymtab(); |
| 586 | self.logSectionOrdinals(); | | |
| 587 | self.logAtoms(); | 562 | self.logAtoms(); |
| 588 | } | 563 | } |
| 589 | | 564 | |
| 590 | try self.writeAtomsIncremental(); | 565 | try self.writeAtomsIncremental(); |
| 591 | | 566 | |
| 592 | try self.setEntryPoint(); | 567 | var lc_buffer = std.ArrayList(u8).init(arena); |
| 593 | try self.updateSectionOrdinals(); | 568 | const lc_writer = lc_buffer.writer(); |
| 594 | try self.writeLinkeditSegment(); | 569 | var ncmds: u32 = 0; |
| 595 | | 570 | |
| 596 | if (self.d_sym) |*d_sym| { | 571 | try self.writeLinkeditSegmentData(&ncmds, lc_writer); |
| 597 | // Flush debug symbols bundle. | 572 | try writeDylinkerLC(&ncmds, lc_writer); |
| 598 | try d_sym.flushModule(self.base.allocator, self.base.options); | 573 | |
| | 574 | self.writeMainLC(&ncmds, lc_writer) catch |err| switch (err) { |
| | 575 | error.MissingMainEntrypoint => { |
| | 576 | self.error_flags.no_entry_point_found = true; |
| | 577 | }, |
| | 578 | else => |e| return e, |
| | 579 | }; |
| | 580 | |
| | 581 | try self.writeDylibIdLC(&ncmds, lc_writer); |
| | 582 | try self.writeRpathLCs(&ncmds, lc_writer); |
| | 583 | |
| | 584 | { |
| | 585 | try lc_writer.writeStruct(macho.source_version_command{ |
| | 586 | .cmdsize = @sizeOf(macho.source_version_command), |
| | 587 | .version = 0x0, |
| | 588 | }); |
| | 589 | ncmds += 1; |
| 599 | } | 590 | } |
| 600 | | 591 | |
| 601 | // code signature and entitlements | 592 | try self.writeBuildVersionLC(&ncmds, lc_writer); |
| 602 | if (self.base.options.entitlements) |path| { | 593 | |
| 603 | if (self.code_signature) |*csig| { | 594 | { |
| 604 | try csig.addEntitlements(self.base.allocator, path); | 595 | std.crypto.random.bytes(&self.uuid.uuid); |
| 605 | csig.code_directory.ident = self.base.options.emit.?.sub_path; | 596 | try lc_writer.writeStruct(self.uuid); |
| 606 | } else { | 597 | ncmds += 1; |
| 607 | var csig = CodeSignature.init(self.page_size); | | |
| 608 | try csig.addEntitlements(self.base.allocator, path); | | |
| 609 | csig.code_directory.ident = self.base.options.emit.?.sub_path; | | |
| 610 | self.code_signature = csig; | | |
| 611 | } | | |
| 612 | } | 598 | } |
| 613 | | 599 | |
| 614 | if (self.code_signature) |*csig| { | 600 | try self.writeLoadDylibLCs(&ncmds, lc_writer); |
| 615 | csig.clear(self.base.allocator); | 601 | |
| 616 | csig.code_directory.ident = self.base.options.emit.?.sub_path; | 602 | const target = self.base.options.target; |
| | 603 | const requires_codesig = blk: { |
| | 604 | if (self.base.options.entitlements) |_| break :blk true; |
| | 605 | if (target.cpu.arch == .aarch64 and (target.os.tag == .macos or target.abi == .simulator)) |
| | 606 | break :blk true; |
| | 607 | break :blk false; |
| | 608 | }; |
| | 609 | var codesig_offset: ?u32 = null; |
| | 610 | var codesig: ?CodeSignature = if (requires_codesig) blk: { |
| 617 | // Preallocate space for the code signature. | 611 | // Preallocate space for the code signature. |
| 618 | // We need to do this at this stage so that we have the load commands with proper values | 612 | // We need to do this at this stage so that we have the load commands with proper values |
| 619 | // written out to the file. | 613 | // written out to the file. |
| 620 | // The most important here is to have the correct vm and filesize of the __LINKEDIT segment | 614 | // The most important here is to have the correct vm and filesize of the __LINKEDIT segment |
| 621 | // where the code signature goes into. | 615 | // where the code signature goes into. |
| 622 | try self.writeCodeSignaturePadding(csig); | 616 | var codesig = CodeSignature.init(self.page_size); |
| 623 | } | 617 | codesig.code_directory.ident = self.base.options.emit.?.sub_path; |
| | 618 | if (self.base.options.entitlements) |path| { |
| | 619 | try codesig.addEntitlements(arena, path); |
| | 620 | } |
| | 621 | codesig_offset = try self.writeCodeSignaturePadding(&codesig, &ncmds, lc_writer); |
| | 622 | break :blk codesig; |
| | 623 | } else null; |
| 624 | | 624 | |
| 625 | try self.writeLoadCommands(); | 625 | var headers_buf = std.ArrayList(u8).init(arena); |
| 626 | try self.writeHeader(); | 626 | try self.writeSegmentHeaders(0, self.segments.items.len, &ncmds, headers_buf.writer()); |
| 627 | | 627 | |
| 628 | if (self.entry_addr == null and self.base.options.output_mode == .Exe) { | 628 | try self.base.file.?.pwriteAll(headers_buf.items, @sizeOf(macho.mach_header_64)); |
| 629 | log.debug("flushing. no_entry_point_found = true", .{}); | 629 | try self.base.file.?.pwriteAll(lc_buffer.items, @sizeOf(macho.mach_header_64) + headers_buf.items.len); |
| 630 | self.error_flags.no_entry_point_found = true; | | |
| 631 | } else { | | |
| 632 | log.debug("flushing. no_entry_point_found = false", .{}); | | |
| 633 | self.error_flags.no_entry_point_found = false; | | |
| 634 | } | | |
| 635 | | 630 | |
| 636 | assert(!self.load_commands_dirty); | 631 | try self.writeHeader(ncmds, @intCast(u32, lc_buffer.items.len + headers_buf.items.len)); |
| 637 | | 632 | |
| 638 | if (self.code_signature) |*csig| { | 633 | if (codesig) |*csig| { |
| 639 | try self.writeCodeSignature(csig); // code signing always comes last | 634 | try self.writeCodeSignature(csig, codesig_offset.?); // code signing always comes last |
| 640 | } | 635 | } |
| 641 | | 636 | |
| 642 | if (build_options.enable_link_snapshots) { | 637 | if (self.d_sym) |*d_sym| { |
| 643 | if (self.base.options.enable_link_snapshots) | 638 | // Flush debug symbols bundle. |
| 644 | try self.snapshotState(); | 639 | try d_sym.flushModule(self.base.allocator, self.base.options); |
| 645 | } | 640 | } |
| 646 | | 641 | |
| | 642 | // if (build_options.enable_link_snapshots) { |
| | 643 | // if (self.base.options.enable_link_snapshots) |
| | 644 | // try self.snapshotState(); |
| | 645 | // } |
| | 646 | |
| 647 | if (cache_miss) { | 647 | if (cache_miss) { |
| 648 | // Update the file with the digest. If it fails we can continue; it only | 648 | // Update the file with the digest. If it fails we can continue; it only |
| 649 | // means that the next invocation will have an unnecessary cache miss. | 649 | // means that the next invocation will have an unnecessary cache miss. |
| ... | @@ -708,6 +708,9 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) | ... | @@ -708,6 +708,9 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) |
| 708 | sub_prog_node.context.refresh(); | 708 | sub_prog_node.context.refresh(); |
| 709 | defer sub_prog_node.end(); | 709 | defer sub_prog_node.end(); |
| 710 | | 710 | |
| | 711 | const cpu_arch = self.base.options.target.cpu.arch; |
| | 712 | const os_tag = self.base.options.target.os.tag; |
| | 713 | const abi = self.base.options.target.abi; |
| 711 | const is_lib = self.base.options.output_mode == .Lib; | 714 | const is_lib = self.base.options.output_mode == .Lib; |
| 712 | const is_dyn_lib = self.base.options.link_mode == .Dynamic and is_lib; | 715 | const is_dyn_lib = self.base.options.link_mode == .Dynamic and is_lib; |
| 713 | const is_exe_or_dyn_lib = is_dyn_lib or self.base.options.output_mode == .Exe; | 716 | const is_exe_or_dyn_lib = is_dyn_lib or self.base.options.output_mode == .Exe; |
| ... | @@ -990,40 +993,6 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) | ... | @@ -990,40 +993,6 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) |
| 990 | } | 993 | } |
| 991 | } | 994 | } |
| 992 | | 995 | |
| 993 | // rpaths | | |
| 994 | var rpath_table = std.StringArrayHashMap(void).init(arena); | | |
| 995 | for (self.base.options.rpath_list) |rpath| { | | |
| 996 | if (rpath_table.contains(rpath)) continue; | | |
| 997 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( | | |
| 998 | u64, | | |
| 999 | @sizeOf(macho.rpath_command) + rpath.len + 1, | | |
| 1000 | @sizeOf(u64), | | |
| 1001 | )); | | |
| 1002 | var rpath_cmd = macho.emptyGenericCommandWithData(macho.rpath_command{ | | |
| 1003 | .cmdsize = cmdsize, | | |
| 1004 | .path = @sizeOf(macho.rpath_command), | | |
| 1005 | }); | | |
| 1006 | rpath_cmd.data = try gpa.alloc(u8, cmdsize - rpath_cmd.inner.path); | | |
| 1007 | mem.set(u8, rpath_cmd.data, 0); | | |
| 1008 | mem.copy(u8, rpath_cmd.data, rpath); | | |
| 1009 | try self.load_commands.append(gpa, .{ .rpath = rpath_cmd }); | | |
| 1010 | try rpath_table.putNoClobber(rpath, {}); | | |
| 1011 | self.load_commands_dirty = true; | | |
| 1012 | } | | |
| 1013 | | | |
| 1014 | // code signature and entitlements | | |
| 1015 | if (self.base.options.entitlements) |path| { | | |
| 1016 | if (self.code_signature) |*csig| { | | |
| 1017 | try csig.addEntitlements(gpa, path); | | |
| 1018 | csig.code_directory.ident = self.base.options.emit.?.sub_path; | | |
| 1019 | } else { | | |
| 1020 | var csig = CodeSignature.init(self.page_size); | | |
| 1021 | try csig.addEntitlements(gpa, path); | | |
| 1022 | csig.code_directory.ident = self.base.options.emit.?.sub_path; | | |
| 1023 | self.code_signature = csig; | | |
| 1024 | } | | |
| 1025 | } | | |
| 1026 | | | |
| 1027 | if (self.base.options.verbose_link) { | 996 | if (self.base.options.verbose_link) { |
| 1028 | var argv = std.ArrayList([]const u8).init(arena); | 997 | var argv = std.ArrayList([]const u8).init(arena); |
| 1029 | | 998 | |
| ... | @@ -1048,7 +1017,7 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) | ... | @@ -1048,7 +1017,7 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) |
| 1048 | try argv.append(syslibroot); | 1017 | try argv.append(syslibroot); |
| 1049 | } | 1018 | } |
| 1050 | | 1019 | |
| 1051 | for (rpath_table.keys()) |rpath| { | 1020 | for (self.base.options.rpath_list) |rpath| { |
| 1052 | try argv.append("-rpath"); | 1021 | try argv.append("-rpath"); |
| 1053 | try argv.append(rpath); | 1022 | try argv.append(rpath); |
| 1054 | } | 1023 | } |
| ... | @@ -1157,15 +1126,15 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) | ... | @@ -1157,15 +1126,15 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) |
| 1157 | var dependent_libs = std.fifo.LinearFifo(struct { | 1126 | var dependent_libs = std.fifo.LinearFifo(struct { |
| 1158 | id: Dylib.Id, | 1127 | id: Dylib.Id, |
| 1159 | parent: u16, | 1128 | parent: u16, |
| 1160 | }, .Dynamic).init(gpa); | 1129 | }, .Dynamic).init(arena); |
| 1161 | defer dependent_libs.deinit(); | 1130 | |
| 1162 | try self.parseInputFiles(positionals.items, self.base.options.sysroot, &dependent_libs); | 1131 | try self.parseInputFiles(positionals.items, self.base.options.sysroot, &dependent_libs); |
| 1163 | try self.parseAndForceLoadStaticArchives(must_link_archives.keys()); | 1132 | try self.parseAndForceLoadStaticArchives(must_link_archives.keys()); |
| 1164 | try self.parseLibs(libs.keys(), libs.values(), self.base.options.sysroot, &dependent_libs); | 1133 | try self.parseLibs(libs.keys(), libs.values(), self.base.options.sysroot, &dependent_libs); |
| 1165 | try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs); | 1134 | try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs); |
| 1166 | | 1135 | |
| 1167 | for (self.objects.items) |*object, object_id| { | 1136 | for (self.objects.items) |_, object_id| { |
| 1168 | try self.resolveSymbolsInObject(object, @intCast(u16, object_id)); | 1137 | try self.resolveSymbolsInObject(@intCast(u16, object_id)); |
| 1169 | } | 1138 | } |
| 1170 | | 1139 | |
| 1171 | try self.resolveSymbolsInArchives(); | 1140 | try self.resolveSymbolsInArchives(); |
| ... | @@ -1175,7 +1144,6 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) | ... | @@ -1175,7 +1144,6 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) |
| 1175 | try self.resolveSymbolsInDylibs(); | 1144 | try self.resolveSymbolsInDylibs(); |
| 1176 | try self.createMhExecuteHeaderSymbol(); | 1145 | try self.createMhExecuteHeaderSymbol(); |
| 1177 | try self.createDsoHandleSymbol(); | 1146 | try self.createDsoHandleSymbol(); |
| 1178 | try self.addCodeSignatureLC(); | | |
| 1179 | try self.resolveSymbolsAtLoading(); | 1147 | try self.resolveSymbolsAtLoading(); |
| 1180 | | 1148 | |
| 1181 | if (self.unresolved.count() > 0) { | 1149 | if (self.unresolved.count() > 0) { |
| ... | @@ -1206,41 +1174,79 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) | ... | @@ -1206,41 +1174,79 @@ fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) |
| 1206 | | 1174 | |
| 1207 | if (build_options.enable_logging) { | 1175 | if (build_options.enable_logging) { |
| 1208 | self.logSymtab(); | 1176 | self.logSymtab(); |
| 1209 | self.logSectionOrdinals(); | | |
| 1210 | self.logAtoms(); | 1177 | self.logAtoms(); |
| 1211 | } | 1178 | } |
| 1212 | | 1179 | |
| 1213 | try self.writeAtomsOneShot(); | 1180 | try self.writeAtomsOneShot(); |
| 1214 | | 1181 | |
| 1215 | if (self.rustc_section_index) |id| { | 1182 | if (self.rustc_section_index) |id| { |
| 1216 | const sect = self.getSectionPtr(.{ | 1183 | const header = &self.sections.items(.header)[id]; |
| 1217 | .seg = self.data_segment_cmd_index.?, | 1184 | header.size = self.rustc_section_size; |
| 1218 | .sect = id, | 1185 | } |
| | 1186 | |
| | 1187 | var lc_buffer = std.ArrayList(u8).init(arena); |
| | 1188 | const lc_writer = lc_buffer.writer(); |
| | 1189 | var ncmds: u32 = 0; |
| | 1190 | |
| | 1191 | try self.writeLinkeditSegmentData(&ncmds, lc_writer); |
| | 1192 | try writeDylinkerLC(&ncmds, lc_writer); |
| | 1193 | try self.writeMainLC(&ncmds, lc_writer); |
| | 1194 | try self.writeDylibIdLC(&ncmds, lc_writer); |
| | 1195 | try self.writeRpathLCs(&ncmds, lc_writer); |
| | 1196 | |
| | 1197 | { |
| | 1198 | try lc_writer.writeStruct(macho.source_version_command{ |
| | 1199 | .cmdsize = @sizeOf(macho.source_version_command), |
| | 1200 | .version = 0x0, |
| 1219 | }); | 1201 | }); |
| 1220 | sect.size = self.rustc_section_size; | 1202 | ncmds += 1; |
| | 1203 | } |
| | 1204 | |
| | 1205 | try self.writeBuildVersionLC(&ncmds, lc_writer); |
| | 1206 | |
| | 1207 | { |
| | 1208 | var uuid_lc = macho.uuid_command{ |
| | 1209 | .cmdsize = @sizeOf(macho.uuid_command), |
| | 1210 | .uuid = undefined, |
| | 1211 | }; |
| | 1212 | std.crypto.random.bytes(&uuid_lc.uuid); |
| | 1213 | try lc_writer.writeStruct(uuid_lc); |
| | 1214 | ncmds += 1; |
| 1221 | } | 1215 | } |
| 1222 | | 1216 | |
| 1223 | try self.setEntryPoint(); | 1217 | try self.writeLoadDylibLCs(&ncmds, lc_writer); |
| 1224 | try self.writeLinkeditSegment(); | | |
| 1225 | | 1218 | |
| 1226 | if (self.code_signature) |*csig| { | 1219 | const requires_codesig = blk: { |
| 1227 | csig.clear(gpa); | 1220 | if (self.base.options.entitlements) |_| break :blk true; |
| 1228 | csig.code_directory.ident = self.base.options.emit.?.sub_path; | 1221 | if (cpu_arch == .aarch64 and (os_tag == .macos or abi == .simulator)) break :blk true; |
| | 1222 | break :blk false; |
| | 1223 | }; |
| | 1224 | var codesig_offset: ?u32 = null; |
| | 1225 | var codesig: ?CodeSignature = if (requires_codesig) blk: { |
| 1229 | // Preallocate space for the code signature. | 1226 | // Preallocate space for the code signature. |
| 1230 | // We need to do this at this stage so that we have the load commands with proper values | 1227 | // We need to do this at this stage so that we have the load commands with proper values |
| 1231 | // written out to the file. | 1228 | // written out to the file. |
| 1232 | // The most important here is to have the correct vm and filesize of the __LINKEDIT segment | 1229 | // The most important here is to have the correct vm and filesize of the __LINKEDIT segment |
| 1233 | // where the code signature goes into. | 1230 | // where the code signature goes into. |
| 1234 | try self.writeCodeSignaturePadding(csig); | 1231 | var codesig = CodeSignature.init(self.page_size); |
| 1235 | } | 1232 | codesig.code_directory.ident = self.base.options.emit.?.sub_path; |
| | 1233 | if (self.base.options.entitlements) |path| { |
| | 1234 | try codesig.addEntitlements(arena, path); |
| | 1235 | } |
| | 1236 | codesig_offset = try self.writeCodeSignaturePadding(&codesig, &ncmds, lc_writer); |
| | 1237 | break :blk codesig; |
| | 1238 | } else null; |
| 1236 | | 1239 | |
| 1237 | try self.writeLoadCommands(); | 1240 | var headers_buf = std.ArrayList(u8).init(arena); |
| 1238 | try self.writeHeader(); | 1241 | try self.writeSegmentHeaders(0, self.segments.items.len, &ncmds, headers_buf.writer()); |
| 1239 | | 1242 | |
| 1240 | assert(!self.load_commands_dirty); | 1243 | try self.base.file.?.pwriteAll(headers_buf.items, @sizeOf(macho.mach_header_64)); |
| | 1244 | try self.base.file.?.pwriteAll(lc_buffer.items, @sizeOf(macho.mach_header_64) + headers_buf.items.len); |
| 1241 | | 1245 | |
| 1242 | if (self.code_signature) |*csig| { | 1246 | try self.writeHeader(ncmds, @intCast(u32, lc_buffer.items.len + headers_buf.items.len)); |
| 1243 | try self.writeCodeSignature(csig); // code signing always comes last | 1247 | |
| | 1248 | if (codesig) |*csig| { |
| | 1249 | try self.writeCodeSignature(csig, codesig_offset.?); // code signing always comes last |
| 1244 | } | 1250 | } |
| 1245 | } | 1251 | } |
| 1246 | | 1252 | |
| ... | @@ -1395,66 +1401,77 @@ fn resolveFramework( | ... | @@ -1395,66 +1401,77 @@ fn resolveFramework( |
| 1395 | } | 1401 | } |
| 1396 | | 1402 | |
| 1397 | fn parseObject(self: *MachO, path: []const u8) !bool { | 1403 | fn parseObject(self: *MachO, path: []const u8) !bool { |
| | 1404 | const gpa = self.base.allocator; |
| 1398 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { | 1405 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { |
| 1399 | error.FileNotFound => return false, | 1406 | error.FileNotFound => return false, |
| 1400 | else => |e| return e, | 1407 | else => |e| return e, |
| 1401 | }; | 1408 | }; |
| 1402 | errdefer file.close(); | 1409 | defer file.close(); |
| 1403 | | | |
| 1404 | const name = try self.base.allocator.dupe(u8, path); | | |
| 1405 | errdefer self.base.allocator.free(name); | | |
| 1406 | | 1410 | |
| | 1411 | const name = try gpa.dupe(u8, path); |
| | 1412 | errdefer gpa.free(name); |
| | 1413 | const cpu_arch = self.base.options.target.cpu.arch; |
| 1407 | const mtime: u64 = mtime: { | 1414 | const mtime: u64 = mtime: { |
| 1408 | const stat = file.stat() catch break :mtime 0; | 1415 | const stat = file.stat() catch break :mtime 0; |
| 1409 | break :mtime @intCast(u64, @divFloor(stat.mtime, 1_000_000_000)); | 1416 | break :mtime @intCast(u64, @divFloor(stat.mtime, 1_000_000_000)); |
| 1410 | }; | 1417 | }; |
| | 1418 | const file_stat = try file.stat(); |
| | 1419 | const file_size = math.cast(usize, file_stat.size) orelse return error.Overflow; |
| | 1420 | const contents = try file.readToEndAllocOptions(gpa, file_size, file_size, @alignOf(u64), null); |
| 1411 | | 1421 | |
| 1412 | var object = Object{ | 1422 | var object = Object{ |
| 1413 | .name = name, | 1423 | .name = name, |
| 1414 | .file = file, | | |
| 1415 | .mtime = mtime, | 1424 | .mtime = mtime, |
| | 1425 | .contents = contents, |
| 1416 | }; | 1426 | }; |
| 1417 | | 1427 | |
| 1418 | object.parse(self.base.allocator, self.base.options.target.cpu.arch) catch |err| switch (err) { | 1428 | object.parse(gpa, cpu_arch) catch |err| switch (err) { |
| 1419 | error.EndOfStream, error.NotObject => { | 1429 | error.EndOfStream, error.NotObject => { |
| 1420 | object.deinit(self.base.allocator); | 1430 | object.deinit(gpa); |
| 1421 | return false; | 1431 | return false; |
| 1422 | }, | 1432 | }, |
| 1423 | else => |e| return e, | 1433 | else => |e| return e, |
| 1424 | }; | 1434 | }; |
| 1425 | | 1435 | |
| 1426 | try self.objects.append(self.base.allocator, object); | 1436 | try self.objects.append(gpa, object); |
| 1427 | | 1437 | |
| 1428 | return true; | 1438 | return true; |
| 1429 | } | 1439 | } |
| 1430 | | 1440 | |
| 1431 | fn parseArchive(self: *MachO, path: []const u8, force_load: bool) !bool { | 1441 | fn parseArchive(self: *MachO, path: []const u8, force_load: bool) !bool { |
| | 1442 | const gpa = self.base.allocator; |
| 1432 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { | 1443 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { |
| 1433 | error.FileNotFound => return false, | 1444 | error.FileNotFound => return false, |
| 1434 | else => |e| return e, | 1445 | else => |e| return e, |
| 1435 | }; | 1446 | }; |
| 1436 | errdefer file.close(); | 1447 | errdefer file.close(); |
| 1437 | | 1448 | |
| 1438 | const name = try self.base.allocator.dupe(u8, path); | 1449 | const name = try gpa.dupe(u8, path); |
| 1439 | errdefer self.base.allocator.free(name); | 1450 | errdefer gpa.free(name); |
| | 1451 | const cpu_arch = self.base.options.target.cpu.arch; |
| | 1452 | const reader = file.reader(); |
| | 1453 | const fat_offset = try fat.getLibraryOffset(reader, cpu_arch); |
| | 1454 | try reader.context.seekTo(fat_offset); |
| 1440 | | 1455 | |
| 1441 | var archive = Archive{ | 1456 | var archive = Archive{ |
| 1442 | .name = name, | 1457 | .name = name, |
| | 1458 | .fat_offset = fat_offset, |
| 1443 | .file = file, | 1459 | .file = file, |
| 1444 | }; | 1460 | }; |
| 1445 | | 1461 | |
| 1446 | archive.parse(self.base.allocator, self.base.options.target.cpu.arch) catch |err| switch (err) { | 1462 | archive.parse(gpa, reader) catch |err| switch (err) { |
| 1447 | error.EndOfStream, error.NotArchive => { | 1463 | error.EndOfStream, error.NotArchive => { |
| 1448 | archive.deinit(self.base.allocator); | 1464 | archive.deinit(gpa); |
| 1449 | return false; | 1465 | return false; |
| 1450 | }, | 1466 | }, |
| 1451 | else => |e| return e, | 1467 | else => |e| return e, |
| 1452 | }; | 1468 | }; |
| 1453 | | 1469 | |
| 1454 | if (force_load) { | 1470 | if (force_load) { |
| 1455 | defer archive.deinit(self.base.allocator); | 1471 | defer archive.deinit(gpa); |
| | 1472 | defer file.close(); |
| 1456 | // Get all offsets from the ToC | 1473 | // Get all offsets from the ToC |
| 1457 | var offsets = std.AutoArrayHashMap(u32, void).init(self.base.allocator); | 1474 | var offsets = std.AutoArrayHashMap(u32, void).init(gpa); |
| 1458 | defer offsets.deinit(); | 1475 | defer offsets.deinit(); |
| 1459 | for (archive.toc.values()) |offs| { | 1476 | for (archive.toc.values()) |offs| { |
| 1460 | for (offs.items) |off| { | 1477 | for (offs.items) |off| { |
| ... | @@ -1462,15 +1479,11 @@ fn parseArchive(self: *MachO, path: []const u8, force_load: bool) !bool { | ... | @@ -1462,15 +1479,11 @@ fn parseArchive(self: *MachO, path: []const u8, force_load: bool) !bool { |
| 1462 | } | 1479 | } |
| 1463 | } | 1480 | } |
| 1464 | for (offsets.keys()) |off| { | 1481 | for (offsets.keys()) |off| { |
| 1465 | const object = try self.objects.addOne(self.base.allocator); | 1482 | const object = try archive.parseObject(gpa, cpu_arch, off); |
| 1466 | object.* = try archive.parseObject( | 1483 | try self.objects.append(gpa, object); |
| 1467 | self.base.allocator, | | |
| 1468 | self.base.options.target.cpu.arch, | | |
| 1469 | off, | | |
| 1470 | ); | | |
| 1471 | } | 1484 | } |
| 1472 | } else { | 1485 | } else { |
| 1473 | try self.archives.append(self.base.allocator, archive); | 1486 | try self.archives.append(gpa, archive); |
| 1474 | } | 1487 | } |
| 1475 | | 1488 | |
| 1476 | return true; | 1489 | return true; |
| ... | @@ -1481,6 +1494,7 @@ const ParseDylibError = error{ | ... | @@ -1481,6 +1494,7 @@ const ParseDylibError = error{ |
| 1481 | EmptyStubFile, | 1494 | EmptyStubFile, |
| 1482 | MismatchedCpuArchitecture, | 1495 | MismatchedCpuArchitecture, |
| 1483 | UnsupportedCpuArchitecture, | 1496 | UnsupportedCpuArchitecture, |
| | 1497 | EndOfStream, |
| 1484 | } || fs.File.OpenError || std.os.PReadError || Dylib.Id.ParseError; | 1498 | } || fs.File.OpenError || std.os.PReadError || Dylib.Id.ParseError; |
| 1485 | | 1499 | |
| 1486 | const DylibCreateOpts = struct { | 1500 | const DylibCreateOpts = struct { |
| ... | @@ -1497,43 +1511,52 @@ pub fn parseDylib( | ... | @@ -1497,43 +1511,52 @@ pub fn parseDylib( |
| 1497 | dependent_libs: anytype, | 1511 | dependent_libs: anytype, |
| 1498 | opts: DylibCreateOpts, | 1512 | opts: DylibCreateOpts, |
| 1499 | ) ParseDylibError!bool { | 1513 | ) ParseDylibError!bool { |
| | 1514 | const gpa = self.base.allocator; |
| 1500 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { | 1515 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { |
| 1501 | error.FileNotFound => return false, | 1516 | error.FileNotFound => return false, |
| 1502 | else => |e| return e, | 1517 | else => |e| return e, |
| 1503 | }; | 1518 | }; |
| 1504 | errdefer file.close(); | 1519 | defer file.close(); |
| | 1520 | |
| | 1521 | const cpu_arch = self.base.options.target.cpu.arch; |
| | 1522 | const file_stat = try file.stat(); |
| | 1523 | var file_size = math.cast(usize, file_stat.size) orelse return error.Overflow; |
| | 1524 | |
| | 1525 | const reader = file.reader(); |
| | 1526 | const fat_offset = try fat.getLibraryOffset(reader, cpu_arch); |
| | 1527 | try file.seekTo(fat_offset); |
| | 1528 | file_size -= fat_offset; |
| 1505 | | 1529 | |
| 1506 | const name = try self.base.allocator.dupe(u8, path); | 1530 | const contents = try file.readToEndAllocOptions(gpa, file_size, file_size, @alignOf(u64), null); |
| 1507 | errdefer self.base.allocator.free(name); | 1531 | defer gpa.free(contents); |
| 1508 | | 1532 | |
| 1509 | const dylib_id = @intCast(u16, self.dylibs.items.len); | 1533 | const dylib_id = @intCast(u16, self.dylibs.items.len); |
| 1510 | var dylib = Dylib{ | 1534 | var dylib = Dylib{ .weak = opts.weak }; |
| 1511 | .name = name, | | |
| 1512 | .file = file, | | |
| 1513 | .weak = opts.weak, | | |
| 1514 | }; | | |
| 1515 | | 1535 | |
| 1516 | dylib.parse( | 1536 | dylib.parseFromBinary( |
| 1517 | self.base.allocator, | 1537 | gpa, |
| 1518 | self.base.options.target.cpu.arch, | 1538 | cpu_arch, |
| 1519 | dylib_id, | 1539 | dylib_id, |
| 1520 | dependent_libs, | 1540 | dependent_libs, |
| | 1541 | path, |
| | 1542 | contents, |
| 1521 | ) catch |err| switch (err) { | 1543 | ) catch |err| switch (err) { |
| 1522 | error.EndOfStream, error.NotDylib => { | 1544 | error.EndOfStream, error.NotDylib => { |
| 1523 | try file.seekTo(0); | 1545 | try file.seekTo(0); |
| 1524 | | 1546 | |
| 1525 | var lib_stub = LibStub.loadFromFile(self.base.allocator, file) catch { | 1547 | var lib_stub = LibStub.loadFromFile(gpa, file) catch { |
| 1526 | dylib.deinit(self.base.allocator); | 1548 | dylib.deinit(gpa); |
| 1527 | return false; | 1549 | return false; |
| 1528 | }; | 1550 | }; |
| 1529 | defer lib_stub.deinit(); | 1551 | defer lib_stub.deinit(); |
| 1530 | | 1552 | |
| 1531 | try dylib.parseFromStub( | 1553 | try dylib.parseFromStub( |
| 1532 | self.base.allocator, | 1554 | gpa, |
| 1533 | self.base.options.target, | 1555 | self.base.options.target, |
| 1534 | lib_stub, | 1556 | lib_stub, |
| 1535 | dylib_id, | 1557 | dylib_id, |
| 1536 | dependent_libs, | 1558 | dependent_libs, |
| | 1559 | path, |
| 1537 | ); | 1560 | ); |
| 1538 | }, | 1561 | }, |
| 1539 | else => |e| return e, | 1562 | else => |e| return e, |
| ... | @@ -1547,13 +1570,13 @@ pub fn parseDylib( | ... | @@ -1547,13 +1570,13 @@ pub fn parseDylib( |
| 1547 | log.warn(" dylib version: {}", .{dylib.id.?.current_version}); | 1570 | log.warn(" dylib version: {}", .{dylib.id.?.current_version}); |
| 1548 | | 1571 | |
| 1549 | // TODO maybe this should be an error and facilitate auto-cleanup? | 1572 | // TODO maybe this should be an error and facilitate auto-cleanup? |
| 1550 | dylib.deinit(self.base.allocator); | 1573 | dylib.deinit(gpa); |
| 1551 | return false; | 1574 | return false; |
| 1552 | } | 1575 | } |
| 1553 | } | 1576 | } |
| 1554 | | 1577 | |
| 1555 | try self.dylibs.append(self.base.allocator, dylib); | 1578 | try self.dylibs.append(gpa, dylib); |
| 1556 | try self.dylibs_map.putNoClobber(self.base.allocator, dylib.id.?.name, dylib_id); | 1579 | try self.dylibs_map.putNoClobber(gpa, dylib.id.?.name, dylib_id); |
| 1557 | | 1580 | |
| 1558 | const should_link_dylib_even_if_unreachable = blk: { | 1581 | const should_link_dylib_even_if_unreachable = blk: { |
| 1559 | if (self.base.options.dead_strip_dylibs and !opts.needed) break :blk false; | 1582 | if (self.base.options.dead_strip_dylibs and !opts.needed) break :blk false; |
| ... | @@ -1561,8 +1584,7 @@ pub fn parseDylib( | ... | @@ -1561,8 +1584,7 @@ pub fn parseDylib( |
| 1561 | }; | 1584 | }; |
| 1562 | | 1585 | |
| 1563 | if (should_link_dylib_even_if_unreachable) { | 1586 | if (should_link_dylib_even_if_unreachable) { |
| 1564 | try self.addLoadDylibLC(dylib_id); | 1587 | try self.referenced_dylibs.putNoClobber(gpa, dylib_id, {}); |
| 1565 | try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {}); | | |
| 1566 | } | 1588 | } |
| 1567 | | 1589 | |
| 1568 | return true; | 1590 | return true; |
| ... | @@ -1572,10 +1594,8 @@ fn parseInputFiles(self: *MachO, files: []const []const u8, syslibroot: ?[]const | ... | @@ -1572,10 +1594,8 @@ fn parseInputFiles(self: *MachO, files: []const []const u8, syslibroot: ?[]const |
| 1572 | for (files) |file_name| { | 1594 | for (files) |file_name| { |
| 1573 | const full_path = full_path: { | 1595 | const full_path = full_path: { |
| 1574 | var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; | 1596 | var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; |
| 1575 | const path = try fs.realpath(file_name, &buffer); | 1597 | break :full_path try fs.realpath(file_name, &buffer); |
| 1576 | break :full_path try self.base.allocator.dupe(u8, path); | | |
| 1577 | }; | 1598 | }; |
| 1578 | defer self.base.allocator.free(full_path); | | |
| 1579 | log.debug("parsing input file path '{s}'", .{full_path}); | 1599 | log.debug("parsing input file path '{s}'", .{full_path}); |
| 1580 | | 1600 | |
| 1581 | if (try self.parseObject(full_path)) continue; | 1601 | if (try self.parseObject(full_path)) continue; |
| ... | @@ -1592,10 +1612,8 @@ fn parseAndForceLoadStaticArchives(self: *MachO, files: []const []const u8) !voi | ... | @@ -1592,10 +1612,8 @@ fn parseAndForceLoadStaticArchives(self: *MachO, files: []const []const u8) !voi |
| 1592 | for (files) |file_name| { | 1612 | for (files) |file_name| { |
| 1593 | const full_path = full_path: { | 1613 | const full_path = full_path: { |
| 1594 | var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; | 1614 | var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; |
| 1595 | const path = try fs.realpath(file_name, &buffer); | 1615 | break :full_path try fs.realpath(file_name, &buffer); |
| 1596 | break :full_path try self.base.allocator.dupe(u8, path); | | |
| 1597 | }; | 1616 | }; |
| 1598 | defer self.base.allocator.free(full_path); | | |
| 1599 | log.debug("parsing and force loading static archive '{s}'", .{full_path}); | 1617 | log.debug("parsing and force loading static archive '{s}'", .{full_path}); |
| 1600 | | 1618 | |
| 1601 | if (try self.parseArchive(full_path, true)) continue; | 1619 | if (try self.parseArchive(full_path, true)) continue; |
| ... | @@ -1669,24 +1687,10 @@ fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: any | ... | @@ -1669,24 +1687,10 @@ fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: any |
| 1669 | } | 1687 | } |
| 1670 | } | 1688 | } |
| 1671 | | 1689 | |
| 1672 | pub const MatchingSection = struct { | 1690 | pub fn getOutputSection(self: *MachO, sect: macho.section_64) !?u8 { |
| 1673 | seg: u16, | | |
| 1674 | sect: u16, | | |
| 1675 | | | |
| 1676 | pub fn eql(this: MatchingSection, other: struct { | | |
| 1677 | seg: ?u16, | | |
| 1678 | sect: ?u16, | | |
| 1679 | }) bool { | | |
| 1680 | const seg = other.seg orelse return false; | | |
| 1681 | const sect = other.sect orelse return false; | | |
| 1682 | return this.seg == seg and this.sect == sect; | | |
| 1683 | } | | |
| 1684 | }; | | |
| 1685 | | | |
| 1686 | pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSection { | | |
| 1687 | const segname = sect.segName(); | 1691 | const segname = sect.segName(); |
| 1688 | const sectname = sect.sectName(); | 1692 | const sectname = sect.sectName(); |
| 1689 | const res: ?MatchingSection = blk: { | 1693 | const res: ?u8 = blk: { |
| 1690 | switch (sect.type_()) { | 1694 | switch (sect.type_()) { |
| 1691 | macho.S_4BYTE_LITERALS, macho.S_8BYTE_LITERALS, macho.S_16BYTE_LITERALS => { | 1695 | macho.S_4BYTE_LITERALS, macho.S_8BYTE_LITERALS, macho.S_16BYTE_LITERALS => { |
| 1692 | if (self.text_const_section_index == null) { | 1696 | if (self.text_const_section_index == null) { |
| ... | @@ -1698,11 +1702,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1698,11 +1702,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1698 | .{}, | 1702 | .{}, |
| 1699 | ); | 1703 | ); |
| 1700 | } | 1704 | } |
| 1701 | | 1705 | break :blk self.text_const_section_index.?; |
| 1702 | break :blk .{ | | |
| 1703 | .seg = self.text_segment_cmd_index.?, | | |
| 1704 | .sect = self.text_const_section_index.?, | | |
| 1705 | }; | | |
| 1706 | }, | 1706 | }, |
| 1707 | macho.S_CSTRING_LITERALS => { | 1707 | macho.S_CSTRING_LITERALS => { |
| 1708 | if (mem.eql(u8, sectname, "__objc_methname")) { | 1708 | if (mem.eql(u8, sectname, "__objc_methname")) { |
| ... | @@ -1717,11 +1717,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1717,11 +1717,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1717 | .{}, | 1717 | .{}, |
| 1718 | ); | 1718 | ); |
| 1719 | } | 1719 | } |
| 1720 | | 1720 | break :blk self.objc_methname_section_index.?; |
| 1721 | break :blk .{ | | |
| 1722 | .seg = self.text_segment_cmd_index.?, | | |
| 1723 | .sect = self.objc_methname_section_index.?, | | |
| 1724 | }; | | |
| 1725 | } else if (mem.eql(u8, sectname, "__objc_methtype")) { | 1721 | } else if (mem.eql(u8, sectname, "__objc_methtype")) { |
| 1726 | if (self.objc_methtype_section_index == null) { | 1722 | if (self.objc_methtype_section_index == null) { |
| 1727 | self.objc_methtype_section_index = try self.initSection( | 1723 | self.objc_methtype_section_index = try self.initSection( |
| ... | @@ -1732,11 +1728,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1732,11 +1728,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1732 | .{}, | 1728 | .{}, |
| 1733 | ); | 1729 | ); |
| 1734 | } | 1730 | } |
| 1735 | | 1731 | break :blk self.objc_methtype_section_index.?; |
| 1736 | break :blk .{ | | |
| 1737 | .seg = self.text_segment_cmd_index.?, | | |
| 1738 | .sect = self.objc_methtype_section_index.?, | | |
| 1739 | }; | | |
| 1740 | } else if (mem.eql(u8, sectname, "__objc_classname")) { | 1732 | } else if (mem.eql(u8, sectname, "__objc_classname")) { |
| 1741 | if (self.objc_classname_section_index == null) { | 1733 | if (self.objc_classname_section_index == null) { |
| 1742 | self.objc_classname_section_index = try self.initSection( | 1734 | self.objc_classname_section_index = try self.initSection( |
| ... | @@ -1747,11 +1739,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1747,11 +1739,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1747 | .{}, | 1739 | .{}, |
| 1748 | ); | 1740 | ); |
| 1749 | } | 1741 | } |
| 1750 | | 1742 | break :blk self.objc_classname_section_index.?; |
| 1751 | break :blk .{ | | |
| 1752 | .seg = self.text_segment_cmd_index.?, | | |
| 1753 | .sect = self.objc_classname_section_index.?, | | |
| 1754 | }; | | |
| 1755 | } | 1743 | } |
| 1756 | | 1744 | |
| 1757 | if (self.cstring_section_index == null) { | 1745 | if (self.cstring_section_index == null) { |
| ... | @@ -1765,11 +1753,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1765,11 +1753,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1765 | }, | 1753 | }, |
| 1766 | ); | 1754 | ); |
| 1767 | } | 1755 | } |
| 1768 | | 1756 | break :blk self.cstring_section_index.?; |
| 1769 | break :blk .{ | | |
| 1770 | .seg = self.text_segment_cmd_index.?, | | |
| 1771 | .sect = self.cstring_section_index.?, | | |
| 1772 | }; | | |
| 1773 | }, | 1757 | }, |
| 1774 | macho.S_LITERAL_POINTERS => { | 1758 | macho.S_LITERAL_POINTERS => { |
| 1775 | if (mem.eql(u8, segname, "__DATA") and mem.eql(u8, sectname, "__objc_selrefs")) { | 1759 | if (mem.eql(u8, segname, "__DATA") and mem.eql(u8, sectname, "__objc_selrefs")) { |
| ... | @@ -1784,11 +1768,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1784,11 +1768,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1784 | }, | 1768 | }, |
| 1785 | ); | 1769 | ); |
| 1786 | } | 1770 | } |
| 1787 | | 1771 | break :blk self.objc_selrefs_section_index.?; |
| 1788 | break :blk .{ | | |
| 1789 | .seg = self.data_segment_cmd_index.?, | | |
| 1790 | .sect = self.objc_selrefs_section_index.?, | | |
| 1791 | }; | | |
| 1792 | } else { | 1772 | } else { |
| 1793 | // TODO investigate | 1773 | // TODO investigate |
| 1794 | break :blk null; | 1774 | break :blk null; |
| ... | @@ -1806,11 +1786,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1806,11 +1786,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1806 | }, | 1786 | }, |
| 1807 | ); | 1787 | ); |
| 1808 | } | 1788 | } |
| 1809 | | 1789 | break :blk self.mod_init_func_section_index.?; |
| 1810 | break :blk .{ | | |
| 1811 | .seg = self.data_const_segment_cmd_index.?, | | |
| 1812 | .sect = self.mod_init_func_section_index.?, | | |
| 1813 | }; | | |
| 1814 | }, | 1790 | }, |
| 1815 | macho.S_MOD_TERM_FUNC_POINTERS => { | 1791 | macho.S_MOD_TERM_FUNC_POINTERS => { |
| 1816 | if (self.mod_term_func_section_index == null) { | 1792 | if (self.mod_term_func_section_index == null) { |
| ... | @@ -1824,11 +1800,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1824,11 +1800,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1824 | }, | 1800 | }, |
| 1825 | ); | 1801 | ); |
| 1826 | } | 1802 | } |
| 1827 | | 1803 | break :blk self.mod_term_func_section_index.?; |
| 1828 | break :blk .{ | | |
| 1829 | .seg = self.data_const_segment_cmd_index.?, | | |
| 1830 | .sect = self.mod_term_func_section_index.?, | | |
| 1831 | }; | | |
| 1832 | }, | 1804 | }, |
| 1833 | macho.S_ZEROFILL => { | 1805 | macho.S_ZEROFILL => { |
| 1834 | if (self.bss_section_index == null) { | 1806 | if (self.bss_section_index == null) { |
| ... | @@ -1842,11 +1814,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1842,11 +1814,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1842 | }, | 1814 | }, |
| 1843 | ); | 1815 | ); |
| 1844 | } | 1816 | } |
| 1845 | | 1817 | break :blk self.bss_section_index.?; |
| 1846 | break :blk .{ | | |
| 1847 | .seg = self.data_segment_cmd_index.?, | | |
| 1848 | .sect = self.bss_section_index.?, | | |
| 1849 | }; | | |
| 1850 | }, | 1818 | }, |
| 1851 | macho.S_THREAD_LOCAL_VARIABLES => { | 1819 | macho.S_THREAD_LOCAL_VARIABLES => { |
| 1852 | if (self.tlv_section_index == null) { | 1820 | if (self.tlv_section_index == null) { |
| ... | @@ -1860,11 +1828,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1860,11 +1828,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1860 | }, | 1828 | }, |
| 1861 | ); | 1829 | ); |
| 1862 | } | 1830 | } |
| 1863 | | 1831 | break :blk self.tlv_section_index.?; |
| 1864 | break :blk .{ | | |
| 1865 | .seg = self.data_segment_cmd_index.?, | | |
| 1866 | .sect = self.tlv_section_index.?, | | |
| 1867 | }; | | |
| 1868 | }, | 1832 | }, |
| 1869 | macho.S_THREAD_LOCAL_VARIABLE_POINTERS => { | 1833 | macho.S_THREAD_LOCAL_VARIABLE_POINTERS => { |
| 1870 | if (self.tlv_ptrs_section_index == null) { | 1834 | if (self.tlv_ptrs_section_index == null) { |
| ... | @@ -1878,11 +1842,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1878,11 +1842,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1878 | }, | 1842 | }, |
| 1879 | ); | 1843 | ); |
| 1880 | } | 1844 | } |
| 1881 | | 1845 | break :blk self.tlv_ptrs_section_index.?; |
| 1882 | break :blk .{ | | |
| 1883 | .seg = self.data_segment_cmd_index.?, | | |
| 1884 | .sect = self.tlv_ptrs_section_index.?, | | |
| 1885 | }; | | |
| 1886 | }, | 1846 | }, |
| 1887 | macho.S_THREAD_LOCAL_REGULAR => { | 1847 | macho.S_THREAD_LOCAL_REGULAR => { |
| 1888 | if (self.tlv_data_section_index == null) { | 1848 | if (self.tlv_data_section_index == null) { |
| ... | @@ -1896,11 +1856,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1896,11 +1856,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1896 | }, | 1856 | }, |
| 1897 | ); | 1857 | ); |
| 1898 | } | 1858 | } |
| 1899 | | 1859 | break :blk self.tlv_data_section_index.?; |
| 1900 | break :blk .{ | | |
| 1901 | .seg = self.data_segment_cmd_index.?, | | |
| 1902 | .sect = self.tlv_data_section_index.?, | | |
| 1903 | }; | | |
| 1904 | }, | 1860 | }, |
| 1905 | macho.S_THREAD_LOCAL_ZEROFILL => { | 1861 | macho.S_THREAD_LOCAL_ZEROFILL => { |
| 1906 | if (self.tlv_bss_section_index == null) { | 1862 | if (self.tlv_bss_section_index == null) { |
| ... | @@ -1914,11 +1870,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1914,11 +1870,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1914 | }, | 1870 | }, |
| 1915 | ); | 1871 | ); |
| 1916 | } | 1872 | } |
| 1917 | | 1873 | break :blk self.tlv_bss_section_index.?; |
| 1918 | break :blk .{ | | |
| 1919 | .seg = self.data_segment_cmd_index.?, | | |
| 1920 | .sect = self.tlv_bss_section_index.?, | | |
| 1921 | }; | | |
| 1922 | }, | 1874 | }, |
| 1923 | macho.S_COALESCED => { | 1875 | macho.S_COALESCED => { |
| 1924 | if (mem.eql(u8, "__TEXT", segname) and mem.eql(u8, "__eh_frame", sectname)) { | 1876 | if (mem.eql(u8, "__TEXT", segname) and mem.eql(u8, "__eh_frame", sectname)) { |
| ... | @@ -1933,11 +1885,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1933,11 +1885,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1933 | .{}, | 1885 | .{}, |
| 1934 | ); | 1886 | ); |
| 1935 | } | 1887 | } |
| 1936 | | 1888 | break :blk self.eh_frame_section_index.?; |
| 1937 | break :blk .{ | | |
| 1938 | .seg = self.text_segment_cmd_index.?, | | |
| 1939 | .sect = self.eh_frame_section_index.?, | | |
| 1940 | }; | | |
| 1941 | } | 1889 | } |
| 1942 | | 1890 | |
| 1943 | // TODO audit this: is this the right mapping? | 1891 | // TODO audit this: is this the right mapping? |
| ... | @@ -1951,10 +1899,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1951,10 +1899,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1951 | ); | 1899 | ); |
| 1952 | } | 1900 | } |
| 1953 | | 1901 | |
| 1954 | break :blk .{ | 1902 | break :blk self.data_const_section_index.?; |
| 1955 | .seg = self.data_const_segment_cmd_index.?, | | |
| 1956 | .sect = self.data_const_section_index.?, | | |
| 1957 | }; | | |
| 1958 | }, | 1903 | }, |
| 1959 | macho.S_REGULAR => { | 1904 | macho.S_REGULAR => { |
| 1960 | if (sect.isCode()) { | 1905 | if (sect.isCode()) { |
| ... | @@ -1971,11 +1916,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1971,11 +1916,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1971 | }, | 1916 | }, |
| 1972 | ); | 1917 | ); |
| 1973 | } | 1918 | } |
| 1974 | | 1919 | break :blk self.text_section_index.?; |
| 1975 | break :blk .{ | | |
| 1976 | .seg = self.text_segment_cmd_index.?, | | |
| 1977 | .sect = self.text_section_index.?, | | |
| 1978 | }; | | |
| 1979 | } | 1920 | } |
| 1980 | if (sect.isDebug()) { | 1921 | if (sect.isDebug()) { |
| 1981 | // TODO debug attributes | 1922 | // TODO debug attributes |
| ... | @@ -1998,11 +1939,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -1998,11 +1939,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 1998 | .{}, | 1939 | .{}, |
| 1999 | ); | 1940 | ); |
| 2000 | } | 1941 | } |
| 2001 | | 1942 | break :blk self.ustring_section_index.?; |
| 2002 | break :blk .{ | | |
| 2003 | .seg = self.text_segment_cmd_index.?, | | |
| 2004 | .sect = self.ustring_section_index.?, | | |
| 2005 | }; | | |
| 2006 | } else if (mem.eql(u8, sectname, "__gcc_except_tab")) { | 1943 | } else if (mem.eql(u8, sectname, "__gcc_except_tab")) { |
| 2007 | if (self.gcc_except_tab_section_index == null) { | 1944 | if (self.gcc_except_tab_section_index == null) { |
| 2008 | self.gcc_except_tab_section_index = try self.initSection( | 1945 | self.gcc_except_tab_section_index = try self.initSection( |
| ... | @@ -2013,11 +1950,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2013,11 +1950,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2013 | .{}, | 1950 | .{}, |
| 2014 | ); | 1951 | ); |
| 2015 | } | 1952 | } |
| 2016 | | 1953 | break :blk self.gcc_except_tab_section_index.?; |
| 2017 | break :blk .{ | | |
| 2018 | .seg = self.text_segment_cmd_index.?, | | |
| 2019 | .sect = self.gcc_except_tab_section_index.?, | | |
| 2020 | }; | | |
| 2021 | } else if (mem.eql(u8, sectname, "__objc_methlist")) { | 1954 | } else if (mem.eql(u8, sectname, "__objc_methlist")) { |
| 2022 | if (self.objc_methlist_section_index == null) { | 1955 | if (self.objc_methlist_section_index == null) { |
| 2023 | self.objc_methlist_section_index = try self.initSection( | 1956 | self.objc_methlist_section_index = try self.initSection( |
| ... | @@ -2028,11 +1961,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2028,11 +1961,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2028 | .{}, | 1961 | .{}, |
| 2029 | ); | 1962 | ); |
| 2030 | } | 1963 | } |
| 2031 | | 1964 | break :blk self.objc_methlist_section_index.?; |
| 2032 | break :blk .{ | | |
| 2033 | .seg = self.text_segment_cmd_index.?, | | |
| 2034 | .sect = self.objc_methlist_section_index.?, | | |
| 2035 | }; | | |
| 2036 | } else if (mem.eql(u8, sectname, "__rodata") or | 1965 | } else if (mem.eql(u8, sectname, "__rodata") or |
| 2037 | mem.eql(u8, sectname, "__typelink") or | 1966 | mem.eql(u8, sectname, "__typelink") or |
| 2038 | mem.eql(u8, sectname, "__itablink") or | 1967 | mem.eql(u8, sectname, "__itablink") or |
| ... | @@ -2048,11 +1977,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2048,11 +1977,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2048 | .{}, | 1977 | .{}, |
| 2049 | ); | 1978 | ); |
| 2050 | } | 1979 | } |
| 2051 | | 1980 | break :blk self.data_const_section_index.?; |
| 2052 | break :blk .{ | | |
| 2053 | .seg = self.data_const_segment_cmd_index.?, | | |
| 2054 | .sect = self.data_const_section_index.?, | | |
| 2055 | }; | | |
| 2056 | } else { | 1981 | } else { |
| 2057 | if (self.text_const_section_index == null) { | 1982 | if (self.text_const_section_index == null) { |
| 2058 | self.text_const_section_index = try self.initSection( | 1983 | self.text_const_section_index = try self.initSection( |
| ... | @@ -2063,11 +1988,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2063,11 +1988,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2063 | .{}, | 1988 | .{}, |
| 2064 | ); | 1989 | ); |
| 2065 | } | 1990 | } |
| 2066 | | 1991 | break :blk self.text_const_section_index.?; |
| 2067 | break :blk .{ | | |
| 2068 | .seg = self.text_segment_cmd_index.?, | | |
| 2069 | .sect = self.text_const_section_index.?, | | |
| 2070 | }; | | |
| 2071 | } | 1992 | } |
| 2072 | } | 1993 | } |
| 2073 | | 1994 | |
| ... | @@ -2081,11 +2002,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2081,11 +2002,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2081 | .{}, | 2002 | .{}, |
| 2082 | ); | 2003 | ); |
| 2083 | } | 2004 | } |
| 2084 | | 2005 | break :blk self.data_const_section_index.?; |
| 2085 | break :blk .{ | | |
| 2086 | .seg = self.data_const_segment_cmd_index.?, | | |
| 2087 | .sect = self.data_const_section_index.?, | | |
| 2088 | }; | | |
| 2089 | } | 2006 | } |
| 2090 | | 2007 | |
| 2091 | if (mem.eql(u8, segname, "__DATA")) { | 2008 | if (mem.eql(u8, segname, "__DATA")) { |
| ... | @@ -2099,11 +2016,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2099,11 +2016,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2099 | .{}, | 2016 | .{}, |
| 2100 | ); | 2017 | ); |
| 2101 | } | 2018 | } |
| 2102 | | 2019 | break :blk self.data_const_section_index.?; |
| 2103 | break :blk .{ | | |
| 2104 | .seg = self.data_const_segment_cmd_index.?, | | |
| 2105 | .sect = self.data_const_section_index.?, | | |
| 2106 | }; | | |
| 2107 | } else if (mem.eql(u8, sectname, "__cfstring")) { | 2020 | } else if (mem.eql(u8, sectname, "__cfstring")) { |
| 2108 | if (self.objc_cfstring_section_index == null) { | 2021 | if (self.objc_cfstring_section_index == null) { |
| 2109 | self.objc_cfstring_section_index = try self.initSection( | 2022 | self.objc_cfstring_section_index = try self.initSection( |
| ... | @@ -2114,11 +2027,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2114,11 +2027,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2114 | .{}, | 2027 | .{}, |
| 2115 | ); | 2028 | ); |
| 2116 | } | 2029 | } |
| 2117 | | 2030 | break :blk self.objc_cfstring_section_index.?; |
| 2118 | break :blk .{ | | |
| 2119 | .seg = self.data_const_segment_cmd_index.?, | | |
| 2120 | .sect = self.objc_cfstring_section_index.?, | | |
| 2121 | }; | | |
| 2122 | } else if (mem.eql(u8, sectname, "__objc_classlist")) { | 2031 | } else if (mem.eql(u8, sectname, "__objc_classlist")) { |
| 2123 | if (self.objc_classlist_section_index == null) { | 2032 | if (self.objc_classlist_section_index == null) { |
| 2124 | self.objc_classlist_section_index = try self.initSection( | 2033 | self.objc_classlist_section_index = try self.initSection( |
| ... | @@ -2129,11 +2038,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2129,11 +2038,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2129 | .{}, | 2038 | .{}, |
| 2130 | ); | 2039 | ); |
| 2131 | } | 2040 | } |
| 2132 | | 2041 | break :blk self.objc_classlist_section_index.?; |
| 2133 | break :blk .{ | | |
| 2134 | .seg = self.data_const_segment_cmd_index.?, | | |
| 2135 | .sect = self.objc_classlist_section_index.?, | | |
| 2136 | }; | | |
| 2137 | } else if (mem.eql(u8, sectname, "__objc_imageinfo")) { | 2042 | } else if (mem.eql(u8, sectname, "__objc_imageinfo")) { |
| 2138 | if (self.objc_imageinfo_section_index == null) { | 2043 | if (self.objc_imageinfo_section_index == null) { |
| 2139 | self.objc_imageinfo_section_index = try self.initSection( | 2044 | self.objc_imageinfo_section_index = try self.initSection( |
| ... | @@ -2144,11 +2049,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2144,11 +2049,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2144 | .{}, | 2049 | .{}, |
| 2145 | ); | 2050 | ); |
| 2146 | } | 2051 | } |
| 2147 | | 2052 | break :blk self.objc_imageinfo_section_index.?; |
| 2148 | break :blk .{ | | |
| 2149 | .seg = self.data_const_segment_cmd_index.?, | | |
| 2150 | .sect = self.objc_imageinfo_section_index.?, | | |
| 2151 | }; | | |
| 2152 | } else if (mem.eql(u8, sectname, "__objc_const")) { | 2053 | } else if (mem.eql(u8, sectname, "__objc_const")) { |
| 2153 | if (self.objc_const_section_index == null) { | 2054 | if (self.objc_const_section_index == null) { |
| 2154 | self.objc_const_section_index = try self.initSection( | 2055 | self.objc_const_section_index = try self.initSection( |
| ... | @@ -2159,11 +2060,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2159,11 +2060,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2159 | .{}, | 2060 | .{}, |
| 2160 | ); | 2061 | ); |
| 2161 | } | 2062 | } |
| 2162 | | 2063 | break :blk self.objc_const_section_index.?; |
| 2163 | break :blk .{ | | |
| 2164 | .seg = self.data_segment_cmd_index.?, | | |
| 2165 | .sect = self.objc_const_section_index.?, | | |
| 2166 | }; | | |
| 2167 | } else if (mem.eql(u8, sectname, "__objc_classrefs")) { | 2064 | } else if (mem.eql(u8, sectname, "__objc_classrefs")) { |
| 2168 | if (self.objc_classrefs_section_index == null) { | 2065 | if (self.objc_classrefs_section_index == null) { |
| 2169 | self.objc_classrefs_section_index = try self.initSection( | 2066 | self.objc_classrefs_section_index = try self.initSection( |
| ... | @@ -2174,11 +2071,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2174,11 +2071,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2174 | .{}, | 2071 | .{}, |
| 2175 | ); | 2072 | ); |
| 2176 | } | 2073 | } |
| 2177 | | 2074 | break :blk self.objc_classrefs_section_index.?; |
| 2178 | break :blk .{ | | |
| 2179 | .seg = self.data_segment_cmd_index.?, | | |
| 2180 | .sect = self.objc_classrefs_section_index.?, | | |
| 2181 | }; | | |
| 2182 | } else if (mem.eql(u8, sectname, "__objc_data")) { | 2075 | } else if (mem.eql(u8, sectname, "__objc_data")) { |
| 2183 | if (self.objc_data_section_index == null) { | 2076 | if (self.objc_data_section_index == null) { |
| 2184 | self.objc_data_section_index = try self.initSection( | 2077 | self.objc_data_section_index = try self.initSection( |
| ... | @@ -2189,11 +2082,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2189,11 +2082,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2189 | .{}, | 2082 | .{}, |
| 2190 | ); | 2083 | ); |
| 2191 | } | 2084 | } |
| 2192 | | 2085 | break :blk self.objc_data_section_index.?; |
| 2193 | break :blk .{ | | |
| 2194 | .seg = self.data_segment_cmd_index.?, | | |
| 2195 | .sect = self.objc_data_section_index.?, | | |
| 2196 | }; | | |
| 2197 | } else if (mem.eql(u8, sectname, ".rustc")) { | 2086 | } else if (mem.eql(u8, sectname, ".rustc")) { |
| 2198 | if (self.rustc_section_index == null) { | 2087 | if (self.rustc_section_index == null) { |
| 2199 | self.rustc_section_index = try self.initSection( | 2088 | self.rustc_section_index = try self.initSection( |
| ... | @@ -2207,11 +2096,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2207,11 +2096,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2207 | // decompress the metadata. | 2096 | // decompress the metadata. |
| 2208 | self.rustc_section_size = sect.size; | 2097 | self.rustc_section_size = sect.size; |
| 2209 | } | 2098 | } |
| 2210 | | 2099 | break :blk self.rustc_section_index.?; |
| 2211 | break :blk .{ | | |
| 2212 | .seg = self.data_segment_cmd_index.?, | | |
| 2213 | .sect = self.rustc_section_index.?, | | |
| 2214 | }; | | |
| 2215 | } else { | 2100 | } else { |
| 2216 | if (self.data_section_index == null) { | 2101 | if (self.data_section_index == null) { |
| 2217 | self.data_section_index = try self.initSection( | 2102 | self.data_section_index = try self.initSection( |
| ... | @@ -2222,11 +2107,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio | ... | @@ -2222,11 +2107,7 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2222 | .{}, | 2107 | .{}, |
| 2223 | ); | 2108 | ); |
| 2224 | } | 2109 | } |
| 2225 | | 2110 | break :blk self.data_section_index.?; |
| 2226 | break :blk .{ | | |
| 2227 | .seg = self.data_segment_cmd_index.?, | | |
| 2228 | .sect = self.data_section_index.?, | | |
| 2229 | }; | | |
| 2230 | } | 2111 | } |
| 2231 | } | 2112 | } |
| 2232 | | 2113 | |
| ... | @@ -2259,30 +2140,33 @@ pub fn createEmptyAtom(gpa: Allocator, sym_index: u32, size: u64, alignment: u32 | ... | @@ -2259,30 +2140,33 @@ pub fn createEmptyAtom(gpa: Allocator, sym_index: u32, size: u64, alignment: u32 |
| 2259 | return atom; | 2140 | return atom; |
| 2260 | } | 2141 | } |
| 2261 | | 2142 | |
| 2262 | pub fn writeAtom(self: *MachO, atom: *Atom, match: MatchingSection) !void { | 2143 | pub fn writeAtom(self: *MachO, atom: *Atom, sect_id: u8) !void { |
| 2263 | const sect = self.getSection(match); | 2144 | const section = self.sections.get(sect_id); |
| 2264 | const sym = atom.getSymbol(self); | 2145 | const sym = atom.getSymbol(self); |
| 2265 | const file_offset = sect.offset + sym.n_value - sect.addr; | 2146 | const file_offset = section.header.offset + sym.n_value - section.header.addr; |
| 2266 | try atom.resolveRelocs(self); | 2147 | try atom.resolveRelocs(self); |
| 2267 | log.debug("writing atom for symbol {s} at file offset 0x{x}", .{ atom.getName(self), file_offset }); | 2148 | log.debug("writing atom for symbol {s} at file offset 0x{x}", .{ atom.getName(self), file_offset }); |
| 2268 | try self.base.file.?.pwriteAll(atom.code.items, file_offset); | 2149 | try self.base.file.?.pwriteAll(atom.code.items, file_offset); |
| 2269 | } | 2150 | } |
| 2270 | | 2151 | |
| 2271 | fn allocateSymbols(self: *MachO) !void { | 2152 | fn allocateSymbols(self: *MachO) !void { |
| 2272 | var it = self.atoms.iterator(); | 2153 | const slice = self.sections.slice(); |
| 2273 | while (it.next()) |entry| { | 2154 | for (slice.items(.last_atom)) |last_atom, sect_id| { |
| 2274 | const match = entry.key_ptr.*; | 2155 | const header = slice.items(.header)[sect_id]; |
| 2275 | var atom = entry.value_ptr.*; | 2156 | var atom = last_atom orelse continue; |
| 2276 | | 2157 | |
| 2277 | while (atom.prev) |prev| { | 2158 | while (atom.prev) |prev| { |
| 2278 | atom = prev; | 2159 | atom = prev; |
| 2279 | } | 2160 | } |
| 2280 | | 2161 | |
| 2281 | const n_sect = self.getSectionOrdinal(match); | 2162 | const n_sect = @intCast(u8, sect_id + 1); |
| 2282 | const sect = self.getSection(match); | 2163 | var base_vaddr = header.addr; |
| 2283 | var base_vaddr = sect.addr; | | |
| 2284 | | 2164 | |
| 2285 | log.debug("allocating local symbols in sect({d}, '{s},{s}')", .{ n_sect, sect.segName(), sect.sectName() }); | 2165 | log.debug("allocating local symbols in sect({d}, '{s},{s}')", .{ |
| | 2166 | n_sect, |
| | 2167 | header.segName(), |
| | 2168 | header.sectName(), |
| | 2169 | }); |
| 2286 | | 2170 | |
| 2287 | while (true) { | 2171 | while (true) { |
| 2288 | const alignment = try math.powi(u32, 2, atom.alignment); | 2172 | const alignment = try math.powi(u32, 2, atom.alignment); |
| ... | @@ -2296,7 +2180,10 @@ fn allocateSymbols(self: *MachO) !void { | ... | @@ -2296,7 +2180,10 @@ fn allocateSymbols(self: *MachO) !void { |
| 2296 | | 2180 | |
| 2297 | // Update each symbol contained within the atom | 2181 | // Update each symbol contained within the atom |
| 2298 | for (atom.contained.items) |sym_at_off| { | 2182 | for (atom.contained.items) |sym_at_off| { |
| 2299 | const contained_sym = self.getSymbolPtr(.{ .sym_index = sym_at_off.sym_index, .file = atom.file }); | 2183 | const contained_sym = self.getSymbolPtr(.{ |
| | 2184 | .sym_index = sym_at_off.sym_index, |
| | 2185 | .file = atom.file, |
| | 2186 | }); |
| 2300 | contained_sym.n_value = base_vaddr + sym_at_off.offset; | 2187 | contained_sym.n_value = base_vaddr + sym_at_off.offset; |
| 2301 | contained_sym.n_sect = n_sect; | 2188 | contained_sym.n_sect = n_sect; |
| 2302 | } | 2189 | } |
| ... | @@ -2310,15 +2197,18 @@ fn allocateSymbols(self: *MachO) !void { | ... | @@ -2310,15 +2197,18 @@ fn allocateSymbols(self: *MachO) !void { |
| 2310 | } | 2197 | } |
| 2311 | } | 2198 | } |
| 2312 | | 2199 | |
| 2313 | fn shiftLocalsByOffset(self: *MachO, match: MatchingSection, offset: i64) !void { | 2200 | fn shiftLocalsByOffset(self: *MachO, sect_id: u8, offset: i64) !void { |
| 2314 | var atom = self.atoms.get(match) orelse return; | 2201 | var atom = self.sections.items(.last_atom)[sect_id] orelse return; |
| 2315 | | 2202 | |
| 2316 | while (true) { | 2203 | while (true) { |
| 2317 | const atom_sym = atom.getSymbolPtr(self); | 2204 | const atom_sym = atom.getSymbolPtr(self); |
| 2318 | atom_sym.n_value = @intCast(u64, @intCast(i64, atom_sym.n_value) + offset); | 2205 | atom_sym.n_value = @intCast(u64, @intCast(i64, atom_sym.n_value) + offset); |
| 2319 | | 2206 | |
| 2320 | for (atom.contained.items) |sym_at_off| { | 2207 | for (atom.contained.items) |sym_at_off| { |
| 2321 | const contained_sym = self.getSymbolPtr(.{ .sym_index = sym_at_off.sym_index, .file = atom.file }); | 2208 | const contained_sym = self.getSymbolPtr(.{ |
| | 2209 | .sym_index = sym_at_off.sym_index, |
| | 2210 | .file = atom.file, |
| | 2211 | }); |
| 2322 | contained_sym.n_value = @intCast(u64, @intCast(i64, contained_sym.n_value) + offset); | 2212 | contained_sym.n_value = @intCast(u64, @intCast(i64, contained_sym.n_value) + offset); |
| 2323 | } | 2213 | } |
| 2324 | | 2214 | |
| ... | @@ -2336,16 +2226,13 @@ fn allocateSpecialSymbols(self: *MachO) !void { | ... | @@ -2336,16 +2226,13 @@ fn allocateSpecialSymbols(self: *MachO) !void { |
| 2336 | const global = self.globals.get(name) orelse continue; | 2226 | const global = self.globals.get(name) orelse continue; |
| 2337 | if (global.file != null) continue; | 2227 | if (global.file != null) continue; |
| 2338 | const sym = self.getSymbolPtr(global); | 2228 | const sym = self.getSymbolPtr(global); |
| 2339 | const seg = self.load_commands.items[self.text_segment_cmd_index.?].segment; | 2229 | const seg = self.segments.items[self.text_segment_cmd_index.?]; |
| 2340 | sym.n_sect = self.getSectionOrdinal(.{ | 2230 | sym.n_sect = 1; |
| 2341 | .seg = self.text_segment_cmd_index.?, | 2231 | sym.n_value = seg.vmaddr; |
| 2342 | .sect = 0, | | |
| 2343 | }); | | |
| 2344 | sym.n_value = seg.inner.vmaddr; | | |
| 2345 | | 2232 | |
| 2346 | log.debug("allocating {s} at the start of {s}", .{ | 2233 | log.debug("allocating {s} at the start of {s}", .{ |
| 2347 | name, | 2234 | name, |
| 2348 | seg.inner.segName(), | 2235 | seg.segName(), |
| 2349 | }); | 2236 | }); |
| 2350 | } | 2237 | } |
| 2351 | } | 2238 | } |
| ... | @@ -2353,18 +2240,20 @@ fn allocateSpecialSymbols(self: *MachO) !void { | ... | @@ -2353,18 +2240,20 @@ fn allocateSpecialSymbols(self: *MachO) !void { |
| 2353 | fn writeAtomsOneShot(self: *MachO) !void { | 2240 | fn writeAtomsOneShot(self: *MachO) !void { |
| 2354 | assert(self.mode == .one_shot); | 2241 | assert(self.mode == .one_shot); |
| 2355 | | 2242 | |
| 2356 | var it = self.atoms.iterator(); | 2243 | const gpa = self.base.allocator; |
| 2357 | while (it.next()) |entry| { | 2244 | const slice = self.sections.slice(); |
| 2358 | const sect = self.getSection(entry.key_ptr.*); | 2245 | |
| 2359 | var atom: *Atom = entry.value_ptr.*; | 2246 | for (slice.items(.last_atom)) |last_atom, sect_id| { |
| | 2247 | const header = slice.items(.header)[sect_id]; |
| | 2248 | var atom = last_atom.?; |
| 2360 | | 2249 | |
| 2361 | if (sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL) continue; | 2250 | if (header.flags == macho.S_ZEROFILL or header.flags == macho.S_THREAD_LOCAL_ZEROFILL) continue; |
| 2362 | | 2251 | |
| 2363 | var buffer = std.ArrayList(u8).init(self.base.allocator); | 2252 | var buffer = std.ArrayList(u8).init(gpa); |
| 2364 | defer buffer.deinit(); | 2253 | defer buffer.deinit(); |
| 2365 | try buffer.ensureTotalCapacity(math.cast(usize, sect.size) orelse return error.Overflow); | 2254 | try buffer.ensureTotalCapacity(math.cast(usize, header.size) orelse return error.Overflow); |
| 2366 | | 2255 | |
| 2367 | log.debug("writing atoms in {s},{s}", .{ sect.segName(), sect.sectName() }); | 2256 | log.debug("writing atoms in {s},{s}", .{ header.segName(), header.sectName() }); |
| 2368 | | 2257 | |
| 2369 | while (atom.prev) |prev| { | 2258 | while (atom.prev) |prev| { |
| 2370 | atom = prev; | 2259 | atom = prev; |
| ... | @@ -2399,18 +2288,18 @@ fn writeAtomsOneShot(self: *MachO) !void { | ... | @@ -2399,18 +2288,18 @@ fn writeAtomsOneShot(self: *MachO) !void { |
| 2399 | if (atom.next) |next| { | 2288 | if (atom.next) |next| { |
| 2400 | atom = next; | 2289 | atom = next; |
| 2401 | } else { | 2290 | } else { |
| 2402 | assert(buffer.items.len == sect.size); | 2291 | assert(buffer.items.len == header.size); |
| 2403 | log.debug(" (writing at file offset 0x{x})", .{sect.offset}); | 2292 | log.debug(" (writing at file offset 0x{x})", .{header.offset}); |
| 2404 | try self.base.file.?.pwriteAll(buffer.items, sect.offset); | 2293 | try self.base.file.?.pwriteAll(buffer.items, header.offset); |
| 2405 | break; | 2294 | break; |
| 2406 | } | 2295 | } |
| 2407 | } | 2296 | } |
| 2408 | } | 2297 | } |
| 2409 | } | 2298 | } |
| 2410 | | 2299 | |
| 2411 | fn writePadding(self: *MachO, match: MatchingSection, size: usize, writer: anytype) !void { | 2300 | fn writePadding(self: *MachO, sect_id: u8, size: usize, writer: anytype) !void { |
| 2412 | const is_code = match.seg == self.text_segment_cmd_index.? and match.sect == self.text_section_index.?; | 2301 | const header = self.sections.items(.header)[sect_id]; |
| 2413 | const min_alignment: u3 = if (!is_code) | 2302 | const min_alignment: u3 = if (!header.isCode()) |
| 2414 | 1 | 2303 | 1 |
| 2415 | else switch (self.base.options.target.cpu.arch) { | 2304 | else switch (self.base.options.target.cpu.arch) { |
| 2416 | .aarch64 => @sizeOf(u32), | 2305 | .aarch64 => @sizeOf(u32), |
| ... | @@ -2421,7 +2310,7 @@ fn writePadding(self: *MachO, match: MatchingSection, size: usize, writer: anyty | ... | @@ -2421,7 +2310,7 @@ fn writePadding(self: *MachO, match: MatchingSection, size: usize, writer: anyty |
| 2421 | const len = @divExact(size, min_alignment); | 2310 | const len = @divExact(size, min_alignment); |
| 2422 | var i: usize = 0; | 2311 | var i: usize = 0; |
| 2423 | while (i < len) : (i += 1) { | 2312 | while (i < len) : (i += 1) { |
| 2424 | if (!is_code) { | 2313 | if (!header.isCode()) { |
| 2425 | try writer.writeByte(0); | 2314 | try writer.writeByte(0); |
| 2426 | } else switch (self.base.options.target.cpu.arch) { | 2315 | } else switch (self.base.options.target.cpu.arch) { |
| 2427 | .aarch64 => { | 2316 | .aarch64 => { |
| ... | @@ -2439,20 +2328,20 @@ fn writePadding(self: *MachO, match: MatchingSection, size: usize, writer: anyty | ... | @@ -2439,20 +2328,20 @@ fn writePadding(self: *MachO, match: MatchingSection, size: usize, writer: anyty |
| 2439 | fn writeAtomsIncremental(self: *MachO) !void { | 2328 | fn writeAtomsIncremental(self: *MachO) !void { |
| 2440 | assert(self.mode == .incremental); | 2329 | assert(self.mode == .incremental); |
| 2441 | | 2330 | |
| 2442 | var it = self.atoms.iterator(); | 2331 | const slice = self.sections.slice(); |
| 2443 | while (it.next()) |entry| { | 2332 | for (slice.items(.last_atom)) |last, i| { |
| 2444 | const match = entry.key_ptr.*; | 2333 | var atom: *Atom = last orelse continue; |
| 2445 | const sect = self.getSection(match); | 2334 | const sect_i = @intCast(u8, i); |
| 2446 | var atom: *Atom = entry.value_ptr.*; | 2335 | const header = slice.items(.header)[sect_i]; |
| 2447 | | 2336 | |
| 2448 | // TODO handle zerofill in stage2 | 2337 | // TODO handle zerofill in stage2 |
| 2449 | // if (sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL) continue; | 2338 | // if (sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL) continue; |
| 2450 | | 2339 | |
| 2451 | log.debug("writing atoms in {s},{s}", .{ sect.segName(), sect.sectName() }); | 2340 | log.debug("writing atoms in {s},{s}", .{ header.segName(), header.sectName() }); |
| 2452 | | 2341 | |
| 2453 | while (true) { | 2342 | while (true) { |
| 2454 | if (atom.dirty) { | 2343 | if (atom.dirty) { |
| 2455 | try self.writeAtom(atom, match); | 2344 | try self.writeAtom(atom, sect_i); |
| 2456 | atom.dirty = false; | 2345 | atom.dirty = false; |
| 2457 | } | 2346 | } |
| 2458 | | 2347 | |
| ... | @@ -2503,10 +2392,7 @@ pub fn createGotAtom(self: *MachO, target: SymbolWithLoc) !*Atom { | ... | @@ -2503,10 +2392,7 @@ pub fn createGotAtom(self: *MachO, target: SymbolWithLoc) !*Atom { |
| 2503 | try self.managed_atoms.append(gpa, atom); | 2392 | try self.managed_atoms.append(gpa, atom); |
| 2504 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); | 2393 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2505 | | 2394 | |
| 2506 | try self.allocateAtomCommon(atom, .{ | 2395 | try self.allocateAtomCommon(atom, self.got_section_index.?); |
| 2507 | .seg = self.data_const_segment_cmd_index.?, | | |
| 2508 | .sect = self.got_section_index.?, | | |
| 2509 | }); | | |
| 2510 | | 2396 | |
| 2511 | return atom; | 2397 | return atom; |
| 2512 | } | 2398 | } |
| ... | @@ -2535,7 +2421,7 @@ pub fn createTlvPtrAtom(self: *MachO, target: SymbolWithLoc) !*Atom { | ... | @@ -2535,7 +2421,7 @@ pub fn createTlvPtrAtom(self: *MachO, target: SymbolWithLoc) !*Atom { |
| 2535 | try self.managed_atoms.append(gpa, atom); | 2421 | try self.managed_atoms.append(gpa, atom); |
| 2536 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); | 2422 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2537 | | 2423 | |
| 2538 | const match = (try self.getMatchingSection(.{ | 2424 | const match = (try self.getOutputSection(.{ |
| 2539 | .segname = makeStaticString("__DATA"), | 2425 | .segname = makeStaticString("__DATA"), |
| 2540 | .sectname = makeStaticString("__thread_ptrs"), | 2426 | .sectname = makeStaticString("__thread_ptrs"), |
| 2541 | .flags = macho.S_THREAD_LOCAL_VARIABLE_POINTERS, | 2427 | .flags = macho.S_THREAD_LOCAL_VARIABLE_POINTERS, |
| ... | @@ -2561,10 +2447,7 @@ fn createDyldPrivateAtom(self: *MachO) !void { | ... | @@ -2561,10 +2447,7 @@ fn createDyldPrivateAtom(self: *MachO) !void { |
| 2561 | const atom = try MachO.createEmptyAtom(gpa, sym_index, @sizeOf(u64), 3); | 2447 | const atom = try MachO.createEmptyAtom(gpa, sym_index, @sizeOf(u64), 3); |
| 2562 | self.dyld_private_atom = atom; | 2448 | self.dyld_private_atom = atom; |
| 2563 | | 2449 | |
| 2564 | try self.allocateAtomCommon(atom, .{ | 2450 | try self.allocateAtomCommon(atom, self.data_section_index.?); |
| 2565 | .seg = self.data_segment_cmd_index.?, | | |
| 2566 | .sect = self.data_section_index.?, | | |
| 2567 | }); | | |
| 2568 | | 2451 | |
| 2569 | try self.managed_atoms.append(gpa, atom); | 2452 | try self.managed_atoms.append(gpa, atom); |
| 2570 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); | 2453 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| ... | @@ -2692,10 +2575,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { | ... | @@ -2692,10 +2575,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2692 | } | 2575 | } |
| 2693 | self.stub_helper_preamble_atom = atom; | 2576 | self.stub_helper_preamble_atom = atom; |
| 2694 | | 2577 | |
| 2695 | try self.allocateAtomCommon(atom, .{ | 2578 | try self.allocateAtomCommon(atom, self.stub_helper_section_index.?); |
| 2696 | .seg = self.text_segment_cmd_index.?, | | |
| 2697 | .sect = self.stub_helper_section_index.?, | | |
| 2698 | }); | | |
| 2699 | | 2579 | |
| 2700 | try self.managed_atoms.append(gpa, atom); | 2580 | try self.managed_atoms.append(gpa, atom); |
| 2701 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); | 2581 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| ... | @@ -2771,10 +2651,7 @@ pub fn createStubHelperAtom(self: *MachO) !*Atom { | ... | @@ -2771,10 +2651,7 @@ pub fn createStubHelperAtom(self: *MachO) !*Atom { |
| 2771 | try self.managed_atoms.append(gpa, atom); | 2651 | try self.managed_atoms.append(gpa, atom); |
| 2772 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); | 2652 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2773 | | 2653 | |
| 2774 | try self.allocateAtomCommon(atom, .{ | 2654 | try self.allocateAtomCommon(atom, self.stub_helper_section_index.?); |
| 2775 | .seg = self.text_segment_cmd_index.?, | | |
| 2776 | .sect = self.stub_helper_section_index.?, | | |
| 2777 | }); | | |
| 2778 | | 2655 | |
| 2779 | return atom; | 2656 | return atom; |
| 2780 | } | 2657 | } |
| ... | @@ -2814,10 +2691,7 @@ pub fn createLazyPointerAtom(self: *MachO, stub_sym_index: u32, target: SymbolWi | ... | @@ -2814,10 +2691,7 @@ pub fn createLazyPointerAtom(self: *MachO, stub_sym_index: u32, target: SymbolWi |
| 2814 | try self.managed_atoms.append(gpa, atom); | 2691 | try self.managed_atoms.append(gpa, atom); |
| 2815 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); | 2692 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2816 | | 2693 | |
| 2817 | try self.allocateAtomCommon(atom, .{ | 2694 | try self.allocateAtomCommon(atom, self.la_symbol_ptr_section_index.?); |
| 2818 | .seg = self.data_segment_cmd_index.?, | | |
| 2819 | .sect = self.la_symbol_ptr_section_index.?, | | |
| 2820 | }); | | |
| 2821 | | 2695 | |
| 2822 | return atom; | 2696 | return atom; |
| 2823 | } | 2697 | } |
| ... | @@ -2896,10 +2770,7 @@ pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom { | ... | @@ -2896,10 +2770,7 @@ pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom { |
| 2896 | try self.managed_atoms.append(gpa, atom); | 2770 | try self.managed_atoms.append(gpa, atom); |
| 2897 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); | 2771 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2898 | | 2772 | |
| 2899 | try self.allocateAtomCommon(atom, .{ | 2773 | try self.allocateAtomCommon(atom, self.stubs_section_index.?); |
| 2900 | .seg = self.text_segment_cmd_index.?, | | |
| 2901 | .sect = self.stubs_section_index.?, | | |
| 2902 | }); | | |
| 2903 | | 2774 | |
| 2904 | return atom; | 2775 | return atom; |
| 2905 | } | 2776 | } |
| ... | @@ -2917,12 +2788,6 @@ fn createTentativeDefAtoms(self: *MachO) !void { | ... | @@ -2917,12 +2788,6 @@ fn createTentativeDefAtoms(self: *MachO) !void { |
| 2917 | | 2788 | |
| 2918 | // Convert any tentative definition into a regular symbol and allocate | 2789 | // Convert any tentative definition into a regular symbol and allocate |
| 2919 | // text blocks for each tentative definition. | 2790 | // text blocks for each tentative definition. |
| 2920 | const match = MatchingSection{ | | |
| 2921 | .seg = self.data_segment_cmd_index.?, | | |
| 2922 | .sect = self.bss_section_index.?, | | |
| 2923 | }; | | |
| 2924 | _ = try self.section_ordinals.getOrPut(gpa, match); | | |
| 2925 | | | |
| 2926 | const size = sym.n_value; | 2791 | const size = sym.n_value; |
| 2927 | const alignment = (sym.n_desc >> 8) & 0x0f; | 2792 | const alignment = (sym.n_desc >> 8) & 0x0f; |
| 2928 | | 2793 | |
| ... | @@ -2937,7 +2802,7 @@ fn createTentativeDefAtoms(self: *MachO) !void { | ... | @@ -2937,7 +2802,7 @@ fn createTentativeDefAtoms(self: *MachO) !void { |
| 2937 | const atom = try MachO.createEmptyAtom(gpa, global.sym_index, size, alignment); | 2802 | const atom = try MachO.createEmptyAtom(gpa, global.sym_index, size, alignment); |
| 2938 | atom.file = global.file; | 2803 | atom.file = global.file; |
| 2939 | | 2804 | |
| 2940 | try self.allocateAtomCommon(atom, match); | 2805 | try self.allocateAtomCommon(atom, self.bss_section_index.?); |
| 2941 | | 2806 | |
| 2942 | if (global.file) |file| { | 2807 | if (global.file) |file| { |
| 2943 | const object = &self.objects.items[file]; | 2808 | const object = &self.objects.items[file]; |
| ... | @@ -3060,7 +2925,8 @@ fn resolveGlobalSymbol(self: *MachO, current: SymbolWithLoc) !void { | ... | @@ -3060,7 +2925,8 @@ fn resolveGlobalSymbol(self: *MachO, current: SymbolWithLoc) !void { |
| 3060 | gop.value_ptr.* = current; | 2925 | gop.value_ptr.* = current; |
| 3061 | } | 2926 | } |
| 3062 | | 2927 | |
| 3063 | fn resolveSymbolsInObject(self: *MachO, object: *Object, object_id: u16) !void { | 2928 | fn resolveSymbolsInObject(self: *MachO, object_id: u16) !void { |
| | 2929 | const object = &self.objects.items[object_id]; |
| 3064 | log.debug("resolving symbols in '{s}'", .{object.name}); | 2930 | log.debug("resolving symbols in '{s}'", .{object.name}); |
| 3065 | | 2931 | |
| 3066 | for (object.symtab.items) |sym, index| { | 2932 | for (object.symtab.items) |sym, index| { |
| ... | @@ -3115,6 +2981,8 @@ fn resolveSymbolsInObject(self: *MachO, object: *Object, object_id: u16) !void { | ... | @@ -3115,6 +2981,8 @@ fn resolveSymbolsInObject(self: *MachO, object: *Object, object_id: u16) !void { |
| 3115 | fn resolveSymbolsInArchives(self: *MachO) !void { | 2981 | fn resolveSymbolsInArchives(self: *MachO) !void { |
| 3116 | if (self.archives.items.len == 0) return; | 2982 | if (self.archives.items.len == 0) return; |
| 3117 | | 2983 | |
| | 2984 | const gpa = self.base.allocator; |
| | 2985 | const cpu_arch = self.base.options.target.cpu.arch; |
| 3118 | var next_sym: usize = 0; | 2986 | var next_sym: usize = 0; |
| 3119 | loop: while (next_sym < self.unresolved.count()) { | 2987 | loop: while (next_sym < self.unresolved.count()) { |
| 3120 | const global = self.globals.values()[self.unresolved.keys()[next_sym]]; | 2988 | const global = self.globals.values()[self.unresolved.keys()[next_sym]]; |
| ... | @@ -3129,13 +2997,9 @@ fn resolveSymbolsInArchives(self: *MachO) !void { | ... | @@ -3129,13 +2997,9 @@ fn resolveSymbolsInArchives(self: *MachO) !void { |
| 3129 | assert(offsets.items.len > 0); | 2997 | assert(offsets.items.len > 0); |
| 3130 | | 2998 | |
| 3131 | const object_id = @intCast(u16, self.objects.items.len); | 2999 | const object_id = @intCast(u16, self.objects.items.len); |
| 3132 | const object = try self.objects.addOne(self.base.allocator); | 3000 | const object = try archive.parseObject(gpa, cpu_arch, offsets.items[0]); |
| 3133 | object.* = try archive.parseObject( | 3001 | try self.objects.append(gpa, object); |
| 3134 | self.base.allocator, | 3002 | try self.resolveSymbolsInObject(object_id); |
| 3135 | self.base.options.target.cpu.arch, | | |
| 3136 | offsets.items[0], | | |
| 3137 | ); | | |
| 3138 | try self.resolveSymbolsInObject(object, object_id); | | |
| 3139 | | 3003 | |
| 3140 | continue :loop; | 3004 | continue :loop; |
| 3141 | } | 3005 | } |
| ... | @@ -3159,7 +3023,6 @@ fn resolveSymbolsInDylibs(self: *MachO) !void { | ... | @@ -3159,7 +3023,6 @@ fn resolveSymbolsInDylibs(self: *MachO) !void { |
| 3159 | | 3023 | |
| 3160 | const dylib_id = @intCast(u16, id); | 3024 | const dylib_id = @intCast(u16, id); |
| 3161 | if (!self.referenced_dylibs.contains(dylib_id)) { | 3025 | if (!self.referenced_dylibs.contains(dylib_id)) { |
| 3162 | try self.addLoadDylibLC(dylib_id); | | |
| 3163 | try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {}); | 3026 | try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {}); |
| 3164 | } | 3027 | } |
| 3165 | | 3028 | |
| ... | @@ -3257,7 +3120,6 @@ fn resolveDyldStubBinder(self: *MachO) !void { | ... | @@ -3257,7 +3120,6 @@ fn resolveDyldStubBinder(self: *MachO) !void { |
| 3257 | | 3120 | |
| 3258 | const dylib_id = @intCast(u16, id); | 3121 | const dylib_id = @intCast(u16, id); |
| 3259 | if (!self.referenced_dylibs.contains(dylib_id)) { | 3122 | if (!self.referenced_dylibs.contains(dylib_id)) { |
| 3260 | try self.addLoadDylibLC(dylib_id); | | |
| 3261 | try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {}); | 3123 | try self.referenced_dylibs.putNoClobber(self.base.allocator, dylib_id, {}); |
| 3262 | } | 3124 | } |
| 3263 | | 3125 | |
| ... | @@ -3280,47 +3142,192 @@ fn resolveDyldStubBinder(self: *MachO) !void { | ... | @@ -3280,47 +3142,192 @@ fn resolveDyldStubBinder(self: *MachO) !void { |
| 3280 | self.got_entries.items[got_index].sym_index = got_atom.sym_index; | 3142 | self.got_entries.items[got_index].sym_index = got_atom.sym_index; |
| 3281 | } | 3143 | } |
| 3282 | | 3144 | |
| 3283 | fn addLoadDylibLC(self: *MachO, id: u16) !void { | 3145 | fn writeDylinkerLC(ncmds: *u32, lc_writer: anytype) !void { |
| 3284 | const dylib = self.dylibs.items[id]; | 3146 | const name_len = mem.sliceTo(default_dyld_path, 0).len; |
| 3285 | const dylib_id = dylib.id orelse unreachable; | 3147 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( |
| 3286 | var dylib_cmd = try macho.createLoadDylibCommand( | 3148 | u64, |
| 3287 | self.base.allocator, | 3149 | @sizeOf(macho.dylinker_command) + name_len, |
| 3288 | if (dylib.weak) .LOAD_WEAK_DYLIB else .LOAD_DYLIB, | 3150 | @sizeOf(u64), |
| 3289 | dylib_id.name, | 3151 | )); |
| 3290 | dylib_id.timestamp, | 3152 | try lc_writer.writeStruct(macho.dylinker_command{ |
| 3291 | dylib_id.current_version, | 3153 | .cmd = .LOAD_DYLINKER, |
| 3292 | dylib_id.compatibility_version, | 3154 | .cmdsize = cmdsize, |
| 3293 | ); | 3155 | .name = @sizeOf(macho.dylinker_command), |
| 3294 | errdefer dylib_cmd.deinit(self.base.allocator); | 3156 | }); |
| 3295 | try self.load_commands.append(self.base.allocator, .{ .dylib = dylib_cmd }); | 3157 | try lc_writer.writeAll(mem.sliceTo(default_dyld_path, 0)); |
| 3296 | self.load_commands_dirty = true; | 3158 | const padding = cmdsize - @sizeOf(macho.dylinker_command) - name_len; |
| | 3159 | if (padding > 0) { |
| | 3160 | try lc_writer.writeByteNTimes(0, padding); |
| | 3161 | } |
| | 3162 | ncmds.* += 1; |
| | 3163 | } |
| | 3164 | |
| | 3165 | fn writeMainLC(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| | 3166 | if (self.base.options.output_mode != .Exe) return; |
| | 3167 | const seg = self.segments.items[self.text_segment_cmd_index.?]; |
| | 3168 | const global = try self.getEntryPoint(); |
| | 3169 | const sym = self.getSymbol(global); |
| | 3170 | try lc_writer.writeStruct(macho.entry_point_command{ |
| | 3171 | .cmd = .MAIN, |
| | 3172 | .cmdsize = @sizeOf(macho.entry_point_command), |
| | 3173 | .entryoff = @intCast(u32, sym.n_value - seg.vmaddr), |
| | 3174 | .stacksize = self.base.options.stack_size_override orelse 0, |
| | 3175 | }); |
| | 3176 | ncmds.* += 1; |
| 3297 | } | 3177 | } |
| 3298 | | 3178 | |
| 3299 | fn addCodeSignatureLC(self: *MachO) !void { | 3179 | const WriteDylibLCCtx = struct { |
| 3300 | if (self.code_signature_cmd_index != null or self.code_signature == null) return; | 3180 | cmd: macho.LC, |
| 3301 | self.code_signature_cmd_index = @intCast(u16, self.load_commands.items.len); | 3181 | name: []const u8, |
| 3302 | try self.load_commands.append(self.base.allocator, .{ | 3182 | timestamp: u32 = 2, |
| 3303 | .linkedit_data = .{ | 3183 | current_version: u32 = 0x10000, |
| 3304 | .cmd = .CODE_SIGNATURE, | 3184 | compatibility_version: u32 = 0x10000, |
| 3305 | .cmdsize = @sizeOf(macho.linkedit_data_command), | 3185 | }; |
| 3306 | .dataoff = 0, | 3186 | |
| 3307 | .datasize = 0, | 3187 | fn writeDylibLC(ctx: WriteDylibLCCtx, ncmds: *u32, lc_writer: anytype) !void { |
| | 3188 | const name_len = ctx.name.len + 1; |
| | 3189 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( |
| | 3190 | u64, |
| | 3191 | @sizeOf(macho.dylib_command) + name_len, |
| | 3192 | @sizeOf(u64), |
| | 3193 | )); |
| | 3194 | try lc_writer.writeStruct(macho.dylib_command{ |
| | 3195 | .cmd = ctx.cmd, |
| | 3196 | .cmdsize = cmdsize, |
| | 3197 | .dylib = .{ |
| | 3198 | .name = @sizeOf(macho.dylib_command), |
| | 3199 | .timestamp = ctx.timestamp, |
| | 3200 | .current_version = ctx.current_version, |
| | 3201 | .compatibility_version = ctx.compatibility_version, |
| 3308 | }, | 3202 | }, |
| 3309 | }); | 3203 | }); |
| 3310 | self.load_commands_dirty = true; | 3204 | try lc_writer.writeAll(ctx.name); |
| | 3205 | try lc_writer.writeByte(0); |
| | 3206 | const padding = cmdsize - @sizeOf(macho.dylib_command) - name_len; |
| | 3207 | if (padding > 0) { |
| | 3208 | try lc_writer.writeByteNTimes(0, padding); |
| | 3209 | } |
| | 3210 | ncmds.* += 1; |
| 3311 | } | 3211 | } |
| 3312 | | 3212 | |
| 3313 | fn setEntryPoint(self: *MachO) !void { | 3213 | fn writeDylibIdLC(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 3314 | if (self.base.options.output_mode != .Exe) return; | 3214 | if (self.base.options.output_mode != .Lib) return; |
| | 3215 | const install_name = self.base.options.install_name orelse self.base.options.emit.?.sub_path; |
| | 3216 | const curr = self.base.options.version orelse std.builtin.Version{ |
| | 3217 | .major = 1, |
| | 3218 | .minor = 0, |
| | 3219 | .patch = 0, |
| | 3220 | }; |
| | 3221 | const compat = self.base.options.compatibility_version orelse std.builtin.Version{ |
| | 3222 | .major = 1, |
| | 3223 | .minor = 0, |
| | 3224 | .patch = 0, |
| | 3225 | }; |
| | 3226 | try writeDylibLC(.{ |
| | 3227 | .cmd = .ID_DYLIB, |
| | 3228 | .name = install_name, |
| | 3229 | .current_version = curr.major << 16 | curr.minor << 8 | curr.patch, |
| | 3230 | .compatibility_version = compat.major << 16 | compat.minor << 8 | compat.patch, |
| | 3231 | }, ncmds, lc_writer); |
| | 3232 | } |
| 3315 | | 3233 | |
| 3316 | const seg = self.load_commands.items[self.text_segment_cmd_index.?].segment; | 3234 | const RpathIterator = struct { |
| 3317 | const global = try self.getEntryPoint(); | 3235 | buffer: []const []const u8, |
| 3318 | const sym = self.getSymbol(global); | 3236 | table: std.StringHashMap(void), |
| 3319 | const ec = &self.load_commands.items[self.main_cmd_index.?].main; | 3237 | count: usize = 0, |
| 3320 | ec.entryoff = @intCast(u32, sym.n_value - seg.inner.vmaddr); | 3238 | |
| 3321 | ec.stacksize = self.base.options.stack_size_override orelse 0; | 3239 | fn init(gpa: Allocator, rpaths: []const []const u8) RpathIterator { |
| 3322 | self.entry_addr = sym.n_value; | 3240 | return .{ .buffer = rpaths, .table = std.StringHashMap(void).init(gpa) }; |
| 3323 | self.load_commands_dirty = true; | 3241 | } |
| | 3242 | |
| | 3243 | fn deinit(it: *RpathIterator) void { |
| | 3244 | it.table.deinit(); |
| | 3245 | } |
| | 3246 | |
| | 3247 | fn next(it: *RpathIterator) !?[]const u8 { |
| | 3248 | while (true) { |
| | 3249 | if (it.count >= it.buffer.len) return null; |
| | 3250 | const rpath = it.buffer[it.count]; |
| | 3251 | it.count += 1; |
| | 3252 | const gop = try it.table.getOrPut(rpath); |
| | 3253 | if (gop.found_existing) continue; |
| | 3254 | return rpath; |
| | 3255 | } |
| | 3256 | } |
| | 3257 | }; |
| | 3258 | |
| | 3259 | fn writeRpathLCs(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| | 3260 | const gpa = self.base.allocator; |
| | 3261 | |
| | 3262 | var it = RpathIterator.init(gpa, self.base.options.rpath_list); |
| | 3263 | defer it.deinit(); |
| | 3264 | |
| | 3265 | while (try it.next()) |rpath| { |
| | 3266 | const rpath_len = rpath.len + 1; |
| | 3267 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( |
| | 3268 | u64, |
| | 3269 | @sizeOf(macho.rpath_command) + rpath_len, |
| | 3270 | @sizeOf(u64), |
| | 3271 | )); |
| | 3272 | try lc_writer.writeStruct(macho.rpath_command{ |
| | 3273 | .cmdsize = cmdsize, |
| | 3274 | .path = @sizeOf(macho.rpath_command), |
| | 3275 | }); |
| | 3276 | try lc_writer.writeAll(rpath); |
| | 3277 | try lc_writer.writeByte(0); |
| | 3278 | const padding = cmdsize - @sizeOf(macho.rpath_command) - rpath_len; |
| | 3279 | if (padding > 0) { |
| | 3280 | try lc_writer.writeByteNTimes(0, padding); |
| | 3281 | } |
| | 3282 | ncmds.* += 1; |
| | 3283 | } |
| | 3284 | } |
| | 3285 | |
| | 3286 | fn writeBuildVersionLC(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| | 3287 | const cmdsize = @sizeOf(macho.build_version_command) + @sizeOf(macho.build_tool_version); |
| | 3288 | const platform_version = blk: { |
| | 3289 | const ver = self.base.options.target.os.version_range.semver.min; |
| | 3290 | const platform_version = ver.major << 16 | ver.minor << 8; |
| | 3291 | break :blk platform_version; |
| | 3292 | }; |
| | 3293 | const sdk_version = if (self.base.options.native_darwin_sdk) |sdk| blk: { |
| | 3294 | const ver = sdk.version; |
| | 3295 | const sdk_version = ver.major << 16 | ver.minor << 8; |
| | 3296 | break :blk sdk_version; |
| | 3297 | } else platform_version; |
| | 3298 | const is_simulator_abi = self.base.options.target.abi == .simulator; |
| | 3299 | try lc_writer.writeStruct(macho.build_version_command{ |
| | 3300 | .cmdsize = cmdsize, |
| | 3301 | .platform = switch (self.base.options.target.os.tag) { |
| | 3302 | .macos => .MACOS, |
| | 3303 | .ios => if (is_simulator_abi) macho.PLATFORM.IOSSIMULATOR else macho.PLATFORM.IOS, |
| | 3304 | .watchos => if (is_simulator_abi) macho.PLATFORM.WATCHOSSIMULATOR else macho.PLATFORM.WATCHOS, |
| | 3305 | .tvos => if (is_simulator_abi) macho.PLATFORM.TVOSSIMULATOR else macho.PLATFORM.TVOS, |
| | 3306 | else => unreachable, |
| | 3307 | }, |
| | 3308 | .minos = platform_version, |
| | 3309 | .sdk = sdk_version, |
| | 3310 | .ntools = 1, |
| | 3311 | }); |
| | 3312 | try lc_writer.writeAll(mem.asBytes(&macho.build_tool_version{ |
| | 3313 | .tool = .LD, |
| | 3314 | .version = 0x0, |
| | 3315 | })); |
| | 3316 | ncmds.* += 1; |
| | 3317 | } |
| | 3318 | |
| | 3319 | fn writeLoadDylibLCs(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| | 3320 | for (self.referenced_dylibs.keys()) |id| { |
| | 3321 | const dylib = self.dylibs.items[id]; |
| | 3322 | const dylib_id = dylib.id orelse unreachable; |
| | 3323 | try writeDylibLC(.{ |
| | 3324 | .cmd = if (dylib.weak) .LOAD_WEAK_DYLIB else .LOAD_DYLIB, |
| | 3325 | .name = dylib_id.name, |
| | 3326 | .timestamp = dylib_id.timestamp, |
| | 3327 | .current_version = dylib_id.current_version, |
| | 3328 | .compatibility_version = dylib_id.compatibility_version, |
| | 3329 | }, ncmds, lc_writer); |
| | 3330 | } |
| 3324 | } | 3331 | } |
| 3325 | | 3332 | |
| 3326 | pub fn deinit(self: *MachO) void { | 3333 | pub fn deinit(self: *MachO) void { |
| ... | @@ -3334,7 +3341,6 @@ pub fn deinit(self: *MachO) void { | ... | @@ -3334,7 +3341,6 @@ pub fn deinit(self: *MachO) void { |
| 3334 | d_sym.deinit(gpa); | 3341 | d_sym.deinit(gpa); |
| 3335 | } | 3342 | } |
| 3336 | | 3343 | |
| 3337 | self.section_ordinals.deinit(gpa); | | |
| 3338 | self.tlv_ptr_entries.deinit(gpa); | 3344 | self.tlv_ptr_entries.deinit(gpa); |
| 3339 | self.tlv_ptr_entries_free_list.deinit(gpa); | 3345 | self.tlv_ptr_entries_free_list.deinit(gpa); |
| 3340 | self.tlv_ptr_entries_table.deinit(gpa); | 3346 | self.tlv_ptr_entries_table.deinit(gpa); |
| ... | @@ -3371,24 +3377,19 @@ pub fn deinit(self: *MachO) void { | ... | @@ -3371,24 +3377,19 @@ pub fn deinit(self: *MachO) void { |
| 3371 | self.dylibs_map.deinit(gpa); | 3377 | self.dylibs_map.deinit(gpa); |
| 3372 | self.referenced_dylibs.deinit(gpa); | 3378 | self.referenced_dylibs.deinit(gpa); |
| 3373 | | 3379 | |
| 3374 | for (self.load_commands.items) |*lc| { | 3380 | self.segments.deinit(gpa); |
| 3375 | lc.deinit(gpa); | 3381 | |
| | 3382 | for (self.sections.items(.free_list)) |*list| { |
| | 3383 | list.deinit(gpa); |
| 3376 | } | 3384 | } |
| 3377 | self.load_commands.deinit(gpa); | 3385 | self.sections.deinit(gpa); |
| 3378 | | 3386 | |
| 3379 | for (self.managed_atoms.items) |atom| { | 3387 | for (self.managed_atoms.items) |atom| { |
| 3380 | atom.deinit(gpa); | 3388 | atom.deinit(gpa); |
| 3381 | gpa.destroy(atom); | 3389 | gpa.destroy(atom); |
| 3382 | } | 3390 | } |
| 3383 | self.managed_atoms.deinit(gpa); | 3391 | self.managed_atoms.deinit(gpa); |
| 3384 | self.atoms.deinit(gpa); | 3392 | |
| 3385 | { | | |
| 3386 | var it = self.atom_free_lists.valueIterator(); | | |
| 3387 | while (it.next()) |free_list| { | | |
| 3388 | free_list.deinit(gpa); | | |
| 3389 | } | | |
| 3390 | self.atom_free_lists.deinit(gpa); | | |
| 3391 | } | | |
| 3392 | if (self.base.options.module) |mod| { | 3393 | if (self.base.options.module) |mod| { |
| 3393 | for (self.decls.keys()) |decl_index| { | 3394 | for (self.decls.keys()) |decl_index| { |
| 3394 | const decl = mod.declPtr(decl_index); | 3395 | const decl = mod.declPtr(decl_index); |
| ... | @@ -3408,34 +3409,24 @@ pub fn deinit(self: *MachO) void { | ... | @@ -3408,34 +3409,24 @@ pub fn deinit(self: *MachO) void { |
| 3408 | } | 3409 | } |
| 3409 | | 3410 | |
| 3410 | self.atom_by_index_table.deinit(gpa); | 3411 | self.atom_by_index_table.deinit(gpa); |
| 3411 | | | |
| 3412 | if (self.code_signature) |*csig| { | | |
| 3413 | csig.deinit(gpa); | | |
| 3414 | } | | |
| 3415 | } | 3412 | } |
| 3416 | | 3413 | |
| 3417 | pub fn closeFiles(self: MachO) void { | 3414 | pub fn closeFiles(self: MachO) void { |
| 3418 | for (self.objects.items) |object| { | | |
| 3419 | object.file.close(); | | |
| 3420 | } | | |
| 3421 | for (self.archives.items) |archive| { | 3415 | for (self.archives.items) |archive| { |
| 3422 | archive.file.close(); | 3416 | archive.file.close(); |
| 3423 | } | 3417 | } |
| 3424 | for (self.dylibs.items) |dylib| { | | |
| 3425 | dylib.file.close(); | | |
| 3426 | } | | |
| 3427 | if (self.d_sym) |ds| { | 3418 | if (self.d_sym) |ds| { |
| 3428 | ds.file.close(); | 3419 | ds.file.close(); |
| 3429 | } | 3420 | } |
| 3430 | } | 3421 | } |
| 3431 | | 3422 | |
| 3432 | fn freeAtom(self: *MachO, atom: *Atom, match: MatchingSection, owns_atom: bool) void { | 3423 | fn freeAtom(self: *MachO, atom: *Atom, sect_id: u8, owns_atom: bool) void { |
| 3433 | log.debug("freeAtom {*}", .{atom}); | 3424 | log.debug("freeAtom {*}", .{atom}); |
| 3434 | if (!owns_atom) { | 3425 | if (!owns_atom) { |
| 3435 | atom.deinit(self.base.allocator); | 3426 | atom.deinit(self.base.allocator); |
| 3436 | } | 3427 | } |
| 3437 | | 3428 | |
| 3438 | const free_list = self.atom_free_lists.getPtr(match).?; | 3429 | const free_list = &self.sections.items(.free_list)[sect_id]; |
| 3439 | var already_have_free_list_node = false; | 3430 | var already_have_free_list_node = false; |
| 3440 | { | 3431 | { |
| 3441 | var i: usize = 0; | 3432 | var i: usize = 0; |
| ... | @@ -3452,13 +3443,14 @@ fn freeAtom(self: *MachO, atom: *Atom, match: MatchingSection, owns_atom: bool) | ... | @@ -3452,13 +3443,14 @@ fn freeAtom(self: *MachO, atom: *Atom, match: MatchingSection, owns_atom: bool) |
| 3452 | } | 3443 | } |
| 3453 | } | 3444 | } |
| 3454 | | 3445 | |
| 3455 | if (self.atoms.getPtr(match)) |last_atom| { | 3446 | const maybe_last_atom = &self.sections.items(.last_atom)[sect_id]; |
| 3456 | if (last_atom.* == atom) { | 3447 | if (maybe_last_atom.*) |last_atom| { |
| | 3448 | if (last_atom == atom) { |
| 3457 | if (atom.prev) |prev| { | 3449 | if (atom.prev) |prev| { |
| 3458 | // TODO shrink the section size here | 3450 | // TODO shrink the section size here |
| 3459 | last_atom.* = prev; | 3451 | maybe_last_atom.* = prev; |
| 3460 | } else { | 3452 | } else { |
| 3461 | _ = self.atoms.fetchRemove(match); | 3453 | maybe_last_atom.* = null; |
| 3462 | } | 3454 | } |
| 3463 | } | 3455 | } |
| 3464 | } | 3456 | } |
| ... | @@ -3486,21 +3478,21 @@ fn freeAtom(self: *MachO, atom: *Atom, match: MatchingSection, owns_atom: bool) | ... | @@ -3486,21 +3478,21 @@ fn freeAtom(self: *MachO, atom: *Atom, match: MatchingSection, owns_atom: bool) |
| 3486 | } | 3478 | } |
| 3487 | } | 3479 | } |
| 3488 | | 3480 | |
| 3489 | fn shrinkAtom(self: *MachO, atom: *Atom, new_block_size: u64, match: MatchingSection) void { | 3481 | fn shrinkAtom(self: *MachO, atom: *Atom, new_block_size: u64, sect_id: u8) void { |
| 3490 | _ = self; | 3482 | _ = self; |
| 3491 | _ = atom; | 3483 | _ = atom; |
| 3492 | _ = new_block_size; | 3484 | _ = new_block_size; |
| 3493 | _ = match; | 3485 | _ = sect_id; |
| 3494 | // TODO check the new capacity, and if it crosses the size threshold into a big enough | 3486 | // TODO check the new capacity, and if it crosses the size threshold into a big enough |
| 3495 | // capacity, insert a free list node for it. | 3487 | // capacity, insert a free list node for it. |
| 3496 | } | 3488 | } |
| 3497 | | 3489 | |
| 3498 | fn growAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, match: MatchingSection) !u64 { | 3490 | fn growAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, sect_id: u8) !u64 { |
| 3499 | const sym = atom.getSymbol(self); | 3491 | const sym = atom.getSymbol(self); |
| 3500 | const align_ok = mem.alignBackwardGeneric(u64, sym.n_value, alignment) == sym.n_value; | 3492 | const align_ok = mem.alignBackwardGeneric(u64, sym.n_value, alignment) == sym.n_value; |
| 3501 | const need_realloc = !align_ok or new_atom_size > atom.capacity(self); | 3493 | const need_realloc = !align_ok or new_atom_size > atom.capacity(self); |
| 3502 | if (!need_realloc) return sym.n_value; | 3494 | if (!need_realloc) return sym.n_value; |
| 3503 | return self.allocateAtom(atom, new_atom_size, alignment, match); | 3495 | return self.allocateAtom(atom, new_atom_size, alignment, sect_id); |
| 3504 | } | 3496 | } |
| 3505 | | 3497 | |
| 3506 | fn allocateSymbol(self: *MachO) !u32 { | 3498 | fn allocateSymbol(self: *MachO) !u32 { |
| ... | @@ -3671,10 +3663,11 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv | ... | @@ -3671,10 +3663,11 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv |
| 3671 | } | 3663 | } |
| 3672 | | 3664 | |
| 3673 | pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Module.Decl.Index) !u32 { | 3665 | pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Module.Decl.Index) !u32 { |
| 3674 | var code_buffer = std.ArrayList(u8).init(self.base.allocator); | 3666 | const gpa = self.base.allocator; |
| | 3667 | |
| | 3668 | var code_buffer = std.ArrayList(u8).init(gpa); |
| 3675 | defer code_buffer.deinit(); | 3669 | defer code_buffer.deinit(); |
| 3676 | | 3670 | |
| 3677 | const gpa = self.base.allocator; | | |
| 3678 | const module = self.base.options.module.?; | 3671 | const module = self.base.options.module.?; |
| 3679 | const gop = try self.unnamed_const_atoms.getOrPut(gpa, decl_index); | 3672 | const gop = try self.unnamed_const_atoms.getOrPut(gpa, decl_index); |
| 3680 | if (!gop.found_existing) { | 3673 | if (!gop.found_existing) { |
| ... | @@ -3725,25 +3718,25 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Modu | ... | @@ -3725,25 +3718,25 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Modu |
| 3725 | atom.code.clearRetainingCapacity(); | 3718 | atom.code.clearRetainingCapacity(); |
| 3726 | try atom.code.appendSlice(gpa, code); | 3719 | try atom.code.appendSlice(gpa, code); |
| 3727 | | 3720 | |
| 3728 | const match = try self.getMatchingSectionAtom( | 3721 | const sect_id = try self.getOutputSectionAtom( |
| 3729 | atom, | 3722 | atom, |
| 3730 | decl_name, | 3723 | decl_name, |
| 3731 | typed_value.ty, | 3724 | typed_value.ty, |
| 3732 | typed_value.val, | 3725 | typed_value.val, |
| 3733 | required_alignment, | 3726 | required_alignment, |
| 3734 | ); | 3727 | ); |
| 3735 | const addr = try self.allocateAtom(atom, code.len, required_alignment, match); | 3728 | const addr = try self.allocateAtom(atom, code.len, required_alignment, sect_id); |
| 3736 | | 3729 | |
| 3737 | log.debug("allocated atom for {?s} at 0x{x}", .{ name, addr }); | 3730 | log.debug("allocated atom for {?s} at 0x{x}", .{ name, addr }); |
| 3738 | log.debug(" (required alignment 0x{x})", .{required_alignment}); | 3731 | log.debug(" (required alignment 0x{x})", .{required_alignment}); |
| 3739 | | 3732 | |
| 3740 | errdefer self.freeAtom(atom, match, true); | 3733 | errdefer self.freeAtom(atom, sect_id, true); |
| 3741 | | 3734 | |
| 3742 | const symbol = atom.getSymbolPtr(self); | 3735 | const symbol = atom.getSymbolPtr(self); |
| 3743 | symbol.* = .{ | 3736 | symbol.* = .{ |
| 3744 | .n_strx = name_str_index, | 3737 | .n_strx = name_str_index, |
| 3745 | .n_type = macho.N_SECT, | 3738 | .n_type = macho.N_SECT, |
| 3746 | .n_sect = self.getSectionOrdinal(match), | 3739 | .n_sect = sect_id + 1, |
| 3747 | .n_desc = 0, | 3740 | .n_desc = 0, |
| 3748 | .n_value = addr, | 3741 | .n_value = addr, |
| 3749 | }; | 3742 | }; |
| ... | @@ -3894,44 +3887,35 @@ fn needsPointerRebase(ty: Type, val: Value, mod: *Module) bool { | ... | @@ -3894,44 +3887,35 @@ fn needsPointerRebase(ty: Type, val: Value, mod: *Module) bool { |
| 3894 | } | 3887 | } |
| 3895 | } | 3888 | } |
| 3896 | | 3889 | |
| 3897 | fn getMatchingSectionAtom( | 3890 | fn getOutputSectionAtom( |
| 3898 | self: *MachO, | 3891 | self: *MachO, |
| 3899 | atom: *Atom, | 3892 | atom: *Atom, |
| 3900 | name: []const u8, | 3893 | name: []const u8, |
| 3901 | ty: Type, | 3894 | ty: Type, |
| 3902 | val: Value, | 3895 | val: Value, |
| 3903 | alignment: u32, | 3896 | alignment: u32, |
| 3904 | ) !MatchingSection { | 3897 | ) !u8 { |
| 3905 | const code = atom.code.items; | 3898 | const code = atom.code.items; |
| 3906 | const mod = self.base.options.module.?; | 3899 | const mod = self.base.options.module.?; |
| 3907 | const align_log_2 = math.log2(alignment); | 3900 | const align_log_2 = math.log2(alignment); |
| 3908 | const zig_ty = ty.zigTypeTag(); | 3901 | const zig_ty = ty.zigTypeTag(); |
| 3909 | const mode = self.base.options.optimize_mode; | 3902 | const mode = self.base.options.optimize_mode; |
| 3910 | const match: MatchingSection = blk: { | 3903 | const sect_id: u8 = blk: { |
| 3911 | // TODO finish and audit this function | 3904 | // TODO finish and audit this function |
| 3912 | if (val.isUndefDeep()) { | 3905 | if (val.isUndefDeep()) { |
| 3913 | if (mode == .ReleaseFast or mode == .ReleaseSmall) { | 3906 | if (mode == .ReleaseFast or mode == .ReleaseSmall) { |
| 3914 | break :blk MatchingSection{ | 3907 | break :blk self.bss_section_index.?; |
| 3915 | .seg = self.data_segment_cmd_index.?, | | |
| 3916 | .sect = self.bss_section_index.?, | | |
| 3917 | }; | | |
| 3918 | } else { | 3908 | } else { |
| 3919 | break :blk MatchingSection{ | 3909 | break :blk self.data_section_index.?; |
| 3920 | .seg = self.data_segment_cmd_index.?, | | |
| 3921 | .sect = self.data_section_index.?, | | |
| 3922 | }; | | |
| 3923 | } | 3910 | } |
| 3924 | } | 3911 | } |
| 3925 | | 3912 | |
| 3926 | if (val.castTag(.variable)) |_| { | 3913 | if (val.castTag(.variable)) |_| { |
| 3927 | break :blk MatchingSection{ | 3914 | break :blk self.data_section_index.?; |
| 3928 | .seg = self.data_segment_cmd_index.?, | | |
| 3929 | .sect = self.data_section_index.?, | | |
| 3930 | }; | | |
| 3931 | } | 3915 | } |
| 3932 | | 3916 | |
| 3933 | if (needsPointerRebase(ty, val, mod)) { | 3917 | if (needsPointerRebase(ty, val, mod)) { |
| 3934 | break :blk (try self.getMatchingSection(.{ | 3918 | break :blk (try self.getOutputSection(.{ |
| 3935 | .segname = makeStaticString("__DATA_CONST"), | 3919 | .segname = makeStaticString("__DATA_CONST"), |
| 3936 | .sectname = makeStaticString("__const"), | 3920 | .sectname = makeStaticString("__const"), |
| 3937 | .size = code.len, | 3921 | .size = code.len, |
| ... | @@ -3941,10 +3925,7 @@ fn getMatchingSectionAtom( | ... | @@ -3941,10 +3925,7 @@ fn getMatchingSectionAtom( |
| 3941 | | 3925 | |
| 3942 | switch (zig_ty) { | 3926 | switch (zig_ty) { |
| 3943 | .Fn => { | 3927 | .Fn => { |
| 3944 | break :blk MatchingSection{ | 3928 | break :blk self.text_section_index.?; |
| 3945 | .seg = self.text_segment_cmd_index.?, | | |
| 3946 | .sect = self.text_section_index.?, | | |
| 3947 | }; | | |
| 3948 | }, | 3929 | }, |
| 3949 | .Array => { | 3930 | .Array => { |
| 3950 | if (val.tag() == .bytes) { | 3931 | if (val.tag() == .bytes) { |
| ... | @@ -3953,7 +3934,7 @@ fn getMatchingSectionAtom( | ... | @@ -3953,7 +3934,7 @@ fn getMatchingSectionAtom( |
| 3953 | .const_slice_u8_sentinel_0, | 3934 | .const_slice_u8_sentinel_0, |
| 3954 | .manyptr_const_u8_sentinel_0, | 3935 | .manyptr_const_u8_sentinel_0, |
| 3955 | => { | 3936 | => { |
| 3956 | break :blk (try self.getMatchingSection(.{ | 3937 | break :blk (try self.getOutputSection(.{ |
| 3957 | .segname = makeStaticString("__TEXT"), | 3938 | .segname = makeStaticString("__TEXT"), |
| 3958 | .sectname = makeStaticString("__cstring"), | 3939 | .sectname = makeStaticString("__cstring"), |
| 3959 | .flags = macho.S_CSTRING_LITERALS, | 3940 | .flags = macho.S_CSTRING_LITERALS, |
| ... | @@ -3967,22 +3948,21 @@ fn getMatchingSectionAtom( | ... | @@ -3967,22 +3948,21 @@ fn getMatchingSectionAtom( |
| 3967 | }, | 3948 | }, |
| 3968 | else => {}, | 3949 | else => {}, |
| 3969 | } | 3950 | } |
| 3970 | break :blk (try self.getMatchingSection(.{ | 3951 | break :blk (try self.getOutputSection(.{ |
| 3971 | .segname = makeStaticString("__TEXT"), | 3952 | .segname = makeStaticString("__TEXT"), |
| 3972 | .sectname = makeStaticString("__const"), | 3953 | .sectname = makeStaticString("__const"), |
| 3973 | .size = code.len, | 3954 | .size = code.len, |
| 3974 | .@"align" = align_log_2, | 3955 | .@"align" = align_log_2, |
| 3975 | })).?; | 3956 | })).?; |
| 3976 | }; | 3957 | }; |
| 3977 | const sect = self.getSection(match); | 3958 | const header = self.sections.items(.header)[sect_id]; |
| 3978 | log.debug(" allocating atom '{s}' in '{s},{s}' ({d},{d})", .{ | 3959 | log.debug(" allocating atom '{s}' in '{s},{s}', ord({d})", .{ |
| 3979 | name, | 3960 | name, |
| 3980 | sect.segName(), | 3961 | header.segName(), |
| 3981 | sect.sectName(), | 3962 | header.sectName(), |
| 3982 | match.seg, | 3963 | sect_id, |
| 3983 | match.sect, | | |
| 3984 | }); | 3964 | }); |
| 3985 | return match; | 3965 | return sect_id; |
| 3986 | } | 3966 | } |
| 3987 | | 3967 | |
| 3988 | fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !u64 { | 3968 | fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !u64 { |
| ... | @@ -3996,7 +3976,7 @@ fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !u64 | ... | @@ -3996,7 +3976,7 @@ fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !u64 |
| 3996 | | 3976 | |
| 3997 | const decl_ptr = self.decls.getPtr(decl_index).?; | 3977 | const decl_ptr = self.decls.getPtr(decl_index).?; |
| 3998 | if (decl_ptr.* == null) { | 3978 | if (decl_ptr.* == null) { |
| 3999 | decl_ptr.* = try self.getMatchingSectionAtom( | 3979 | decl_ptr.* = try self.getOutputSectionAtom( |
| 4000 | &decl.link.macho, | 3980 | &decl.link.macho, |
| 4001 | sym_name, | 3981 | sym_name, |
| 4002 | decl.ty, | 3982 | decl.ty, |
| ... | @@ -4045,7 +4025,7 @@ fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !u64 | ... | @@ -4045,7 +4025,7 @@ fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !u64 |
| 4045 | symbol.* = .{ | 4025 | symbol.* = .{ |
| 4046 | .n_strx = name_str_index, | 4026 | .n_strx = name_str_index, |
| 4047 | .n_type = macho.N_SECT, | 4027 | .n_type = macho.N_SECT, |
| 4048 | .n_sect = self.getSectionOrdinal(match), | 4028 | .n_sect = match + 1, |
| 4049 | .n_desc = 0, | 4029 | .n_desc = 0, |
| 4050 | .n_value = addr, | 4030 | .n_value = addr, |
| 4051 | }; | 4031 | }; |
| ... | @@ -4134,10 +4114,7 @@ pub fn updateDeclExports( | ... | @@ -4134,10 +4114,7 @@ pub fn updateDeclExports( |
| 4134 | sym.* = .{ | 4114 | sym.* = .{ |
| 4135 | .n_strx = try self.strtab.insert(gpa, exp_name), | 4115 | .n_strx = try self.strtab.insert(gpa, exp_name), |
| 4136 | .n_type = macho.N_SECT | macho.N_EXT, | 4116 | .n_type = macho.N_SECT | macho.N_EXT, |
| 4137 | .n_sect = self.getSectionOrdinal(.{ | 4117 | .n_sect = self.text_section_index.? + 1, // TODO what if we export a variable? |
| 4138 | .seg = self.text_segment_cmd_index.?, | | |
| 4139 | .sect = self.text_section_index.?, // TODO what if we export a variable? | | |
| 4140 | }), | | |
| 4141 | .n_desc = 0, | 4118 | .n_desc = 0, |
| 4142 | .n_value = decl_sym.n_value, | 4119 | .n_value = decl_sym.n_value, |
| 4143 | }; | 4120 | }; |
| ... | @@ -4208,10 +4185,7 @@ pub fn deleteExport(self: *MachO, exp: Export) void { | ... | @@ -4208,10 +4185,7 @@ pub fn deleteExport(self: *MachO, exp: Export) void { |
| 4208 | fn freeUnnamedConsts(self: *MachO, decl_index: Module.Decl.Index) void { | 4185 | fn freeUnnamedConsts(self: *MachO, decl_index: Module.Decl.Index) void { |
| 4209 | const unnamed_consts = self.unnamed_const_atoms.getPtr(decl_index) orelse return; | 4186 | const unnamed_consts = self.unnamed_const_atoms.getPtr(decl_index) orelse return; |
| 4210 | for (unnamed_consts.items) |atom| { | 4187 | for (unnamed_consts.items) |atom| { |
| 4211 | self.freeAtom(atom, .{ | 4188 | self.freeAtom(atom, self.text_const_section_index.?, true); |
| 4212 | .seg = self.text_segment_cmd_index.?, | | |
| 4213 | .sect = self.text_const_section_index.?, | | |
| 4214 | }, true); | | |
| 4215 | self.locals_free_list.append(self.base.allocator, atom.sym_index) catch {}; | 4189 | self.locals_free_list.append(self.base.allocator, atom.sym_index) catch {}; |
| 4216 | self.locals.items[atom.sym_index].n_type = 0; | 4190 | self.locals.items[atom.sym_index].n_type = 0; |
| 4217 | _ = self.atom_by_index_table.remove(atom.sym_index); | 4191 | _ = self.atom_by_index_table.remove(atom.sym_index); |
| ... | @@ -4294,6 +4268,7 @@ pub fn getDeclVAddr(self: *MachO, decl_index: Module.Decl.Index, reloc_info: Fil | ... | @@ -4294,6 +4268,7 @@ pub fn getDeclVAddr(self: *MachO, decl_index: Module.Decl.Index, reloc_info: Fil |
| 4294 | } | 4268 | } |
| 4295 | | 4269 | |
| 4296 | fn populateMissingMetadata(self: *MachO) !void { | 4270 | fn populateMissingMetadata(self: *MachO) !void { |
| | 4271 | const gpa = self.base.allocator; |
| 4297 | const cpu_arch = self.base.options.target.cpu.arch; | 4272 | const cpu_arch = self.base.options.target.cpu.arch; |
| 4298 | const pagezero_vmsize = self.base.options.pagezero_size orelse default_pagezero_vmsize; | 4273 | const pagezero_vmsize = self.base.options.pagezero_size orelse default_pagezero_vmsize; |
| 4299 | const aligned_pagezero_vmsize = mem.alignBackwardGeneric(u64, pagezero_vmsize, self.page_size); | 4274 | const aligned_pagezero_vmsize = mem.alignBackwardGeneric(u64, pagezero_vmsize, self.page_size); |
| ... | @@ -4305,21 +4280,16 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4305,21 +4280,16 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4305 | log.warn("requested __PAGEZERO size (0x{x}) is not page aligned", .{pagezero_vmsize}); | 4280 | log.warn("requested __PAGEZERO size (0x{x}) is not page aligned", .{pagezero_vmsize}); |
| 4306 | log.warn(" rounding down to 0x{x}", .{aligned_pagezero_vmsize}); | 4281 | log.warn(" rounding down to 0x{x}", .{aligned_pagezero_vmsize}); |
| 4307 | } | 4282 | } |
| 4308 | self.pagezero_segment_cmd_index = @intCast(u16, self.load_commands.items.len); | 4283 | self.pagezero_segment_cmd_index = @intCast(u8, self.segments.items.len); |
| 4309 | try self.load_commands.append(self.base.allocator, .{ | 4284 | try self.segments.append(gpa, .{ |
| 4310 | .segment = .{ | 4285 | .segname = makeStaticString("__PAGEZERO"), |
| 4311 | .inner = .{ | 4286 | .vmsize = aligned_pagezero_vmsize, |
| 4312 | .segname = makeStaticString("__PAGEZERO"), | 4287 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 4313 | .vmsize = aligned_pagezero_vmsize, | | |
| 4314 | .cmdsize = @sizeOf(macho.segment_command_64), | | |
| 4315 | }, | | |
| 4316 | }, | | |
| 4317 | }); | 4288 | }); |
| 4318 | self.load_commands_dirty = true; | | |
| 4319 | } | 4289 | } |
| 4320 | | 4290 | |
| 4321 | if (self.text_segment_cmd_index == null) { | 4291 | if (self.text_segment_cmd_index == null) { |
| 4322 | self.text_segment_cmd_index = @intCast(u16, self.load_commands.items.len); | 4292 | self.text_segment_cmd_index = @intCast(u8, self.segments.items.len); |
| 4323 | const needed_size = if (self.mode == .incremental) blk: { | 4293 | const needed_size = if (self.mode == .incremental) blk: { |
| 4324 | const headerpad_size = @maximum(self.base.options.headerpad_size orelse 0, default_headerpad_size); | 4294 | const headerpad_size = @maximum(self.base.options.headerpad_size orelse 0, default_headerpad_size); |
| 4325 | const program_code_size_hint = self.base.options.program_code_size_hint; | 4295 | const program_code_size_hint = self.base.options.program_code_size_hint; |
| ... | @@ -4329,20 +4299,15 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4329,20 +4299,15 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4329 | log.debug("found __TEXT segment free space 0x{x} to 0x{x}", .{ 0, needed_size }); | 4299 | log.debug("found __TEXT segment free space 0x{x} to 0x{x}", .{ 0, needed_size }); |
| 4330 | break :blk needed_size; | 4300 | break :blk needed_size; |
| 4331 | } else 0; | 4301 | } else 0; |
| 4332 | try self.load_commands.append(self.base.allocator, .{ | 4302 | try self.segments.append(gpa, .{ |
| 4333 | .segment = .{ | 4303 | .segname = makeStaticString("__TEXT"), |
| 4334 | .inner = .{ | 4304 | .vmaddr = aligned_pagezero_vmsize, |
| 4335 | .segname = makeStaticString("__TEXT"), | 4305 | .vmsize = needed_size, |
| 4336 | .vmaddr = aligned_pagezero_vmsize, | 4306 | .filesize = needed_size, |
| 4337 | .vmsize = needed_size, | 4307 | .maxprot = macho.PROT.READ | macho.PROT.EXEC, |
| 4338 | .filesize = needed_size, | 4308 | .initprot = macho.PROT.READ | macho.PROT.EXEC, |
| 4339 | .maxprot = macho.PROT.READ | macho.PROT.EXEC, | 4309 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 4340 | .initprot = macho.PROT.READ | macho.PROT.EXEC, | | |
| 4341 | .cmdsize = @sizeOf(macho.segment_command_64), | | |
| 4342 | }, | | |
| 4343 | }, | | |
| 4344 | }); | 4310 | }); |
| 4345 | self.load_commands_dirty = true; | | |
| 4346 | } | 4311 | } |
| 4347 | | 4312 | |
| 4348 | if (self.text_section_index == null) { | 4313 | if (self.text_section_index == null) { |
| ... | @@ -4419,7 +4384,7 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4419,7 +4384,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4419 | } | 4384 | } |
| 4420 | | 4385 | |
| 4421 | if (self.data_const_segment_cmd_index == null) { | 4386 | if (self.data_const_segment_cmd_index == null) { |
| 4422 | self.data_const_segment_cmd_index = @intCast(u16, self.load_commands.items.len); | 4387 | self.data_const_segment_cmd_index = @intCast(u8, self.segments.items.len); |
| 4423 | var vmaddr: u64 = 0; | 4388 | var vmaddr: u64 = 0; |
| 4424 | var fileoff: u64 = 0; | 4389 | var fileoff: u64 = 0; |
| 4425 | var needed_size: u64 = 0; | 4390 | var needed_size: u64 = 0; |
| ... | @@ -4434,21 +4399,16 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4434,21 +4399,16 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4434 | fileoff + needed_size, | 4399 | fileoff + needed_size, |
| 4435 | }); | 4400 | }); |
| 4436 | } | 4401 | } |
| 4437 | try self.load_commands.append(self.base.allocator, .{ | 4402 | try self.segments.append(gpa, .{ |
| 4438 | .segment = .{ | 4403 | .segname = makeStaticString("__DATA_CONST"), |
| 4439 | .inner = .{ | 4404 | .vmaddr = vmaddr, |
| 4440 | .segname = makeStaticString("__DATA_CONST"), | 4405 | .vmsize = needed_size, |
| 4441 | .vmaddr = vmaddr, | 4406 | .fileoff = fileoff, |
| 4442 | .vmsize = needed_size, | 4407 | .filesize = needed_size, |
| 4443 | .fileoff = fileoff, | 4408 | .maxprot = macho.PROT.READ | macho.PROT.WRITE, |
| 4444 | .filesize = needed_size, | 4409 | .initprot = macho.PROT.READ | macho.PROT.WRITE, |
| 4445 | .maxprot = macho.PROT.READ | macho.PROT.WRITE, | 4410 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 4446 | .initprot = macho.PROT.READ | macho.PROT.WRITE, | | |
| 4447 | .cmdsize = @sizeOf(macho.segment_command_64), | | |
| 4448 | }, | | |
| 4449 | }, | | |
| 4450 | }); | 4411 | }); |
| 4451 | self.load_commands_dirty = true; | | |
| 4452 | } | 4412 | } |
| 4453 | | 4413 | |
| 4454 | if (self.got_section_index == null) { | 4414 | if (self.got_section_index == null) { |
| ... | @@ -4469,7 +4429,7 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4469,7 +4429,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4469 | } | 4429 | } |
| 4470 | | 4430 | |
| 4471 | if (self.data_segment_cmd_index == null) { | 4431 | if (self.data_segment_cmd_index == null) { |
| 4472 | self.data_segment_cmd_index = @intCast(u16, self.load_commands.items.len); | 4432 | self.data_segment_cmd_index = @intCast(u8, self.segments.items.len); |
| 4473 | var vmaddr: u64 = 0; | 4433 | var vmaddr: u64 = 0; |
| 4474 | var fileoff: u64 = 0; | 4434 | var fileoff: u64 = 0; |
| 4475 | var needed_size: u64 = 0; | 4435 | var needed_size: u64 = 0; |
| ... | @@ -4484,21 +4444,16 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4484,21 +4444,16 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4484 | fileoff + needed_size, | 4444 | fileoff + needed_size, |
| 4485 | }); | 4445 | }); |
| 4486 | } | 4446 | } |
| 4487 | try self.load_commands.append(self.base.allocator, .{ | 4447 | try self.segments.append(gpa, .{ |
| 4488 | .segment = .{ | 4448 | .segname = makeStaticString("__DATA"), |
| 4489 | .inner = .{ | 4449 | .vmaddr = vmaddr, |
| 4490 | .segname = makeStaticString("__DATA"), | 4450 | .vmsize = needed_size, |
| 4491 | .vmaddr = vmaddr, | 4451 | .fileoff = fileoff, |
| 4492 | .vmsize = needed_size, | 4452 | .filesize = needed_size, |
| 4493 | .fileoff = fileoff, | 4453 | .maxprot = macho.PROT.READ | macho.PROT.WRITE, |
| 4494 | .filesize = needed_size, | 4454 | .initprot = macho.PROT.READ | macho.PROT.WRITE, |
| 4495 | .maxprot = macho.PROT.READ | macho.PROT.WRITE, | 4455 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 4496 | .initprot = macho.PROT.READ | macho.PROT.WRITE, | | |
| 4497 | .cmdsize = @sizeOf(macho.segment_command_64), | | |
| 4498 | }, | | |
| 4499 | }, | | |
| 4500 | }); | 4456 | }); |
| 4501 | self.load_commands_dirty = true; | | |
| 4502 | } | 4457 | } |
| 4503 | | 4458 | |
| 4504 | if (self.la_symbol_ptr_section_index == null) { | 4459 | if (self.la_symbol_ptr_section_index == null) { |
| ... | @@ -4602,7 +4557,7 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4602,7 +4557,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4602 | } | 4557 | } |
| 4603 | | 4558 | |
| 4604 | if (self.linkedit_segment_cmd_index == null) { | 4559 | if (self.linkedit_segment_cmd_index == null) { |
| 4605 | self.linkedit_segment_cmd_index = @intCast(u16, self.load_commands.items.len); | 4560 | self.linkedit_segment_cmd_index = @intCast(u8, self.segments.items.len); |
| 4606 | var vmaddr: u64 = 0; | 4561 | var vmaddr: u64 = 0; |
| 4607 | var fileoff: u64 = 0; | 4562 | var fileoff: u64 = 0; |
| 4608 | if (self.mode == .incremental) { | 4563 | if (self.mode == .incremental) { |
| ... | @@ -4611,249 +4566,113 @@ fn populateMissingMetadata(self: *MachO) !void { | ... | @@ -4611,249 +4566,113 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4611 | fileoff = base.fileoff; | 4566 | fileoff = base.fileoff; |
| 4612 | log.debug("found __LINKEDIT segment free space at 0x{x}", .{fileoff}); | 4567 | log.debug("found __LINKEDIT segment free space at 0x{x}", .{fileoff}); |
| 4613 | } | 4568 | } |
| 4614 | try self.load_commands.append(self.base.allocator, .{ | 4569 | try self.segments.append(gpa, .{ |
| 4615 | .segment = .{ | 4570 | .segname = makeStaticString("__LINKEDIT"), |
| 4616 | .inner = .{ | 4571 | .vmaddr = vmaddr, |
| 4617 | .segname = makeStaticString("__LINKEDIT"), | 4572 | .fileoff = fileoff, |
| 4618 | .vmaddr = vmaddr, | 4573 | .maxprot = macho.PROT.READ, |
| 4619 | .fileoff = fileoff, | 4574 | .initprot = macho.PROT.READ, |
| 4620 | .maxprot = macho.PROT.READ, | 4575 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 4621 | .initprot = macho.PROT.READ, | | |
| 4622 | .cmdsize = @sizeOf(macho.segment_command_64), | | |
| 4623 | }, | | |
| 4624 | }, | | |
| 4625 | }); | 4576 | }); |
| 4626 | self.load_commands_dirty = true; | | |
| 4627 | } | | |
| 4628 | | | |
| 4629 | if (self.dyld_info_cmd_index == null) { | | |
| 4630 | self.dyld_info_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4631 | try self.load_commands.append(self.base.allocator, .{ | | |
| 4632 | .dyld_info_only = .{ | | |
| 4633 | .cmd = .DYLD_INFO_ONLY, | | |
| 4634 | .cmdsize = @sizeOf(macho.dyld_info_command), | | |
| 4635 | .rebase_off = 0, | | |
| 4636 | .rebase_size = 0, | | |
| 4637 | .bind_off = 0, | | |
| 4638 | .bind_size = 0, | | |
| 4639 | .weak_bind_off = 0, | | |
| 4640 | .weak_bind_size = 0, | | |
| 4641 | .lazy_bind_off = 0, | | |
| 4642 | .lazy_bind_size = 0, | | |
| 4643 | .export_off = 0, | | |
| 4644 | .export_size = 0, | | |
| 4645 | }, | | |
| 4646 | }); | | |
| 4647 | self.load_commands_dirty = true; | | |
| 4648 | } | | |
| 4649 | | | |
| 4650 | if (self.symtab_cmd_index == null) { | | |
| 4651 | self.symtab_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4652 | try self.load_commands.append(self.base.allocator, .{ | | |
| 4653 | .symtab = .{ | | |
| 4654 | .cmdsize = @sizeOf(macho.symtab_command), | | |
| 4655 | .symoff = 0, | | |
| 4656 | .nsyms = 0, | | |
| 4657 | .stroff = 0, | | |
| 4658 | .strsize = 0, | | |
| 4659 | }, | | |
| 4660 | }); | | |
| 4661 | self.load_commands_dirty = true; | | |
| 4662 | } | | |
| 4663 | | | |
| 4664 | if (self.dysymtab_cmd_index == null) { | | |
| 4665 | self.dysymtab_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4666 | try self.load_commands.append(self.base.allocator, .{ | | |
| 4667 | .dysymtab = .{ | | |
| 4668 | .cmdsize = @sizeOf(macho.dysymtab_command), | | |
| 4669 | .ilocalsym = 0, | | |
| 4670 | .nlocalsym = 0, | | |
| 4671 | .iextdefsym = 0, | | |
| 4672 | .nextdefsym = 0, | | |
| 4673 | .iundefsym = 0, | | |
| 4674 | .nundefsym = 0, | | |
| 4675 | .tocoff = 0, | | |
| 4676 | .ntoc = 0, | | |
| 4677 | .modtaboff = 0, | | |
| 4678 | .nmodtab = 0, | | |
| 4679 | .extrefsymoff = 0, | | |
| 4680 | .nextrefsyms = 0, | | |
| 4681 | .indirectsymoff = 0, | | |
| 4682 | .nindirectsyms = 0, | | |
| 4683 | .extreloff = 0, | | |
| 4684 | .nextrel = 0, | | |
| 4685 | .locreloff = 0, | | |
| 4686 | .nlocrel = 0, | | |
| 4687 | }, | | |
| 4688 | }); | | |
| 4689 | self.load_commands_dirty = true; | | |
| 4690 | } | 4577 | } |
| | 4578 | } |
| 4691 | | 4579 | |
| 4692 | if (self.dylinker_cmd_index == null) { | 4580 | inline fn calcInstallNameLen(cmd_size: u64, name: []const u8, assume_max_path_len: bool) u64 { |
| 4693 | self.dylinker_cmd_index = @intCast(u16, self.load_commands.items.len); | 4581 | const name_len = if (assume_max_path_len) std.os.PATH_MAX else std.mem.len(name) + 1; |
| 4694 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( | 4582 | return mem.alignForwardGeneric(u64, cmd_size + name_len, @alignOf(u64)); |
| 4695 | u64, | 4583 | } |
| 4696 | @sizeOf(macho.dylinker_command) + mem.sliceTo(default_dyld_path, 0).len, | | |
| 4697 | @sizeOf(u64), | | |
| 4698 | )); | | |
| 4699 | var dylinker_cmd = macho.emptyGenericCommandWithData(macho.dylinker_command{ | | |
| 4700 | .cmd = .LOAD_DYLINKER, | | |
| 4701 | .cmdsize = cmdsize, | | |
| 4702 | .name = @sizeOf(macho.dylinker_command), | | |
| 4703 | }); | | |
| 4704 | dylinker_cmd.data = try self.base.allocator.alloc(u8, cmdsize - dylinker_cmd.inner.name); | | |
| 4705 | mem.set(u8, dylinker_cmd.data, 0); | | |
| 4706 | mem.copy(u8, dylinker_cmd.data, mem.sliceTo(default_dyld_path, 0)); | | |
| 4707 | try self.load_commands.append(self.base.allocator, .{ .dylinker = dylinker_cmd }); | | |
| 4708 | self.load_commands_dirty = true; | | |
| 4709 | } | | |
| 4710 | | | |
| 4711 | if (self.main_cmd_index == null and self.base.options.output_mode == .Exe) { | | |
| 4712 | self.main_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4713 | try self.load_commands.append(self.base.allocator, .{ | | |
| 4714 | .main = .{ | | |
| 4715 | .cmdsize = @sizeOf(macho.entry_point_command), | | |
| 4716 | .entryoff = 0x0, | | |
| 4717 | .stacksize = 0, | | |
| 4718 | }, | | |
| 4719 | }); | | |
| 4720 | self.load_commands_dirty = true; | | |
| 4721 | } | | |
| 4722 | | 4584 | |
| 4723 | if (self.dylib_id_cmd_index == null and self.base.options.output_mode == .Lib) { | 4585 | fn calcLCsSize(self: *MachO, assume_max_path_len: bool) !u32 { |
| 4724 | self.dylib_id_cmd_index = @intCast(u16, self.load_commands.items.len); | 4586 | const gpa = self.base.allocator; |
| 4725 | const install_name = self.base.options.install_name orelse self.base.options.emit.?.sub_path; | 4587 | var sizeofcmds: u64 = 0; |
| 4726 | const current_version = self.base.options.version orelse | 4588 | for (self.segments.items) |seg| { |
| 4727 | std.builtin.Version{ .major = 1, .minor = 0, .patch = 0 }; | 4589 | sizeofcmds += seg.nsects * @sizeOf(macho.section_64) + @sizeOf(macho.segment_command_64); |
| 4728 | const compat_version = self.base.options.compatibility_version orelse | 4590 | } |
| 4729 | std.builtin.Version{ .major = 1, .minor = 0, .patch = 0 }; | 4591 | |
| 4730 | var dylib_cmd = try macho.createLoadDylibCommand( | 4592 | // LC_DYLD_INFO_ONLY |
| 4731 | self.base.allocator, | 4593 | sizeofcmds += @sizeOf(macho.dyld_info_command); |
| 4732 | .ID_DYLIB, | 4594 | // LC_FUNCTION_STARTS |
| 4733 | install_name, | 4595 | if (self.text_section_index != null) { |
| 4734 | 2, | 4596 | sizeofcmds += @sizeOf(macho.linkedit_data_command); |
| 4735 | current_version.major << 16 | current_version.minor << 8 | current_version.patch, | 4597 | } |
| 4736 | compat_version.major << 16 | compat_version.minor << 8 | compat_version.patch, | 4598 | // LC_DATA_IN_CODE |
| | 4599 | sizeofcmds += @sizeOf(macho.linkedit_data_command); |
| | 4600 | // LC_SYMTAB |
| | 4601 | sizeofcmds += @sizeOf(macho.symtab_command); |
| | 4602 | // LC_DYSYMTAB |
| | 4603 | sizeofcmds += @sizeOf(macho.dysymtab_command); |
| | 4604 | // LC_LOAD_DYLINKER |
| | 4605 | sizeofcmds += calcInstallNameLen( |
| | 4606 | @sizeOf(macho.dylinker_command), |
| | 4607 | mem.sliceTo(default_dyld_path, 0), |
| | 4608 | false, |
| | 4609 | ); |
| | 4610 | // LC_MAIN |
| | 4611 | if (self.base.options.output_mode == .Exe) { |
| | 4612 | sizeofcmds += @sizeOf(macho.entry_point_command); |
| | 4613 | } |
| | 4614 | // LC_ID_DYLIB |
| | 4615 | if (self.base.options.output_mode == .Lib) { |
| | 4616 | sizeofcmds += blk: { |
| | 4617 | const install_name = self.base.options.install_name orelse self.base.options.emit.?.sub_path; |
| | 4618 | break :blk calcInstallNameLen( |
| | 4619 | @sizeOf(macho.dylib_command), |
| | 4620 | install_name, |
| | 4621 | assume_max_path_len, |
| | 4622 | ); |
| | 4623 | }; |
| | 4624 | } |
| | 4625 | // LC_RPATH |
| | 4626 | { |
| | 4627 | var it = RpathIterator.init(gpa, self.base.options.rpath_list); |
| | 4628 | defer it.deinit(); |
| | 4629 | while (try it.next()) |rpath| { |
| | 4630 | sizeofcmds += calcInstallNameLen( |
| | 4631 | @sizeOf(macho.rpath_command), |
| | 4632 | rpath, |
| | 4633 | assume_max_path_len, |
| | 4634 | ); |
| | 4635 | } |
| | 4636 | } |
| | 4637 | // LC_SOURCE_VERSION |
| | 4638 | sizeofcmds += @sizeOf(macho.source_version_command); |
| | 4639 | // LC_BUILD_VERSION |
| | 4640 | sizeofcmds += @sizeOf(macho.build_version_command) + @sizeOf(macho.build_tool_version); |
| | 4641 | // LC_UUID |
| | 4642 | sizeofcmds += @sizeOf(macho.uuid_command); |
| | 4643 | // LC_LOAD_DYLIB |
| | 4644 | for (self.referenced_dylibs.keys()) |id| { |
| | 4645 | const dylib = self.dylibs.items[id]; |
| | 4646 | const dylib_id = dylib.id orelse unreachable; |
| | 4647 | sizeofcmds += calcInstallNameLen( |
| | 4648 | @sizeOf(macho.dylib_command), |
| | 4649 | dylib_id.name, |
| | 4650 | assume_max_path_len, |
| 4737 | ); | 4651 | ); |
| 4738 | errdefer dylib_cmd.deinit(self.base.allocator); | | |
| 4739 | try self.load_commands.append(self.base.allocator, .{ .dylib = dylib_cmd }); | | |
| 4740 | self.load_commands_dirty = true; | | |
| 4741 | } | 4652 | } |
| 4742 | | 4653 | // LC_CODE_SIGNATURE |
| 4743 | if (self.source_version_cmd_index == null) { | 4654 | { |
| 4744 | self.source_version_cmd_index = @intCast(u16, self.load_commands.items.len); | 4655 | const target = self.base.options.target; |
| 4745 | try self.load_commands.append(self.base.allocator, .{ | 4656 | const requires_codesig = blk: { |
| 4746 | .source_version = .{ | 4657 | if (self.base.options.entitlements) |_| break :blk true; |
| 4747 | .cmdsize = @sizeOf(macho.source_version_command), | 4658 | if (target.cpu.arch == .aarch64 and (target.os.tag == .macos or target.abi == .simulator)) |
| 4748 | .version = 0x0, | 4659 | break :blk true; |
| 4749 | }, | 4660 | break :blk false; |
| 4750 | }); | 4661 | }; |
| 4751 | self.load_commands_dirty = true; | 4662 | if (requires_codesig) { |
| | 4663 | sizeofcmds += @sizeOf(macho.linkedit_data_command); |
| | 4664 | } |
| 4752 | } | 4665 | } |
| 4753 | | 4666 | |
| 4754 | if (self.build_version_cmd_index == null) { | 4667 | return @intCast(u32, sizeofcmds); |
| 4755 | self.build_version_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4756 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( | | |
| 4757 | u64, | | |
| 4758 | @sizeOf(macho.build_version_command) + @sizeOf(macho.build_tool_version), | | |
| 4759 | @sizeOf(u64), | | |
| 4760 | )); | | |
| 4761 | const platform_version = blk: { | | |
| 4762 | const ver = self.base.options.target.os.version_range.semver.min; | | |
| 4763 | const platform_version = ver.major << 16 | ver.minor << 8; | | |
| 4764 | break :blk platform_version; | | |
| 4765 | }; | | |
| 4766 | const sdk_version = if (self.base.options.native_darwin_sdk) |sdk| blk: { | | |
| 4767 | const ver = sdk.version; | | |
| 4768 | const sdk_version = ver.major << 16 | ver.minor << 8; | | |
| 4769 | break :blk sdk_version; | | |
| 4770 | } else platform_version; | | |
| 4771 | const is_simulator_abi = self.base.options.target.abi == .simulator; | | |
| 4772 | var cmd = macho.emptyGenericCommandWithData(macho.build_version_command{ | | |
| 4773 | .cmdsize = cmdsize, | | |
| 4774 | .platform = switch (self.base.options.target.os.tag) { | | |
| 4775 | .macos => .MACOS, | | |
| 4776 | .ios => if (is_simulator_abi) macho.PLATFORM.IOSSIMULATOR else macho.PLATFORM.IOS, | | |
| 4777 | .watchos => if (is_simulator_abi) macho.PLATFORM.WATCHOSSIMULATOR else macho.PLATFORM.WATCHOS, | | |
| 4778 | .tvos => if (is_simulator_abi) macho.PLATFORM.TVOSSIMULATOR else macho.PLATFORM.TVOS, | | |
| 4779 | else => unreachable, | | |
| 4780 | }, | | |
| 4781 | .minos = platform_version, | | |
| 4782 | .sdk = sdk_version, | | |
| 4783 | .ntools = 1, | | |
| 4784 | }); | | |
| 4785 | const ld_ver = macho.build_tool_version{ | | |
| 4786 | .tool = .LD, | | |
| 4787 | .version = 0x0, | | |
| 4788 | }; | | |
| 4789 | cmd.data = try self.base.allocator.alloc(u8, cmdsize - @sizeOf(macho.build_version_command)); | | |
| 4790 | mem.set(u8, cmd.data, 0); | | |
| 4791 | mem.copy(u8, cmd.data, mem.asBytes(&ld_ver)); | | |
| 4792 | try self.load_commands.append(self.base.allocator, .{ .build_version = cmd }); | | |
| 4793 | self.load_commands_dirty = true; | | |
| 4794 | } | | |
| 4795 | | | |
| 4796 | if (self.uuid_cmd_index == null) { | | |
| 4797 | self.uuid_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4798 | var uuid_cmd: macho.uuid_command = .{ | | |
| 4799 | .cmdsize = @sizeOf(macho.uuid_command), | | |
| 4800 | .uuid = undefined, | | |
| 4801 | }; | | |
| 4802 | std.crypto.random.bytes(&uuid_cmd.uuid); | | |
| 4803 | try self.load_commands.append(self.base.allocator, .{ .uuid = uuid_cmd }); | | |
| 4804 | self.load_commands_dirty = true; | | |
| 4805 | } | | |
| 4806 | | | |
| 4807 | if (self.function_starts_cmd_index == null) { | | |
| 4808 | self.function_starts_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4809 | try self.load_commands.append(self.base.allocator, .{ | | |
| 4810 | .linkedit_data = .{ | | |
| 4811 | .cmd = .FUNCTION_STARTS, | | |
| 4812 | .cmdsize = @sizeOf(macho.linkedit_data_command), | | |
| 4813 | .dataoff = 0, | | |
| 4814 | .datasize = 0, | | |
| 4815 | }, | | |
| 4816 | }); | | |
| 4817 | self.load_commands_dirty = true; | | |
| 4818 | } | | |
| 4819 | | | |
| 4820 | if (self.data_in_code_cmd_index == null) { | | |
| 4821 | self.data_in_code_cmd_index = @intCast(u16, self.load_commands.items.len); | | |
| 4822 | try self.load_commands.append(self.base.allocator, .{ | | |
| 4823 | .linkedit_data = .{ | | |
| 4824 | .cmd = .DATA_IN_CODE, | | |
| 4825 | .cmdsize = @sizeOf(macho.linkedit_data_command), | | |
| 4826 | .dataoff = 0, | | |
| 4827 | .datasize = 0, | | |
| 4828 | }, | | |
| 4829 | }); | | |
| 4830 | self.load_commands_dirty = true; | | |
| 4831 | } | | |
| 4832 | } | 4668 | } |
| 4833 | | 4669 | |
| 4834 | fn calcMinHeaderpad(self: *MachO) u64 { | 4670 | fn calcMinHeaderPad(self: *MachO) !u64 { |
| 4835 | var sizeofcmds: u32 = 0; | 4671 | var padding: u32 = (try self.calcLCsSize(false)) + (self.base.options.headerpad_size orelse 0); |
| 4836 | for (self.load_commands.items) |lc| { | | |
| 4837 | if (lc.cmd() == .NONE) continue; | | |
| 4838 | sizeofcmds += lc.cmdsize(); | | |
| 4839 | } | | |
| 4840 | | | |
| 4841 | var padding: u32 = sizeofcmds + (self.base.options.headerpad_size orelse 0); | | |
| 4842 | log.debug("minimum requested headerpad size 0x{x}", .{padding + @sizeOf(macho.mach_header_64)}); | 4672 | log.debug("minimum requested headerpad size 0x{x}", .{padding + @sizeOf(macho.mach_header_64)}); |
| 4843 | | 4673 | |
| 4844 | if (self.base.options.headerpad_max_install_names) { | 4674 | if (self.base.options.headerpad_max_install_names) { |
| 4845 | var min_headerpad_size: u32 = 0; | 4675 | var min_headerpad_size: u32 = try self.calcLCsSize(true); |
| 4846 | for (self.load_commands.items) |lc| switch (lc.cmd()) { | | |
| 4847 | .ID_DYLIB, | | |
| 4848 | .LOAD_WEAK_DYLIB, | | |
| 4849 | .LOAD_DYLIB, | | |
| 4850 | .REEXPORT_DYLIB, | | |
| 4851 | => { | | |
| 4852 | min_headerpad_size += @sizeOf(macho.dylib_command) + std.os.PATH_MAX + 1; | | |
| 4853 | }, | | |
| 4854 | | | |
| 4855 | else => {}, | | |
| 4856 | }; | | |
| 4857 | log.debug("headerpad_max_install_names minimum headerpad size 0x{x}", .{ | 4676 | log.debug("headerpad_max_install_names minimum headerpad size 0x{x}", .{ |
| 4858 | min_headerpad_size + @sizeOf(macho.mach_header_64), | 4677 | min_headerpad_size + @sizeOf(macho.mach_header_64), |
| 4859 | }); | 4678 | }); |
| ... | @@ -4868,32 +4687,31 @@ fn calcMinHeaderpad(self: *MachO) u64 { | ... | @@ -4868,32 +4687,31 @@ fn calcMinHeaderpad(self: *MachO) u64 { |
| 4868 | fn allocateSegments(self: *MachO) !void { | 4687 | fn allocateSegments(self: *MachO) !void { |
| 4869 | try self.allocateSegment(self.text_segment_cmd_index, &.{ | 4688 | try self.allocateSegment(self.text_segment_cmd_index, &.{ |
| 4870 | self.pagezero_segment_cmd_index, | 4689 | self.pagezero_segment_cmd_index, |
| 4871 | }, self.calcMinHeaderpad()); | 4690 | }, try self.calcMinHeaderPad()); |
| 4872 | | 4691 | |
| 4873 | if (self.text_segment_cmd_index) |index| blk: { | 4692 | if (self.text_segment_cmd_index) |index| blk: { |
| 4874 | const seg = &self.load_commands.items[index].segment; | 4693 | const seg = &self.segments.items[index]; |
| 4875 | if (seg.sections.items.len == 0) break :blk; | 4694 | if (seg.nsects == 0) break :blk; |
| 4876 | | 4695 | |
| 4877 | // Shift all sections to the back to minimize jump size between __TEXT and __DATA segments. | 4696 | // Shift all sections to the back to minimize jump size between __TEXT and __DATA segments. |
| 4878 | var min_alignment: u32 = 0; | 4697 | var min_alignment: u32 = 0; |
| 4879 | for (seg.sections.items) |sect| { | 4698 | for (self.sections.items(.header)[0..seg.nsects]) |header| { |
| 4880 | const alignment = try math.powi(u32, 2, sect.@"align"); | 4699 | const alignment = try math.powi(u32, 2, header.@"align"); |
| 4881 | min_alignment = math.max(min_alignment, alignment); | 4700 | min_alignment = math.max(min_alignment, alignment); |
| 4882 | } | 4701 | } |
| 4883 | | 4702 | |
| 4884 | assert(min_alignment > 0); | 4703 | assert(min_alignment > 0); |
| 4885 | const last_sect_idx = seg.sections.items.len - 1; | 4704 | const last_header = self.sections.items(.header)[seg.nsects - 1]; |
| 4886 | const last_sect = seg.sections.items[last_sect_idx]; | | |
| 4887 | const shift: u32 = shift: { | 4705 | const shift: u32 = shift: { |
| 4888 | const diff = seg.inner.filesize - last_sect.offset - last_sect.size; | 4706 | const diff = seg.filesize - last_header.offset - last_header.size; |
| 4889 | const factor = @divTrunc(diff, min_alignment); | 4707 | const factor = @divTrunc(diff, min_alignment); |
| 4890 | break :shift @intCast(u32, factor * min_alignment); | 4708 | break :shift @intCast(u32, factor * min_alignment); |
| 4891 | }; | 4709 | }; |
| 4892 | | 4710 | |
| 4893 | if (shift > 0) { | 4711 | if (shift > 0) { |
| 4894 | for (seg.sections.items) |*sect| { | 4712 | for (self.sections.items(.header)[0..seg.nsects]) |*header| { |
| 4895 | sect.offset += shift; | 4713 | header.offset += shift; |
| 4896 | sect.addr += shift; | 4714 | header.addr += shift; |
| 4897 | } | 4715 | } |
| 4898 | } | 4716 | } |
| 4899 | } | 4717 | } |
| ... | @@ -4917,42 +4735,42 @@ fn allocateSegments(self: *MachO) !void { | ... | @@ -4917,42 +4735,42 @@ fn allocateSegments(self: *MachO) !void { |
| 4917 | }, 0); | 4735 | }, 0); |
| 4918 | } | 4736 | } |
| 4919 | | 4737 | |
| 4920 | fn allocateSegment(self: *MachO, maybe_index: ?u16, indices: []const ?u16, init_size: u64) !void { | 4738 | fn allocateSegment(self: *MachO, maybe_index: ?u8, indices: []const ?u8, init_size: u64) !void { |
| 4921 | const index = maybe_index orelse return; | 4739 | const index = maybe_index orelse return; |
| 4922 | const seg = &self.load_commands.items[index].segment; | 4740 | const seg = &self.segments.items[index]; |
| 4923 | | 4741 | |
| 4924 | const base = self.getSegmentAllocBase(indices); | 4742 | const base = self.getSegmentAllocBase(indices); |
| 4925 | seg.inner.vmaddr = base.vmaddr; | 4743 | seg.vmaddr = base.vmaddr; |
| 4926 | seg.inner.fileoff = base.fileoff; | 4744 | seg.fileoff = base.fileoff; |
| 4927 | seg.inner.filesize = init_size; | 4745 | seg.filesize = init_size; |
| 4928 | seg.inner.vmsize = init_size; | 4746 | seg.vmsize = init_size; |
| 4929 | | 4747 | |
| 4930 | // Allocate the sections according to their alignment at the beginning of the segment. | 4748 | // Allocate the sections according to their alignment at the beginning of the segment. |
| 4931 | var start = init_size; | 4749 | var start = init_size; |
| 4932 | for (seg.sections.items) |*sect| { | 4750 | const slice = self.sections.slice(); |
| 4933 | const is_zerofill = sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL; | 4751 | for (slice.items(.header)) |*header, sect_id| { |
| 4934 | const use_llvm = build_options.have_llvm and self.base.options.use_llvm; | 4752 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 4935 | const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1; | 4753 | if (segment_index != index) continue; |
| 4936 | const alignment = try math.powi(u32, 2, sect.@"align"); | 4754 | const is_zerofill = header.flags == macho.S_ZEROFILL or header.flags == macho.S_THREAD_LOCAL_ZEROFILL; |
| | 4755 | const alignment = try math.powi(u32, 2, header.@"align"); |
| 4937 | const start_aligned = mem.alignForwardGeneric(u64, start, alignment); | 4756 | const start_aligned = mem.alignForwardGeneric(u64, start, alignment); |
| 4938 | | 4757 | |
| 4939 | // TODO handle zerofill sections in stage2 | 4758 | header.offset = if (is_zerofill) |
| 4940 | sect.offset = if (is_zerofill and (use_stage1 or use_llvm)) | | |
| 4941 | 0 | 4759 | 0 |
| 4942 | else | 4760 | else |
| 4943 | @intCast(u32, seg.inner.fileoff + start_aligned); | 4761 | @intCast(u32, seg.fileoff + start_aligned); |
| 4944 | sect.addr = seg.inner.vmaddr + start_aligned; | 4762 | header.addr = seg.vmaddr + start_aligned; |
| 4945 | | 4763 | |
| 4946 | start = start_aligned + sect.size; | 4764 | start = start_aligned + header.size; |
| 4947 | | 4765 | |
| 4948 | if (!(is_zerofill and (use_stage1 or use_llvm))) { | 4766 | if (!is_zerofill) { |
| 4949 | seg.inner.filesize = start; | 4767 | seg.filesize = start; |
| 4950 | } | 4768 | } |
| 4951 | seg.inner.vmsize = start; | 4769 | seg.vmsize = start; |
| 4952 | } | 4770 | } |
| 4953 | | 4771 | |
| 4954 | seg.inner.filesize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size); | 4772 | seg.filesize = mem.alignForwardGeneric(u64, seg.filesize, self.page_size); |
| 4955 | seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.vmsize, self.page_size); | 4773 | seg.vmsize = mem.alignForwardGeneric(u64, seg.vmsize, self.page_size); |
| 4956 | } | 4774 | } |
| 4957 | | 4775 | |
| 4958 | const InitSectionOpts = struct { | 4776 | const InitSectionOpts = struct { |
| ... | @@ -4963,16 +4781,16 @@ const InitSectionOpts = struct { | ... | @@ -4963,16 +4781,16 @@ const InitSectionOpts = struct { |
| 4963 | | 4781 | |
| 4964 | fn initSection( | 4782 | fn initSection( |
| 4965 | self: *MachO, | 4783 | self: *MachO, |
| 4966 | segment_id: u16, | 4784 | segment_id: u8, |
| 4967 | sectname: []const u8, | 4785 | sectname: []const u8, |
| 4968 | size: u64, | 4786 | size: u64, |
| 4969 | alignment: u32, | 4787 | alignment: u32, |
| 4970 | opts: InitSectionOpts, | 4788 | opts: InitSectionOpts, |
| 4971 | ) !u16 { | 4789 | ) !u8 { |
| 4972 | const seg = &self.load_commands.items[segment_id].segment; | 4790 | const seg = &self.segments.items[segment_id]; |
| 4973 | var sect = macho.section_64{ | 4791 | var header = macho.section_64{ |
| 4974 | .sectname = makeStaticString(sectname), | 4792 | .sectname = makeStaticString(sectname), |
| 4975 | .segname = seg.inner.segname, | 4793 | .segname = seg.segname, |
| 4976 | .size = if (self.mode == .incremental) @intCast(u32, size) else 0, | 4794 | .size = if (self.mode == .incremental) @intCast(u32, size) else 0, |
| 4977 | .@"align" = alignment, | 4795 | .@"align" = alignment, |
| 4978 | .flags = opts.flags, | 4796 | .flags = opts.flags, |
| ... | @@ -4982,165 +4800,157 @@ fn initSection( | ... | @@ -4982,165 +4800,157 @@ fn initSection( |
| 4982 | | 4800 | |
| 4983 | if (self.mode == .incremental) { | 4801 | if (self.mode == .incremental) { |
| 4984 | const alignment_pow_2 = try math.powi(u32, 2, alignment); | 4802 | const alignment_pow_2 = try math.powi(u32, 2, alignment); |
| 4985 | const padding: ?u32 = if (segment_id == self.text_segment_cmd_index.?) | 4803 | const padding: ?u64 = if (segment_id == self.text_segment_cmd_index.?) |
| 4986 | @maximum(self.base.options.headerpad_size orelse 0, default_headerpad_size) | 4804 | try self.calcMinHeaderPad() |
| 4987 | else | 4805 | else |
| 4988 | null; | 4806 | null; |
| 4989 | const off = self.findFreeSpace(segment_id, alignment_pow_2, padding); | 4807 | const off = self.findFreeSpace(segment_id, alignment_pow_2, padding); |
| 4990 | log.debug("allocating {s},{s} section from 0x{x} to 0x{x}", .{ | 4808 | log.debug("allocating {s},{s} section from 0x{x} to 0x{x}", .{ |
| 4991 | sect.segName(), | 4809 | header.segName(), |
| 4992 | sect.sectName(), | 4810 | header.sectName(), |
| 4993 | off, | 4811 | off, |
| 4994 | off + size, | 4812 | off + size, |
| 4995 | }); | 4813 | }); |
| 4996 | | 4814 | |
| 4997 | sect.addr = seg.inner.vmaddr + off - seg.inner.fileoff; | 4815 | header.addr = seg.vmaddr + off - seg.fileoff; |
| 4998 | | | |
| 4999 | const is_zerofill = opts.flags == macho.S_ZEROFILL or opts.flags == macho.S_THREAD_LOCAL_ZEROFILL; | | |
| 5000 | const use_llvm = build_options.have_llvm and self.base.options.use_llvm; | | |
| 5001 | const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1; | | |
| 5002 | | 4816 | |
| 5003 | // TODO handle zerofill in stage2 | 4817 | // TODO handle zerofill in stage2 |
| 5004 | if (!(is_zerofill and (use_stage1 or use_llvm))) { | 4818 | // const is_zerofill = opts.flags == macho.S_ZEROFILL or opts.flags == macho.S_THREAD_LOCAL_ZEROFILL; |
| 5005 | sect.offset = @intCast(u32, off); | 4819 | header.offset = @intCast(u32, off); |
| 5006 | } | | |
| 5007 | } | | |
| 5008 | | 4820 | |
| 5009 | const index = @intCast(u16, seg.sections.items.len); | 4821 | try self.updateSectionOrdinals(); |
| 5010 | try seg.sections.append(self.base.allocator, sect); | 4822 | } |
| 5011 | seg.inner.cmdsize += @sizeOf(macho.section_64); | | |
| 5012 | seg.inner.nsects += 1; | | |
| 5013 | | | |
| 5014 | const match = MatchingSection{ | | |
| 5015 | .seg = segment_id, | | |
| 5016 | .sect = index, | | |
| 5017 | }; | | |
| 5018 | _ = try self.section_ordinals.getOrPut(self.base.allocator, match); | | |
| 5019 | try self.atom_free_lists.putNoClobber(self.base.allocator, match, .{}); | | |
| 5020 | | 4823 | |
| 5021 | self.load_commands_dirty = true; | 4824 | const index = @intCast(u8, self.sections.slice().len); |
| 5022 | self.sections_order_dirty = true; | 4825 | try self.sections.append(self.base.allocator, .{ |
| | 4826 | .segment_index = segment_id, |
| | 4827 | .header = header, |
| | 4828 | }); |
| | 4829 | seg.cmdsize += @sizeOf(macho.section_64); |
| | 4830 | seg.nsects += 1; |
| 5023 | | 4831 | |
| 5024 | return index; | 4832 | return index; |
| 5025 | } | 4833 | } |
| 5026 | | 4834 | |
| 5027 | fn findFreeSpace(self: MachO, segment_id: u16, alignment: u64, start: ?u32) u64 { | 4835 | fn findFreeSpace(self: MachO, segment_id: u8, alignment: u64, start: ?u64) u64 { |
| 5028 | const seg = self.load_commands.items[segment_id].segment; | 4836 | const seg = self.segments.items[segment_id]; |
| 5029 | if (seg.sections.items.len == 0) { | 4837 | const indexes = self.getSectionIndexes(segment_id); |
| 5030 | return if (start) |v| v else seg.inner.fileoff; | 4838 | if (indexes.end - indexes.start == 0) { |
| | 4839 | return if (start) |v| v else seg.fileoff; |
| 5031 | } | 4840 | } |
| 5032 | const last_sect = seg.sections.items[seg.sections.items.len - 1]; | 4841 | const last_sect = self.sections.items(.header)[indexes.end - 1]; |
| 5033 | const final_off = last_sect.offset + padToIdeal(last_sect.size); | 4842 | const final_off = last_sect.offset + padToIdeal(last_sect.size); |
| 5034 | return mem.alignForwardGeneric(u64, final_off, alignment); | 4843 | return mem.alignForwardGeneric(u64, final_off, alignment); |
| 5035 | } | 4844 | } |
| 5036 | | 4845 | |
| 5037 | fn growSegment(self: *MachO, seg_id: u16, new_size: u64) !void { | 4846 | fn growSegment(self: *MachO, segment_index: u8, new_size: u64) !void { |
| 5038 | const seg = &self.load_commands.items[seg_id].segment; | 4847 | const segment = &self.segments.items[segment_index]; |
| 5039 | const new_seg_size = mem.alignForwardGeneric(u64, new_size, self.page_size); | 4848 | const new_segment_size = mem.alignForwardGeneric(u64, new_size, self.page_size); |
| 5040 | assert(new_seg_size > seg.inner.filesize); | 4849 | assert(new_segment_size > segment.filesize); |
| 5041 | const offset_amt = new_seg_size - seg.inner.filesize; | 4850 | const offset_amt = new_segment_size - segment.filesize; |
| 5042 | log.debug("growing segment {s} from 0x{x} to 0x{x}", .{ | 4851 | log.debug("growing segment {s} from 0x{x} to 0x{x}", .{ |
| 5043 | seg.inner.segname, | 4852 | segment.segname, |
| 5044 | seg.inner.filesize, | 4853 | segment.filesize, |
| 5045 | new_seg_size, | 4854 | new_segment_size, |
| 5046 | }); | 4855 | }); |
| 5047 | seg.inner.filesize = new_seg_size; | 4856 | segment.filesize = new_segment_size; |
| 5048 | seg.inner.vmsize = new_seg_size; | 4857 | segment.vmsize = new_segment_size; |
| 5049 | | 4858 | |
| 5050 | log.debug(" (new segment file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{ | 4859 | log.debug(" (new segment file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{ |
| 5051 | seg.inner.fileoff, | 4860 | segment.fileoff, |
| 5052 | seg.inner.fileoff + seg.inner.filesize, | 4861 | segment.fileoff + segment.filesize, |
| 5053 | seg.inner.vmaddr, | 4862 | segment.vmaddr, |
| 5054 | seg.inner.vmaddr + seg.inner.vmsize, | 4863 | segment.vmaddr + segment.vmsize, |
| 5055 | }); | 4864 | }); |
| 5056 | | 4865 | |
| 5057 | var next: usize = seg_id + 1; | 4866 | var next: u8 = segment_index + 1; |
| 5058 | while (next < self.linkedit_segment_cmd_index.? + 1) : (next += 1) { | 4867 | while (next < self.linkedit_segment_cmd_index.? + 1) : (next += 1) { |
| 5059 | const next_seg = &self.load_commands.items[next].segment; | 4868 | const next_segment = &self.segments.items[next]; |
| 5060 | | 4869 | |
| 5061 | try MachO.copyRangeAllOverlappingAlloc( | 4870 | try MachO.copyRangeAllOverlappingAlloc( |
| 5062 | self.base.allocator, | 4871 | self.base.allocator, |
| 5063 | self.base.file.?, | 4872 | self.base.file.?, |
| 5064 | next_seg.inner.fileoff, | 4873 | next_segment.fileoff, |
| 5065 | next_seg.inner.fileoff + offset_amt, | 4874 | next_segment.fileoff + offset_amt, |
| 5066 | math.cast(usize, next_seg.inner.filesize) orelse return error.Overflow, | 4875 | math.cast(usize, next_segment.filesize) orelse return error.Overflow, |
| 5067 | ); | 4876 | ); |
| 5068 | | 4877 | |
| 5069 | next_seg.inner.fileoff += offset_amt; | 4878 | next_segment.fileoff += offset_amt; |
| 5070 | next_seg.inner.vmaddr += offset_amt; | 4879 | next_segment.vmaddr += offset_amt; |
| 5071 | | 4880 | |
| 5072 | log.debug(" (new {s} segment file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{ | 4881 | log.debug(" (new {s} segment file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{ |
| 5073 | next_seg.inner.segname, | 4882 | next_segment.segname, |
| 5074 | next_seg.inner.fileoff, | 4883 | next_segment.fileoff, |
| 5075 | next_seg.inner.fileoff + next_seg.inner.filesize, | 4884 | next_segment.fileoff + next_segment.filesize, |
| 5076 | next_seg.inner.vmaddr, | 4885 | next_segment.vmaddr, |
| 5077 | next_seg.inner.vmaddr + next_seg.inner.vmsize, | 4886 | next_segment.vmaddr + next_segment.vmsize, |
| 5078 | }); | 4887 | }); |
| 5079 | | 4888 | |
| 5080 | for (next_seg.sections.items) |*moved_sect, moved_sect_id| { | 4889 | const indexes = self.getSectionIndexes(next); |
| 5081 | moved_sect.offset += @intCast(u32, offset_amt); | 4890 | for (self.sections.items(.header)[indexes.start..indexes.end]) |*header, i| { |
| 5082 | moved_sect.addr += offset_amt; | 4891 | header.offset += @intCast(u32, offset_amt); |
| | 4892 | header.addr += offset_amt; |
| 5083 | | 4893 | |
| 5084 | log.debug(" (new {s},{s} file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{ | 4894 | log.debug(" (new {s},{s} file offsets from 0x{x} to 0x{x} (in memory 0x{x} to 0x{x}))", .{ |
| 5085 | moved_sect.segName(), | 4895 | header.segName(), |
| 5086 | moved_sect.sectName(), | 4896 | header.sectName(), |
| 5087 | moved_sect.offset, | 4897 | header.offset, |
| 5088 | moved_sect.offset + moved_sect.size, | 4898 | header.offset + header.size, |
| 5089 | moved_sect.addr, | 4899 | header.addr, |
| 5090 | moved_sect.addr + moved_sect.size, | 4900 | header.addr + header.size, |
| 5091 | }); | 4901 | }); |
| 5092 | | 4902 | |
| 5093 | try self.shiftLocalsByOffset(.{ | 4903 | try self.shiftLocalsByOffset(@intCast(u8, i + indexes.start), @intCast(i64, offset_amt)); |
| 5094 | .seg = @intCast(u16, next), | | |
| 5095 | .sect = @intCast(u16, moved_sect_id), | | |
| 5096 | }, @intCast(i64, offset_amt)); | | |
| 5097 | } | 4904 | } |
| 5098 | } | 4905 | } |
| 5099 | } | 4906 | } |
| 5100 | | 4907 | |
| 5101 | fn growSection(self: *MachO, match: MatchingSection, new_size: u32) !void { | 4908 | fn growSection(self: *MachO, sect_id: u8, new_size: u32) !void { |
| 5102 | const tracy = trace(@src()); | 4909 | const tracy = trace(@src()); |
| 5103 | defer tracy.end(); | 4910 | defer tracy.end(); |
| 5104 | | 4911 | |
| 5105 | const seg = &self.load_commands.items[match.seg].segment; | 4912 | const section = self.sections.get(sect_id); |
| 5106 | const sect = &seg.sections.items[match.sect]; | 4913 | const segment_index = section.segment_index; |
| | 4914 | const header = section.header; |
| | 4915 | const segment = self.segments.items[segment_index]; |
| 5107 | | 4916 | |
| 5108 | const alignment = try math.powi(u32, 2, sect.@"align"); | 4917 | const alignment = try math.powi(u32, 2, header.@"align"); |
| 5109 | const max_size = self.allocatedSize(match.seg, sect.offset); | 4918 | const max_size = self.allocatedSize(segment_index, header.offset); |
| 5110 | const ideal_size = padToIdeal(new_size); | 4919 | const ideal_size = padToIdeal(new_size); |
| 5111 | const needed_size = mem.alignForwardGeneric(u32, ideal_size, alignment); | 4920 | const needed_size = mem.alignForwardGeneric(u32, ideal_size, alignment); |
| 5112 | | 4921 | |
| 5113 | if (needed_size > max_size) blk: { | 4922 | if (needed_size > max_size) blk: { |
| 5114 | log.debug(" (need to grow! needed 0x{x}, max 0x{x})", .{ needed_size, max_size }); | 4923 | log.debug(" (need to grow! needed 0x{x}, max 0x{x})", .{ needed_size, max_size }); |
| 5115 | | 4924 | |
| 5116 | if (match.sect == seg.sections.items.len - 1) { | 4925 | const indexes = self.getSectionIndexes(segment_index); |
| | 4926 | if (sect_id == indexes.end - 1) { |
| 5117 | // Last section, just grow segments | 4927 | // Last section, just grow segments |
| 5118 | try self.growSegment(match.seg, seg.inner.filesize + needed_size - max_size); | 4928 | try self.growSegment(segment_index, segment.filesize + needed_size - max_size); |
| 5119 | break :blk; | 4929 | break :blk; |
| 5120 | } | 4930 | } |
| 5121 | | 4931 | |
| 5122 | // Need to move all sections below in file and address spaces. | 4932 | // Need to move all sections below in file and address spaces. |
| 5123 | const offset_amt = offset: { | 4933 | const offset_amt = offset: { |
| 5124 | const max_alignment = try self.getSectionMaxAlignment(match.seg, match.sect + 1); | 4934 | const max_alignment = try self.getSectionMaxAlignment(sect_id + 1, indexes.end); |
| 5125 | break :offset mem.alignForwardGeneric(u64, needed_size - max_size, max_alignment); | 4935 | break :offset mem.alignForwardGeneric(u64, needed_size - max_size, max_alignment); |
| 5126 | }; | 4936 | }; |
| 5127 | | 4937 | |
| 5128 | // Before we commit to this, check if the segment needs to grow too. | 4938 | // Before we commit to this, check if the segment needs to grow too. |
| 5129 | // We assume that each section header is growing linearly with the increasing | 4939 | // We assume that each section header is growing linearly with the increasing |
| 5130 | // file offset / virtual memory address space. | 4940 | // file offset / virtual memory address space. |
| 5131 | const last_sect = seg.sections.items[seg.sections.items.len - 1]; | 4941 | const last_sect_header = self.sections.items(.header)[indexes.end - 1]; |
| 5132 | const last_sect_off = last_sect.offset + last_sect.size; | 4942 | const last_sect_off = last_sect_header.offset + last_sect_header.size; |
| 5133 | const seg_off = seg.inner.fileoff + seg.inner.filesize; | 4943 | const seg_off = segment.fileoff + segment.filesize; |
| 5134 | | 4944 | |
| 5135 | if (last_sect_off + offset_amt > seg_off) { | 4945 | if (last_sect_off + offset_amt > seg_off) { |
| 5136 | // Need to grow segment first. | 4946 | // Need to grow segment first. |
| 5137 | const spill_size = (last_sect_off + offset_amt) - seg_off; | 4947 | const spill_size = (last_sect_off + offset_amt) - seg_off; |
| 5138 | try self.growSegment(match.seg, seg.inner.filesize + spill_size); | 4948 | try self.growSegment(segment_index, segment.filesize + spill_size); |
| 5139 | } | 4949 | } |
| 5140 | | 4950 | |
| 5141 | // We have enough space to expand within the segment, so move all sections by | 4951 | // We have enough space to expand within the segment, so move all sections by |
| 5142 | // the required amount and update their header offsets. | 4952 | // the required amount and update their header offsets. |
| 5143 | const next_sect = seg.sections.items[match.sect + 1]; | 4953 | const next_sect = self.sections.items(.header)[sect_id + 1]; |
| 5144 | const total_size = last_sect_off - next_sect.offset; | 4954 | const total_size = last_sect_off - next_sect.offset; |
| 5145 | | 4955 | |
| 5146 | try MachO.copyRangeAllOverlappingAlloc( | 4956 | try MachO.copyRangeAllOverlappingAlloc( |
| ... | @@ -5151,9 +4961,7 @@ fn growSection(self: *MachO, match: MatchingSection, new_size: u32) !void { | ... | @@ -5151,9 +4961,7 @@ fn growSection(self: *MachO, match: MatchingSection, new_size: u32) !void { |
| 5151 | math.cast(usize, total_size) orelse return error.Overflow, | 4961 | math.cast(usize, total_size) orelse return error.Overflow, |
| 5152 | ); | 4962 | ); |
| 5153 | | 4963 | |
| 5154 | var next = match.sect + 1; | 4964 | for (self.sections.items(.header)[sect_id + 1 .. indexes.end]) |*moved_sect, i| { |
| 5155 | while (next < seg.sections.items.len) : (next += 1) { | | |
| 5156 | const moved_sect = &seg.sections.items[next]; | | |
| 5157 | moved_sect.offset += @intCast(u32, offset_amt); | 4965 | moved_sect.offset += @intCast(u32, offset_amt); |
| 5158 | moved_sect.addr += offset_amt; | 4966 | moved_sect.addr += offset_amt; |
| 5159 | | 4967 | |
| ... | @@ -5166,49 +4974,45 @@ fn growSection(self: *MachO, match: MatchingSection, new_size: u32) !void { | ... | @@ -5166,49 +4974,45 @@ fn growSection(self: *MachO, match: MatchingSection, new_size: u32) !void { |
| 5166 | moved_sect.addr + moved_sect.size, | 4974 | moved_sect.addr + moved_sect.size, |
| 5167 | }); | 4975 | }); |
| 5168 | | 4976 | |
| 5169 | try self.shiftLocalsByOffset(.{ | 4977 | try self.shiftLocalsByOffset(@intCast(u8, sect_id + 1 + i), @intCast(i64, offset_amt)); |
| 5170 | .seg = match.seg, | | |
| 5171 | .sect = next, | | |
| 5172 | }, @intCast(i64, offset_amt)); | | |
| 5173 | } | 4978 | } |
| 5174 | } | 4979 | } |
| 5175 | } | 4980 | } |
| 5176 | | 4981 | |
| 5177 | fn allocatedSize(self: MachO, segment_id: u16, start: u64) u64 { | 4982 | fn allocatedSize(self: MachO, segment_id: u8, start: u64) u64 { |
| 5178 | const seg = self.load_commands.items[segment_id].segment; | 4983 | const segment = self.segments.items[segment_id]; |
| 5179 | assert(start >= seg.inner.fileoff); | 4984 | const indexes = self.getSectionIndexes(segment_id); |
| 5180 | var min_pos: u64 = seg.inner.fileoff + seg.inner.filesize; | 4985 | assert(start >= segment.fileoff); |
| | 4986 | var min_pos: u64 = segment.fileoff + segment.filesize; |
| 5181 | if (start > min_pos) return 0; | 4987 | if (start > min_pos) return 0; |
| 5182 | for (seg.sections.items) |section| { | 4988 | for (self.sections.items(.header)[indexes.start..indexes.end]) |header| { |
| 5183 | if (section.offset <= start) continue; | 4989 | if (header.offset <= start) continue; |
| 5184 | if (section.offset < min_pos) min_pos = section.offset; | 4990 | if (header.offset < min_pos) min_pos = header.offset; |
| 5185 | } | 4991 | } |
| 5186 | return min_pos - start; | 4992 | return min_pos - start; |
| 5187 | } | 4993 | } |
| 5188 | | 4994 | |
| 5189 | fn getSectionMaxAlignment(self: *MachO, segment_id: u16, start_sect_id: u16) !u32 { | 4995 | fn getSectionMaxAlignment(self: *MachO, start: u8, end: u8) !u32 { |
| 5190 | const seg = self.load_commands.items[segment_id].segment; | | |
| 5191 | var max_alignment: u32 = 1; | 4996 | var max_alignment: u32 = 1; |
| 5192 | var next = start_sect_id; | 4997 | const slice = self.sections.slice(); |
| 5193 | while (next < seg.sections.items.len) : (next += 1) { | 4998 | for (slice.items(.header)[start..end]) |header| { |
| 5194 | const sect = seg.sections.items[next]; | 4999 | const alignment = try math.powi(u32, 2, header.@"align"); |
| 5195 | const alignment = try math.powi(u32, 2, sect.@"align"); | | |
| 5196 | max_alignment = math.max(max_alignment, alignment); | 5000 | max_alignment = math.max(max_alignment, alignment); |
| 5197 | } | 5001 | } |
| 5198 | return max_alignment; | 5002 | return max_alignment; |
| 5199 | } | 5003 | } |
| 5200 | | 5004 | |
| 5201 | fn allocateAtomCommon(self: *MachO, atom: *Atom, match: MatchingSection) !void { | 5005 | fn allocateAtomCommon(self: *MachO, atom: *Atom, sect_id: u8) !void { |
| 5202 | const sym = atom.getSymbolPtr(self); | 5006 | const sym = atom.getSymbolPtr(self); |
| 5203 | if (self.mode == .incremental) { | 5007 | if (self.mode == .incremental) { |
| 5204 | const size = atom.size; | 5008 | const size = atom.size; |
| 5205 | const alignment = try math.powi(u32, 2, atom.alignment); | 5009 | const alignment = try math.powi(u32, 2, atom.alignment); |
| 5206 | const vaddr = try self.allocateAtom(atom, size, alignment, match); | 5010 | const vaddr = try self.allocateAtom(atom, size, alignment, sect_id); |
| 5207 | const sym_name = atom.getName(self); | 5011 | const sym_name = atom.getName(self); |
| 5208 | log.debug("allocated {s} atom at 0x{x}", .{ sym_name, vaddr }); | 5012 | log.debug("allocated {s} atom at 0x{x}", .{ sym_name, vaddr }); |
| 5209 | sym.n_value = vaddr; | 5013 | sym.n_value = vaddr; |
| 5210 | } else try self.addAtomToSection(atom, match); | 5014 | } else try self.addAtomToSection(atom, sect_id); |
| 5211 | sym.n_sect = self.getSectionOrdinal(match); | 5015 | sym.n_sect = sect_id + 1; |
| 5212 | } | 5016 | } |
| 5213 | | 5017 | |
| 5214 | fn allocateAtom( | 5018 | fn allocateAtom( |
| ... | @@ -5216,15 +5020,15 @@ fn allocateAtom( | ... | @@ -5216,15 +5020,15 @@ fn allocateAtom( |
| 5216 | atom: *Atom, | 5020 | atom: *Atom, |
| 5217 | new_atom_size: u64, | 5021 | new_atom_size: u64, |
| 5218 | alignment: u64, | 5022 | alignment: u64, |
| 5219 | match: MatchingSection, | 5023 | sect_id: u8, |
| 5220 | ) !u64 { | 5024 | ) !u64 { |
| 5221 | const tracy = trace(@src()); | 5025 | const tracy = trace(@src()); |
| 5222 | defer tracy.end(); | 5026 | defer tracy.end(); |
| 5223 | | 5027 | |
| 5224 | const sect = self.getSectionPtr(match); | 5028 | const header = &self.sections.items(.header)[sect_id]; |
| 5225 | var free_list = self.atom_free_lists.get(match).?; | 5029 | const free_list = &self.sections.items(.free_list)[sect_id]; |
| 5226 | const needs_padding = match.seg == self.text_segment_cmd_index.? and match.sect == self.text_section_index.?; | 5030 | const maybe_last_atom = &self.sections.items(.last_atom)[sect_id]; |
| 5227 | const new_atom_ideal_capacity = if (needs_padding) padToIdeal(new_atom_size) else new_atom_size; | 5031 | const new_atom_ideal_capacity = if (header.isCode()) padToIdeal(new_atom_size) else new_atom_size; |
| 5228 | | 5032 | |
| 5229 | // We use these to indicate our intention to update metadata, placing the new atom, | 5033 | // We use these to indicate our intention to update metadata, placing the new atom, |
| 5230 | // and possibly removing a free list node. | 5034 | // and possibly removing a free list node. |
| ... | @@ -5244,7 +5048,7 @@ fn allocateAtom( | ... | @@ -5244,7 +5048,7 @@ fn allocateAtom( |
| 5244 | // Is it enough that we could fit this new atom? | 5048 | // Is it enough that we could fit this new atom? |
| 5245 | const sym = big_atom.getSymbol(self); | 5049 | const sym = big_atom.getSymbol(self); |
| 5246 | const capacity = big_atom.capacity(self); | 5050 | const capacity = big_atom.capacity(self); |
| 5247 | const ideal_capacity = if (needs_padding) padToIdeal(capacity) else capacity; | 5051 | const ideal_capacity = if (header.isCode()) padToIdeal(capacity) else capacity; |
| 5248 | const ideal_capacity_end_vaddr = math.add(u64, sym.n_value, ideal_capacity) catch ideal_capacity; | 5052 | const ideal_capacity_end_vaddr = math.add(u64, sym.n_value, ideal_capacity) catch ideal_capacity; |
| 5249 | const capacity_end_vaddr = sym.n_value + capacity; | 5053 | const capacity_end_vaddr = sym.n_value + capacity; |
| 5250 | const new_start_vaddr_unaligned = capacity_end_vaddr - new_atom_ideal_capacity; | 5054 | const new_start_vaddr_unaligned = capacity_end_vaddr - new_atom_ideal_capacity; |
| ... | @@ -5272,30 +5076,28 @@ fn allocateAtom( | ... | @@ -5272,30 +5076,28 @@ fn allocateAtom( |
| 5272 | free_list_removal = i; | 5076 | free_list_removal = i; |
| 5273 | } | 5077 | } |
| 5274 | break :blk new_start_vaddr; | 5078 | break :blk new_start_vaddr; |
| 5275 | } else if (self.atoms.get(match)) |last| { | 5079 | } else if (maybe_last_atom.*) |last| { |
| 5276 | const last_symbol = last.getSymbol(self); | 5080 | const last_symbol = last.getSymbol(self); |
| 5277 | const ideal_capacity = if (needs_padding) padToIdeal(last.size) else last.size; | 5081 | const ideal_capacity = if (header.isCode()) padToIdeal(last.size) else last.size; |
| 5278 | const ideal_capacity_end_vaddr = last_symbol.n_value + ideal_capacity; | 5082 | const ideal_capacity_end_vaddr = last_symbol.n_value + ideal_capacity; |
| 5279 | const new_start_vaddr = mem.alignForwardGeneric(u64, ideal_capacity_end_vaddr, alignment); | 5083 | const new_start_vaddr = mem.alignForwardGeneric(u64, ideal_capacity_end_vaddr, alignment); |
| 5280 | atom_placement = last; | 5084 | atom_placement = last; |
| 5281 | break :blk new_start_vaddr; | 5085 | break :blk new_start_vaddr; |
| 5282 | } else { | 5086 | } else { |
| 5283 | break :blk mem.alignForwardGeneric(u64, sect.addr, alignment); | 5087 | break :blk mem.alignForwardGeneric(u64, header.addr, alignment); |
| 5284 | } | 5088 | } |
| 5285 | }; | 5089 | }; |
| 5286 | | 5090 | |
| 5287 | const expand_section = atom_placement == null or atom_placement.?.next == null; | 5091 | const expand_section = atom_placement == null or atom_placement.?.next == null; |
| 5288 | if (expand_section) { | 5092 | if (expand_section) { |
| 5289 | const needed_size = @intCast(u32, (vaddr + new_atom_size) - sect.addr); | 5093 | const needed_size = @intCast(u32, (vaddr + new_atom_size) - header.addr); |
| 5290 | try self.growSection(match, needed_size); | 5094 | try self.growSection(sect_id, needed_size); |
| 5291 | _ = try self.atoms.put(self.base.allocator, match, atom); | 5095 | maybe_last_atom.* = atom; |
| 5292 | sect.size = needed_size; | 5096 | header.size = needed_size; |
| 5293 | self.load_commands_dirty = true; | | |
| 5294 | } | 5097 | } |
| 5295 | const align_pow = @intCast(u32, math.log2(alignment)); | 5098 | const align_pow = @intCast(u32, math.log2(alignment)); |
| 5296 | if (sect.@"align" < align_pow) { | 5099 | if (header.@"align" < align_pow) { |
| 5297 | sect.@"align" = align_pow; | 5100 | header.@"align" = align_pow; |
| 5298 | self.load_commands_dirty = true; | | |
| 5299 | } | 5101 | } |
| 5300 | atom.size = new_atom_size; | 5102 | atom.size = new_atom_size; |
| 5301 | atom.alignment = align_pow; | 5103 | atom.alignment = align_pow; |
| ... | @@ -5322,20 +5124,19 @@ fn allocateAtom( | ... | @@ -5322,20 +5124,19 @@ fn allocateAtom( |
| 5322 | return vaddr; | 5124 | return vaddr; |
| 5323 | } | 5125 | } |
| 5324 | | 5126 | |
| 5325 | pub fn addAtomToSection(self: *MachO, atom: *Atom, match: MatchingSection) !void { | 5127 | pub fn addAtomToSection(self: *MachO, atom: *Atom, sect_id: u8) !void { |
| 5326 | if (self.atoms.getPtr(match)) |last| { | 5128 | var section = self.sections.get(sect_id); |
| 5327 | last.*.next = atom; | 5129 | if (section.header.size > 0) { |
| 5328 | atom.prev = last.*; | 5130 | section.last_atom.?.next = atom; |
| 5329 | last.* = atom; | 5131 | atom.prev = section.last_atom.?; |
| 5330 | } else { | | |
| 5331 | try self.atoms.putNoClobber(self.base.allocator, match, atom); | | |
| 5332 | } | 5132 | } |
| 5333 | const sect = self.getSectionPtr(match); | 5133 | section.last_atom = atom; |
| 5334 | const atom_alignment = try math.powi(u32, 2, atom.alignment); | 5134 | const atom_alignment = try math.powi(u32, 2, atom.alignment); |
| 5335 | const aligned_end_addr = mem.alignForwardGeneric(u64, sect.size, atom_alignment); | 5135 | const aligned_end_addr = mem.alignForwardGeneric(u64, section.header.size, atom_alignment); |
| 5336 | const padding = aligned_end_addr - sect.size; | 5136 | const padding = aligned_end_addr - section.header.size; |
| 5337 | sect.size += padding + atom.size; | 5137 | section.header.size += padding + atom.size; |
| 5338 | sect.@"align" = @maximum(sect.@"align", atom.alignment); | 5138 | section.header.@"align" = @maximum(section.header.@"align", atom.alignment); |
| | 5139 | self.sections.set(sect_id, section); |
| 5339 | } | 5140 | } |
| 5340 | | 5141 | |
| 5341 | pub fn getGlobalSymbol(self: *MachO, name: []const u8) !u32 { | 5142 | pub fn getGlobalSymbol(self: *MachO, name: []const u8) !u32 { |
| ... | @@ -5368,74 +5169,27 @@ pub fn getGlobalSymbol(self: *MachO, name: []const u8) !u32 { | ... | @@ -5368,74 +5169,27 @@ pub fn getGlobalSymbol(self: *MachO, name: []const u8) !u32 { |
| 5368 | return sym_index; | 5169 | return sym_index; |
| 5369 | } | 5170 | } |
| 5370 | | 5171 | |
| 5371 | fn getSegmentAllocBase(self: MachO, indices: []const ?u16) struct { vmaddr: u64, fileoff: u64 } { | 5172 | fn getSegmentAllocBase(self: MachO, indices: []const ?u8) struct { vmaddr: u64, fileoff: u64 } { |
| 5372 | for (indices) |maybe_prev_id| { | 5173 | for (indices) |maybe_prev_id| { |
| 5373 | const prev_id = maybe_prev_id orelse continue; | 5174 | const prev_id = maybe_prev_id orelse continue; |
| 5374 | const prev = self.load_commands.items[prev_id].segment; | 5175 | const prev = self.segments.items[prev_id]; |
| 5375 | return .{ | 5176 | return .{ |
| 5376 | .vmaddr = prev.inner.vmaddr + prev.inner.vmsize, | 5177 | .vmaddr = prev.vmaddr + prev.vmsize, |
| 5377 | .fileoff = prev.inner.fileoff + prev.inner.filesize, | 5178 | .fileoff = prev.fileoff + prev.filesize, |
| 5378 | }; | 5179 | }; |
| 5379 | } | 5180 | } |
| 5380 | return .{ .vmaddr = 0, .fileoff = 0 }; | 5181 | return .{ .vmaddr = 0, .fileoff = 0 }; |
| 5381 | } | 5182 | } |
| 5382 | | 5183 | |
| 5383 | fn pruneAndSortSectionsInSegment(self: *MachO, maybe_seg_id: *?u16, indices: []*?u16) !void { | 5184 | fn pruneAndSortSections(self: *MachO) !void { |
| 5384 | const seg_id = maybe_seg_id.* orelse return; | 5185 | const gpa = self.base.allocator; |
| 5385 | | | |
| 5386 | var mapping = std.AutoArrayHashMap(u16, ?u16).init(self.base.allocator); | | |
| 5387 | defer mapping.deinit(); | | |
| 5388 | | | |
| 5389 | const seg = &self.load_commands.items[seg_id].segment; | | |
| 5390 | var sections = seg.sections.toOwnedSlice(self.base.allocator); | | |
| 5391 | defer self.base.allocator.free(sections); | | |
| 5392 | try seg.sections.ensureTotalCapacity(self.base.allocator, sections.len); | | |
| 5393 | | | |
| 5394 | for (indices) |maybe_index| { | | |
| 5395 | const old_idx = maybe_index.* orelse continue; | | |
| 5396 | const sect = &sections[old_idx]; | | |
| 5397 | if (sect.size == 0) { | | |
| 5398 | log.debug("pruning section {s},{s}", .{ sect.segName(), sect.sectName() }); | | |
| 5399 | maybe_index.* = null; | | |
| 5400 | seg.inner.cmdsize -= @sizeOf(macho.section_64); | | |
| 5401 | seg.inner.nsects -= 1; | | |
| 5402 | } else { | | |
| 5403 | maybe_index.* = @intCast(u16, seg.sections.items.len); | | |
| 5404 | seg.sections.appendAssumeCapacity(sect.*); | | |
| 5405 | } | | |
| 5406 | try mapping.putNoClobber(old_idx, maybe_index.*); | | |
| 5407 | } | | |
| 5408 | | | |
| 5409 | var atoms = std.ArrayList(struct { match: MatchingSection, atom: *Atom }).init(self.base.allocator); | | |
| 5410 | defer atoms.deinit(); | | |
| 5411 | try atoms.ensureTotalCapacity(mapping.count()); | | |
| 5412 | | | |
| 5413 | for (mapping.keys()) |old_sect| { | | |
| 5414 | const new_sect = mapping.get(old_sect).? orelse { | | |
| 5415 | _ = self.atoms.remove(.{ .seg = seg_id, .sect = old_sect }); | | |
| 5416 | continue; | | |
| 5417 | }; | | |
| 5418 | const kv = self.atoms.fetchRemove(.{ .seg = seg_id, .sect = old_sect }).?; | | |
| 5419 | atoms.appendAssumeCapacity(.{ | | |
| 5420 | .match = .{ .seg = seg_id, .sect = new_sect }, | | |
| 5421 | .atom = kv.value, | | |
| 5422 | }); | | |
| 5423 | } | | |
| 5424 | | 5186 | |
| 5425 | while (atoms.popOrNull()) |next| { | 5187 | var sections = self.sections.toOwnedSlice(); |
| 5426 | try self.atoms.putNoClobber(self.base.allocator, next.match, next.atom); | 5188 | defer sections.deinit(gpa); |
| 5427 | } | 5189 | try self.sections.ensureTotalCapacity(gpa, sections.len); |
| 5428 | | 5190 | |
| 5429 | if (seg.inner.nsects == 0 and !mem.eql(u8, "__TEXT", seg.inner.segName())) { | 5191 | for (&[_]*?u8{ |
| 5430 | // Segment has now become empty, so mark it as such | 5192 | // __TEXT |
| 5431 | log.debug("marking segment {s} as dead", .{seg.inner.segName()}); | | |
| 5432 | seg.inner.cmd = @intToEnum(macho.LC, 0); | | |
| 5433 | maybe_seg_id.* = null; | | |
| 5434 | } | | |
| 5435 | } | | |
| 5436 | | | |
| 5437 | fn pruneAndSortSections(self: *MachO) !void { | | |
| 5438 | try self.pruneAndSortSectionsInSegment(&self.text_segment_cmd_index, &.{ | | |
| 5439 | &self.text_section_index, | 5193 | &self.text_section_index, |
| 5440 | &self.stubs_section_index, | 5194 | &self.stubs_section_index, |
| 5441 | &self.stub_helper_section_index, | 5195 | &self.stub_helper_section_index, |
| ... | @@ -5448,9 +5202,7 @@ fn pruneAndSortSections(self: *MachO) !void { | ... | @@ -5448,9 +5202,7 @@ fn pruneAndSortSections(self: *MachO) !void { |
| 5448 | &self.objc_methtype_section_index, | 5202 | &self.objc_methtype_section_index, |
| 5449 | &self.objc_classname_section_index, | 5203 | &self.objc_classname_section_index, |
| 5450 | &self.eh_frame_section_index, | 5204 | &self.eh_frame_section_index, |
| 5451 | }); | 5205 | // __DATA_CONST |
| 5452 | | | |
| 5453 | try self.pruneAndSortSectionsInSegment(&self.data_const_segment_cmd_index, &.{ | | |
| 5454 | &self.got_section_index, | 5206 | &self.got_section_index, |
| 5455 | &self.mod_init_func_section_index, | 5207 | &self.mod_init_func_section_index, |
| 5456 | &self.mod_term_func_section_index, | 5208 | &self.mod_term_func_section_index, |
| ... | @@ -5458,9 +5210,7 @@ fn pruneAndSortSections(self: *MachO) !void { | ... | @@ -5458,9 +5210,7 @@ fn pruneAndSortSections(self: *MachO) !void { |
| 5458 | &self.objc_cfstring_section_index, | 5210 | &self.objc_cfstring_section_index, |
| 5459 | &self.objc_classlist_section_index, | 5211 | &self.objc_classlist_section_index, |
| 5460 | &self.objc_imageinfo_section_index, | 5212 | &self.objc_imageinfo_section_index, |
| 5461 | }); | 5213 | // __DATA |
| 5462 | | | |
| 5463 | try self.pruneAndSortSectionsInSegment(&self.data_segment_cmd_index, &.{ | | |
| 5464 | &self.rustc_section_index, | 5214 | &self.rustc_section_index, |
| 5465 | &self.la_symbol_ptr_section_index, | 5215 | &self.la_symbol_ptr_section_index, |
| 5466 | &self.objc_const_section_index, | 5216 | &self.objc_const_section_index, |
| ... | @@ -5473,103 +5223,129 @@ fn pruneAndSortSections(self: *MachO) !void { | ... | @@ -5473,103 +5223,129 @@ fn pruneAndSortSections(self: *MachO) !void { |
| 5473 | &self.tlv_data_section_index, | 5223 | &self.tlv_data_section_index, |
| 5474 | &self.tlv_bss_section_index, | 5224 | &self.tlv_bss_section_index, |
| 5475 | &self.bss_section_index, | 5225 | &self.bss_section_index, |
| 5476 | }); | 5226 | }) |maybe_index| { |
| 5477 | | 5227 | const old_idx = maybe_index.* orelse continue; |
| 5478 | // Create new section ordinals. | 5228 | const segment_index = sections.items(.segment_index)[old_idx]; |
| 5479 | self.section_ordinals.clearRetainingCapacity(); | 5229 | const header = sections.items(.header)[old_idx]; |
| 5480 | if (self.text_segment_cmd_index) |seg_id| { | 5230 | const last_atom = sections.items(.last_atom)[old_idx]; |
| 5481 | const seg = self.load_commands.items[seg_id].segment; | 5231 | if (header.size == 0) { |
| 5482 | for (seg.sections.items) |_, sect_id| { | 5232 | log.debug("pruning section {s},{s}", .{ header.segName(), header.sectName() }); |
| 5483 | const res = self.section_ordinals.getOrPutAssumeCapacity(.{ | 5233 | maybe_index.* = null; |
| 5484 | .seg = seg_id, | 5234 | const seg = &self.segments.items[segment_index]; |
| 5485 | .sect = @intCast(u16, sect_id), | 5235 | seg.cmdsize -= @sizeOf(macho.section_64); |
| 5486 | }); | 5236 | seg.nsects -= 1; |
| 5487 | assert(!res.found_existing); | 5237 | } else { |
| 5488 | } | 5238 | maybe_index.* = @intCast(u8, self.sections.slice().len); |
| 5489 | } | 5239 | self.sections.appendAssumeCapacity(.{ |
| 5490 | if (self.data_const_segment_cmd_index) |seg_id| { | 5240 | .segment_index = segment_index, |
| 5491 | const seg = self.load_commands.items[seg_id].segment; | 5241 | .header = header, |
| 5492 | for (seg.sections.items) |_, sect_id| { | 5242 | .last_atom = last_atom, |
| 5493 | const res = self.section_ordinals.getOrPutAssumeCapacity(.{ | | |
| 5494 | .seg = seg_id, | | |
| 5495 | .sect = @intCast(u16, sect_id), | | |
| 5496 | }); | 5243 | }); |
| 5497 | assert(!res.found_existing); | | |
| 5498 | } | 5244 | } |
| 5499 | } | 5245 | } |
| 5500 | if (self.data_segment_cmd_index) |seg_id| { | 5246 | |
| 5501 | const seg = self.load_commands.items[seg_id].segment; | 5247 | for (self.segments.items) |*seg| { |
| 5502 | for (seg.sections.items) |_, sect_id| { | 5248 | const segname = seg.segName(); |
| 5503 | const res = self.section_ordinals.getOrPutAssumeCapacity(.{ | 5249 | if (seg.nsects == 0 and |
| 5504 | .seg = seg_id, | 5250 | !mem.eql(u8, "__TEXT", segname) and |
| 5505 | .sect = @intCast(u16, sect_id), | 5251 | !mem.eql(u8, "__PAGEZERO", segname) and |
| 5506 | }); | 5252 | !mem.eql(u8, "__LINKEDIT", segname)) |
| 5507 | assert(!res.found_existing); | 5253 | { |
| | 5254 | // Segment has now become empty, so mark it as such |
| | 5255 | log.debug("marking segment {s} as dead", .{seg.segName()}); |
| | 5256 | seg.cmd = @intToEnum(macho.LC, 0); |
| 5508 | } | 5257 | } |
| 5509 | } | 5258 | } |
| 5510 | self.sections_order_dirty = false; | | |
| 5511 | } | 5259 | } |
| 5512 | | 5260 | |
| 5513 | fn updateSectionOrdinals(self: *MachO) !void { | 5261 | fn updateSectionOrdinals(self: *MachO) !void { |
| 5514 | if (!self.sections_order_dirty) return; | 5262 | _ = self; |
| 5515 | | | |
| 5516 | const tracy = trace(@src()); | 5263 | const tracy = trace(@src()); |
| 5517 | defer tracy.end(); | 5264 | defer tracy.end(); |
| 5518 | | 5265 | |
| 5519 | log.debug("updating section ordinals", .{}); | 5266 | @panic("updating section ordinals"); |
| 5520 | | 5267 | |
| 5521 | const gpa = self.base.allocator; | 5268 | // const gpa = self.base.allocator; |
| | 5269 | |
| | 5270 | // var ordinal_remap = std.AutoHashMap(u8, u8).init(gpa); |
| | 5271 | // defer ordinal_remap.deinit(); |
| | 5272 | // var ordinals: std.AutoArrayHashMapUnmanaged(MatchingSection, void) = .{}; |
| | 5273 | |
| | 5274 | // var new_ordinal: u8 = 0; |
| | 5275 | // for (&[_]?u16{ |
| | 5276 | // self.text_segment_cmd_index, |
| | 5277 | // self.data_const_segment_cmd_index, |
| | 5278 | // self.data_segment_cmd_index, |
| | 5279 | // }) |maybe_index| { |
| | 5280 | // const index = maybe_index orelse continue; |
| | 5281 | // const seg = self.load_commands.items[index].segment; |
| | 5282 | // for (seg.sections.items) |sect, sect_id| { |
| | 5283 | // const match = MatchingSection{ |
| | 5284 | // .seg = @intCast(u16, index), |
| | 5285 | // .sect = @intCast(u16, sect_id), |
| | 5286 | // }; |
| | 5287 | // const old_ordinal = self.getSectionOrdinal(match); |
| | 5288 | // new_ordinal += 1; |
| | 5289 | // log.debug("'{s},{s}': sect({d}, '_,_') => sect({d}, '_,_')", .{ |
| | 5290 | // sect.segName(), |
| | 5291 | // sect.sectName(), |
| | 5292 | // old_ordinal, |
| | 5293 | // new_ordinal, |
| | 5294 | // }); |
| | 5295 | // try ordinal_remap.putNoClobber(old_ordinal, new_ordinal); |
| | 5296 | // try ordinals.putNoClobber(gpa, match, {}); |
| | 5297 | // } |
| | 5298 | // } |
| | 5299 | |
| | 5300 | // // FIXME Jakub |
| | 5301 | // // TODO no need for duping work here; simply walk the atom graph |
| | 5302 | // for (self.locals.items) |*sym| { |
| | 5303 | // if (sym.undf()) continue; |
| | 5304 | // if (sym.n_sect == 0) continue; |
| | 5305 | // sym.n_sect = ordinal_remap.get(sym.n_sect).?; |
| | 5306 | // } |
| | 5307 | // for (self.objects.items) |*object| { |
| | 5308 | // for (object.symtab.items) |*sym| { |
| | 5309 | // if (sym.undf()) continue; |
| | 5310 | // if (sym.n_sect == 0) continue; |
| | 5311 | // sym.n_sect = ordinal_remap.get(sym.n_sect).?; |
| | 5312 | // } |
| | 5313 | // } |
| | 5314 | |
| | 5315 | // self.section_ordinals.deinit(gpa); |
| | 5316 | // self.section_ordinals = ordinals; |
| | 5317 | } |
| 5522 | | 5318 | |
| 5523 | var ordinal_remap = std.AutoHashMap(u8, u8).init(gpa); | 5319 | pub fn writeSegmentHeaders(self: *MachO, start: usize, end: usize, ncmds: *u32, writer: anytype) !void { |
| 5524 | defer ordinal_remap.deinit(); | 5320 | var count: usize = 0; |
| 5525 | var ordinals: std.AutoArrayHashMapUnmanaged(MatchingSection, void) = .{}; | 5321 | for (self.segments.items[start..end]) |seg| { |
| | 5322 | if (seg.cmd == .NONE) continue; |
| | 5323 | try writer.writeStruct(seg); |
| 5526 | | 5324 | |
| 5527 | var new_ordinal: u8 = 0; | 5325 | // TODO |
| 5528 | for (&[_]?u16{ | 5326 | for (self.sections.items(.header)[count..][0..seg.nsects]) |header| { |
| 5529 | self.text_segment_cmd_index, | 5327 | try writer.writeStruct(header); |
| 5530 | self.data_const_segment_cmd_index, | | |
| 5531 | self.data_segment_cmd_index, | | |
| 5532 | }) |maybe_index| { | | |
| 5533 | const index = maybe_index orelse continue; | | |
| 5534 | const seg = self.load_commands.items[index].segment; | | |
| 5535 | for (seg.sections.items) |sect, sect_id| { | | |
| 5536 | const match = MatchingSection{ | | |
| 5537 | .seg = @intCast(u16, index), | | |
| 5538 | .sect = @intCast(u16, sect_id), | | |
| 5539 | }; | | |
| 5540 | const old_ordinal = self.getSectionOrdinal(match); | | |
| 5541 | new_ordinal += 1; | | |
| 5542 | log.debug("'{s},{s}': sect({d}, '_,_') => sect({d}, '_,_')", .{ | | |
| 5543 | sect.segName(), | | |
| 5544 | sect.sectName(), | | |
| 5545 | old_ordinal, | | |
| 5546 | new_ordinal, | | |
| 5547 | }); | | |
| 5548 | try ordinal_remap.putNoClobber(old_ordinal, new_ordinal); | | |
| 5549 | try ordinals.putNoClobber(gpa, match, {}); | | |
| 5550 | } | 5328 | } |
| 5551 | } | | |
| 5552 | | 5329 | |
| 5553 | // FIXME Jakub | 5330 | count += seg.nsects; |
| 5554 | // TODO no need for duping work here; simply walk the atom graph | 5331 | ncmds.* += 1; |
| 5555 | for (self.locals.items) |*sym| { | | |
| 5556 | if (sym.undf()) continue; | | |
| 5557 | if (sym.n_sect == 0) continue; | | |
| 5558 | sym.n_sect = ordinal_remap.get(sym.n_sect).?; | | |
| 5559 | } | | |
| 5560 | for (self.objects.items) |*object| { | | |
| 5561 | for (object.symtab.items) |*sym| { | | |
| 5562 | if (sym.undf()) continue; | | |
| 5563 | if (sym.n_sect == 0) continue; | | |
| 5564 | sym.n_sect = ordinal_remap.get(sym.n_sect).?; | | |
| 5565 | } | | |
| 5566 | } | 5332 | } |
| | 5333 | } |
| | 5334 | |
| | 5335 | fn writeLinkeditSegmentData(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| | 5336 | const seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| | 5337 | seg.filesize = 0; |
| | 5338 | seg.vmsize = 0; |
| 5567 | | 5339 | |
| 5568 | self.section_ordinals.deinit(gpa); | 5340 | try self.writeDyldInfoData(ncmds, lc_writer); |
| 5569 | self.section_ordinals = ordinals; | 5341 | try self.writeFunctionStarts(ncmds, lc_writer); |
| | 5342 | try self.writeDataInCode(ncmds, lc_writer); |
| | 5343 | try self.writeSymtabs(ncmds, lc_writer); |
| | 5344 | |
| | 5345 | seg.vmsize = mem.alignForwardGeneric(u64, seg.filesize, self.page_size); |
| 5570 | } | 5346 | } |
| 5571 | | 5347 | |
| 5572 | fn writeDyldInfoData(self: *MachO) !void { | 5348 | fn writeDyldInfoData(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 5573 | const tracy = trace(@src()); | 5349 | const tracy = trace(@src()); |
| 5574 | defer tracy.end(); | 5350 | defer tracy.end(); |
| 5575 | | 5351 | |
| ... | @@ -5582,89 +5358,86 @@ fn writeDyldInfoData(self: *MachO) !void { | ... | @@ -5582,89 +5358,86 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5582 | var lazy_bind_pointers = std.ArrayList(bind.Pointer).init(gpa); | 5358 | var lazy_bind_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 5583 | defer lazy_bind_pointers.deinit(); | 5359 | defer lazy_bind_pointers.deinit(); |
| 5584 | | 5360 | |
| 5585 | { | 5361 | const slice = self.sections.slice(); |
| 5586 | var it = self.atoms.iterator(); | 5362 | for (slice.items(.last_atom)) |last_atom, sect_id| { |
| 5587 | while (it.next()) |entry| { | 5363 | var atom = last_atom orelse continue; |
| 5588 | const match = entry.key_ptr.*; | 5364 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 5589 | var atom: *Atom = entry.value_ptr.*; | 5365 | const header = slice.items(.header)[sect_id]; |
| 5590 | | 5366 | |
| 5591 | if (self.text_segment_cmd_index) |seg| { | 5367 | if (mem.eql(u8, header.segName(), "__TEXT")) continue; // __TEXT is non-writable |
| 5592 | if (match.seg == seg) continue; // __TEXT is non-writable | | |
| 5593 | } | | |
| 5594 | | 5368 | |
| 5595 | const seg = self.getSegment(match); | 5369 | log.debug("dyld info for {s},{s}", .{ header.segName(), header.sectName() }); |
| 5596 | const sect = self.getSection(match); | | |
| 5597 | log.debug("dyld info for {s},{s}", .{ sect.segName(), sect.sectName() }); | | |
| 5598 | | 5370 | |
| 5599 | while (true) { | 5371 | const seg = self.segments.items[segment_index]; |
| 5600 | log.debug(" ATOM(%{d}, '{s}')", .{ atom.sym_index, atom.getName(self) }); | | |
| 5601 | const sym = atom.getSymbol(self); | | |
| 5602 | const base_offset = sym.n_value - seg.inner.vmaddr; | | |
| 5603 | | 5372 | |
| 5604 | for (atom.rebases.items) |offset| { | 5373 | while (true) { |
| 5605 | log.debug(" | rebase at {x}", .{base_offset + offset}); | 5374 | log.debug(" ATOM(%{d}, '{s}')", .{ atom.sym_index, atom.getName(self) }); |
| 5606 | try rebase_pointers.append(.{ | 5375 | const sym = atom.getSymbol(self); |
| 5607 | .offset = base_offset + offset, | 5376 | const base_offset = sym.n_value - seg.vmaddr; |
| 5608 | .segment_id = match.seg, | | |
| 5609 | }); | | |
| 5610 | } | | |
| 5611 | | 5377 | |
| 5612 | for (atom.bindings.items) |binding| { | 5378 | for (atom.rebases.items) |offset| { |
| 5613 | const bind_sym = self.getSymbol(binding.target); | 5379 | log.debug(" | rebase at {x}", .{base_offset + offset}); |
| 5614 | const bind_sym_name = self.getSymbolName(binding.target); | 5380 | try rebase_pointers.append(.{ |
| 5615 | const dylib_ordinal = @divTrunc( | 5381 | .offset = base_offset + offset, |
| 5616 | @bitCast(i16, bind_sym.n_desc), | 5382 | .segment_id = segment_index, |
| 5617 | macho.N_SYMBOL_RESOLVER, | 5383 | }); |
| 5618 | ); | 5384 | } |
| 5619 | var flags: u4 = 0; | | |
| 5620 | log.debug(" | bind at {x}, import('{s}') in dylib({d})", .{ | | |
| 5621 | binding.offset + base_offset, | | |
| 5622 | bind_sym_name, | | |
| 5623 | dylib_ordinal, | | |
| 5624 | }); | | |
| 5625 | if (bind_sym.weakRef()) { | | |
| 5626 | log.debug(" | marking as weak ref ", .{}); | | |
| 5627 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); | | |
| 5628 | } | | |
| 5629 | try bind_pointers.append(.{ | | |
| 5630 | .offset = binding.offset + base_offset, | | |
| 5631 | .segment_id = match.seg, | | |
| 5632 | .dylib_ordinal = dylib_ordinal, | | |
| 5633 | .name = bind_sym_name, | | |
| 5634 | .bind_flags = flags, | | |
| 5635 | }); | | |
| 5636 | } | | |
| 5637 | | 5385 | |
| 5638 | for (atom.lazy_bindings.items) |binding| { | 5386 | for (atom.bindings.items) |binding| { |
| 5639 | const bind_sym = self.getSymbol(binding.target); | 5387 | const bind_sym = self.getSymbol(binding.target); |
| 5640 | const bind_sym_name = self.getSymbolName(binding.target); | 5388 | const bind_sym_name = self.getSymbolName(binding.target); |
| 5641 | const dylib_ordinal = @divTrunc( | 5389 | const dylib_ordinal = @divTrunc( |
| 5642 | @bitCast(i16, bind_sym.n_desc), | 5390 | @bitCast(i16, bind_sym.n_desc), |
| 5643 | macho.N_SYMBOL_RESOLVER, | 5391 | macho.N_SYMBOL_RESOLVER, |
| 5644 | ); | 5392 | ); |
| 5645 | var flags: u4 = 0; | 5393 | var flags: u4 = 0; |
| 5646 | log.debug(" | lazy bind at {x} import('{s}') ord({d})", .{ | 5394 | log.debug(" | bind at {x}, import('{s}') in dylib({d})", .{ |
| 5647 | binding.offset + base_offset, | 5395 | binding.offset + base_offset, |
| 5648 | bind_sym_name, | 5396 | bind_sym_name, |
| 5649 | dylib_ordinal, | 5397 | dylib_ordinal, |
| 5650 | }); | 5398 | }); |
| 5651 | if (bind_sym.weakRef()) { | 5399 | if (bind_sym.weakRef()) { |
| 5652 | log.debug(" | marking as weak ref ", .{}); | 5400 | log.debug(" | marking as weak ref ", .{}); |
| 5653 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); | 5401 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 5654 | } | | |
| 5655 | try lazy_bind_pointers.append(.{ | | |
| 5656 | .offset = binding.offset + base_offset, | | |
| 5657 | .segment_id = match.seg, | | |
| 5658 | .dylib_ordinal = dylib_ordinal, | | |
| 5659 | .name = bind_sym_name, | | |
| 5660 | .bind_flags = flags, | | |
| 5661 | }); | | |
| 5662 | } | 5402 | } |
| | 5403 | try bind_pointers.append(.{ |
| | 5404 | .offset = binding.offset + base_offset, |
| | 5405 | .segment_id = segment_index, |
| | 5406 | .dylib_ordinal = dylib_ordinal, |
| | 5407 | .name = bind_sym_name, |
| | 5408 | .bind_flags = flags, |
| | 5409 | }); |
| | 5410 | } |
| 5663 | | 5411 | |
| 5664 | if (atom.prev) |prev| { | 5412 | for (atom.lazy_bindings.items) |binding| { |
| 5665 | atom = prev; | 5413 | const bind_sym = self.getSymbol(binding.target); |
| 5666 | } else break; | 5414 | const bind_sym_name = self.getSymbolName(binding.target); |
| | 5415 | const dylib_ordinal = @divTrunc( |
| | 5416 | @bitCast(i16, bind_sym.n_desc), |
| | 5417 | macho.N_SYMBOL_RESOLVER, |
| | 5418 | ); |
| | 5419 | var flags: u4 = 0; |
| | 5420 | log.debug(" | lazy bind at {x} import('{s}') ord({d})", .{ |
| | 5421 | binding.offset + base_offset, |
| | 5422 | bind_sym_name, |
| | 5423 | dylib_ordinal, |
| | 5424 | }); |
| | 5425 | if (bind_sym.weakRef()) { |
| | 5426 | log.debug(" | marking as weak ref ", .{}); |
| | 5427 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| | 5428 | } |
| | 5429 | try lazy_bind_pointers.append(.{ |
| | 5430 | .offset = binding.offset + base_offset, |
| | 5431 | .segment_id = segment_index, |
| | 5432 | .dylib_ordinal = dylib_ordinal, |
| | 5433 | .name = bind_sym_name, |
| | 5434 | .bind_flags = flags, |
| | 5435 | }); |
| 5667 | } | 5436 | } |
| | 5437 | |
| | 5438 | if (atom.prev) |prev| { |
| | 5439 | atom = prev; |
| | 5440 | } else break; |
| 5668 | } | 5441 | } |
| 5669 | } | 5442 | } |
| 5670 | | 5443 | |
| ... | @@ -5675,8 +5448,8 @@ fn writeDyldInfoData(self: *MachO) !void { | ... | @@ -5675,8 +5448,8 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5675 | // TODO handle macho.EXPORT_SYMBOL_FLAGS_REEXPORT and macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER. | 5448 | // TODO handle macho.EXPORT_SYMBOL_FLAGS_REEXPORT and macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER. |
| 5676 | log.debug("generating export trie", .{}); | 5449 | log.debug("generating export trie", .{}); |
| 5677 | | 5450 | |
| 5678 | const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].segment; | 5451 | const text_segment = self.segments.items[self.text_segment_cmd_index.?]; |
| 5679 | const base_address = text_segment.inner.vmaddr; | 5452 | const base_address = text_segment.vmaddr; |
| 5680 | | 5453 | |
| 5681 | if (self.base.options.output_mode == .Exe) { | 5454 | if (self.base.options.output_mode == .Exe) { |
| 5682 | for (&[_]SymbolWithLoc{ | 5455 | for (&[_]SymbolWithLoc{ |
| ... | @@ -5714,48 +5487,27 @@ fn writeDyldInfoData(self: *MachO) !void { | ... | @@ -5714,48 +5487,27 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5714 | try trie.finalize(gpa); | 5487 | try trie.finalize(gpa); |
| 5715 | } | 5488 | } |
| 5716 | | 5489 | |
| 5717 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; | 5490 | const link_seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| 5718 | const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].dyld_info_only; | 5491 | const rebase_off = mem.alignForwardGeneric(u64, link_seg.fileoff, @alignOf(u64)); |
| 5719 | | 5492 | assert(rebase_off == link_seg.fileoff); |
| 5720 | const rebase_off = mem.alignForwardGeneric(u64, seg.inner.fileoff, @alignOf(u64)); | | |
| 5721 | const rebase_size = try bind.rebaseInfoSize(rebase_pointers.items); | 5493 | const rebase_size = try bind.rebaseInfoSize(rebase_pointers.items); |
| 5722 | dyld_info.rebase_off = @intCast(u32, rebase_off); | 5494 | log.debug("writing rebase info from 0x{x} to 0x{x}", .{ rebase_off, rebase_off + rebase_size }); |
| 5723 | dyld_info.rebase_size = @intCast(u32, rebase_size); | | |
| 5724 | log.debug("writing rebase info from 0x{x} to 0x{x}", .{ | | |
| 5725 | dyld_info.rebase_off, | | |
| 5726 | dyld_info.rebase_off + dyld_info.rebase_size, | | |
| 5727 | }); | | |
| 5728 | | 5495 | |
| 5729 | const bind_off = mem.alignForwardGeneric(u64, dyld_info.rebase_off + dyld_info.rebase_size, @alignOf(u64)); | 5496 | const bind_off = mem.alignForwardGeneric(u64, rebase_off + rebase_size, @alignOf(u64)); |
| 5730 | const bind_size = try bind.bindInfoSize(bind_pointers.items); | 5497 | const bind_size = try bind.bindInfoSize(bind_pointers.items); |
| 5731 | dyld_info.bind_off = @intCast(u32, bind_off); | 5498 | log.debug("writing bind info from 0x{x} to 0x{x}", .{ bind_off, bind_off + bind_size }); |
| 5732 | dyld_info.bind_size = @intCast(u32, bind_size); | | |
| 5733 | log.debug("writing bind info from 0x{x} to 0x{x}", .{ | | |
| 5734 | dyld_info.bind_off, | | |
| 5735 | dyld_info.bind_off + dyld_info.bind_size, | | |
| 5736 | }); | | |
| 5737 | | 5499 | |
| 5738 | const lazy_bind_off = mem.alignForwardGeneric(u64, dyld_info.bind_off + dyld_info.bind_size, @alignOf(u64)); | 5500 | const lazy_bind_off = mem.alignForwardGeneric(u64, bind_off + bind_size, @alignOf(u64)); |
| 5739 | const lazy_bind_size = try bind.lazyBindInfoSize(lazy_bind_pointers.items); | 5501 | const lazy_bind_size = try bind.lazyBindInfoSize(lazy_bind_pointers.items); |
| 5740 | dyld_info.lazy_bind_off = @intCast(u32, lazy_bind_off); | 5502 | log.debug("writing lazy bind info from 0x{x} to 0x{x}", .{ lazy_bind_off, lazy_bind_off + lazy_bind_size }); |
| 5741 | dyld_info.lazy_bind_size = @intCast(u32, lazy_bind_size); | | |
| 5742 | log.debug("writing lazy bind info from 0x{x} to 0x{x}", .{ | | |
| 5743 | dyld_info.lazy_bind_off, | | |
| 5744 | dyld_info.lazy_bind_off + dyld_info.lazy_bind_size, | | |
| 5745 | }); | | |
| 5746 | | 5503 | |
| 5747 | const export_off = mem.alignForwardGeneric(u64, dyld_info.lazy_bind_off + dyld_info.lazy_bind_size, @alignOf(u64)); | 5504 | const export_off = mem.alignForwardGeneric(u64, lazy_bind_off + lazy_bind_size, @alignOf(u64)); |
| 5748 | const export_size = trie.size; | 5505 | const export_size = trie.size; |
| 5749 | dyld_info.export_off = @intCast(u32, export_off); | 5506 | log.debug("writing export trie from 0x{x} to 0x{x}", .{ export_off, export_off + export_size }); |
| 5750 | dyld_info.export_size = @intCast(u32, export_size); | | |
| 5751 | log.debug("writing export trie from 0x{x} to 0x{x}", .{ | | |
| 5752 | dyld_info.export_off, | | |
| 5753 | dyld_info.export_off + dyld_info.export_size, | | |
| 5754 | }); | | |
| 5755 | | 5507 | |
| 5756 | seg.inner.filesize = dyld_info.export_off + dyld_info.export_size - seg.inner.fileoff; | 5508 | const needed_size = export_off + export_size - rebase_off; |
| | 5509 | link_seg.filesize = needed_size; |
| 5757 | | 5510 | |
| 5758 | const needed_size = dyld_info.export_off + dyld_info.export_size - dyld_info.rebase_off; | | |
| 5759 | var buffer = try gpa.alloc(u8, needed_size); | 5511 | var buffer = try gpa.alloc(u8, needed_size); |
| 5760 | defer gpa.free(buffer); | 5512 | defer gpa.free(buffer); |
| 5761 | mem.set(u8, buffer, 0); | 5513 | mem.set(u8, buffer, 0); |
| ... | @@ -5763,54 +5515,61 @@ fn writeDyldInfoData(self: *MachO) !void { | ... | @@ -5763,54 +5515,61 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5763 | var stream = std.io.fixedBufferStream(buffer); | 5515 | var stream = std.io.fixedBufferStream(buffer); |
| 5764 | const writer = stream.writer(); | 5516 | const writer = stream.writer(); |
| 5765 | | 5517 | |
| 5766 | const base_off = dyld_info.rebase_off; | | |
| 5767 | try bind.writeRebaseInfo(rebase_pointers.items, writer); | 5518 | try bind.writeRebaseInfo(rebase_pointers.items, writer); |
| 5768 | try stream.seekTo(dyld_info.bind_off - base_off); | 5519 | try stream.seekTo(bind_off - rebase_off); |
| 5769 | | 5520 | |
| 5770 | try bind.writeBindInfo(bind_pointers.items, writer); | 5521 | try bind.writeBindInfo(bind_pointers.items, writer); |
| 5771 | try stream.seekTo(dyld_info.lazy_bind_off - base_off); | 5522 | try stream.seekTo(lazy_bind_off - rebase_off); |
| 5772 | | 5523 | |
| 5773 | try bind.writeLazyBindInfo(lazy_bind_pointers.items, writer); | 5524 | try bind.writeLazyBindInfo(lazy_bind_pointers.items, writer); |
| 5774 | try stream.seekTo(dyld_info.export_off - base_off); | 5525 | try stream.seekTo(export_off - rebase_off); |
| 5775 | | 5526 | |
| 5776 | _ = try trie.write(writer); | 5527 | _ = try trie.write(writer); |
| 5777 | | 5528 | |
| 5778 | log.debug("writing dyld info from 0x{x} to 0x{x}", .{ | 5529 | log.debug("writing dyld info from 0x{x} to 0x{x}", .{ |
| 5779 | dyld_info.rebase_off, | 5530 | rebase_off, |
| 5780 | dyld_info.rebase_off + needed_size, | 5531 | rebase_off + needed_size, |
| 5781 | }); | 5532 | }); |
| 5782 | | 5533 | |
| 5783 | try self.base.file.?.pwriteAll(buffer, dyld_info.rebase_off); | 5534 | try self.base.file.?.pwriteAll(buffer, rebase_off); |
| 5784 | try self.populateLazyBindOffsetsInStubHelper( | 5535 | try self.populateLazyBindOffsetsInStubHelper(buffer[lazy_bind_off - rebase_off ..][0..lazy_bind_size]); |
| 5785 | buffer[dyld_info.lazy_bind_off - base_off ..][0..dyld_info.lazy_bind_size], | 5536 | |
| 5786 | ); | 5537 | try lc_writer.writeStruct(macho.dyld_info_command{ |
| 5787 | | 5538 | .cmd = .DYLD_INFO_ONLY, |
| 5788 | self.load_commands_dirty = true; | 5539 | .cmdsize = @sizeOf(macho.dyld_info_command), |
| | 5540 | .rebase_off = @intCast(u32, rebase_off), |
| | 5541 | .rebase_size = @intCast(u32, rebase_size), |
| | 5542 | .bind_off = @intCast(u32, bind_off), |
| | 5543 | .bind_size = @intCast(u32, bind_size), |
| | 5544 | .weak_bind_off = 0, |
| | 5545 | .weak_bind_size = 0, |
| | 5546 | .lazy_bind_off = @intCast(u32, lazy_bind_off), |
| | 5547 | .lazy_bind_size = @intCast(u32, lazy_bind_size), |
| | 5548 | .export_off = @intCast(u32, export_off), |
| | 5549 | .export_size = @intCast(u32, export_size), |
| | 5550 | }); |
| | 5551 | ncmds.* += 1; |
| 5789 | } | 5552 | } |
| 5790 | | 5553 | |
| 5791 | fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { | 5554 | fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5792 | const gpa = self.base.allocator; | 5555 | const gpa = self.base.allocator; |
| 5793 | const text_segment_cmd_index = self.text_segment_cmd_index orelse return; | 5556 | |
| 5794 | const stub_helper_section_index = self.stub_helper_section_index orelse return; | 5557 | const stub_helper_section_index = self.stub_helper_section_index orelse return; |
| 5795 | const last_atom = self.atoms.get(.{ | | |
| 5796 | .seg = text_segment_cmd_index, | | |
| 5797 | .sect = stub_helper_section_index, | | |
| 5798 | }) orelse return; | | |
| 5799 | if (self.stub_helper_preamble_atom == null) return; | 5558 | if (self.stub_helper_preamble_atom == null) return; |
| 5800 | if (last_atom == self.stub_helper_preamble_atom.?) return; | 5559 | |
| | 5560 | const section = self.sections.get(stub_helper_section_index); |
| | 5561 | const last_atom = section.last_atom orelse return; |
| | 5562 | if (last_atom == self.stub_helper_preamble_atom.?) return; // TODO is this a redundant check? |
| 5801 | | 5563 | |
| 5802 | var table = std.AutoHashMap(i64, *Atom).init(gpa); | 5564 | var table = std.AutoHashMap(i64, *Atom).init(gpa); |
| 5803 | defer table.deinit(); | 5565 | defer table.deinit(); |
| 5804 | | 5566 | |
| 5805 | { | 5567 | { |
| 5806 | var stub_atom = last_atom; | 5568 | var stub_atom = last_atom; |
| 5807 | var laptr_atom = self.atoms.get(.{ | 5569 | var laptr_atom = self.sections.items(.last_atom)[self.la_symbol_ptr_section_index.?].?; |
| 5808 | .seg = self.data_segment_cmd_index.?, | | |
| 5809 | .sect = self.la_symbol_ptr_section_index.?, | | |
| 5810 | }).?; | | |
| 5811 | const base_addr = blk: { | 5570 | const base_addr = blk: { |
| 5812 | const seg = self.load_commands.items[self.data_segment_cmd_index.?].segment; | 5571 | const seg = self.segments.items[self.data_segment_cmd_index.?]; |
| 5813 | break :blk seg.inner.vmaddr; | 5572 | break :blk seg.vmaddr; |
| 5814 | }; | 5573 | }; |
| 5815 | | 5574 | |
| 5816 | while (true) { | 5575 | while (true) { |
| ... | @@ -5871,10 +5630,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { | ... | @@ -5871,10 +5630,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5871 | } | 5630 | } |
| 5872 | } | 5631 | } |
| 5873 | | 5632 | |
| 5874 | const sect = self.getSection(.{ | 5633 | const header = self.sections.items(.header)[stub_helper_section_index]; |
| 5875 | .seg = text_segment_cmd_index, | | |
| 5876 | .sect = stub_helper_section_index, | | |
| 5877 | }); | | |
| 5878 | const stub_offset: u4 = switch (self.base.options.target.cpu.arch) { | 5634 | const stub_offset: u4 = switch (self.base.options.target.cpu.arch) { |
| 5879 | .x86_64 => 1, | 5635 | .x86_64 => 1, |
| 5880 | .aarch64 => 2 * @sizeOf(u32), | 5636 | .aarch64 => 2 * @sizeOf(u32), |
| ... | @@ -5886,7 +5642,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { | ... | @@ -5886,7 +5642,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5886 | while (offsets.popOrNull()) |bind_offset| { | 5642 | while (offsets.popOrNull()) |bind_offset| { |
| 5887 | const atom = table.get(bind_offset.sym_offset).?; | 5643 | const atom = table.get(bind_offset.sym_offset).?; |
| 5888 | const sym = atom.getSymbol(self); | 5644 | const sym = atom.getSymbol(self); |
| 5889 | const file_offset = sect.offset + sym.n_value - sect.addr + stub_offset; | 5645 | const file_offset = header.offset + sym.n_value - header.addr + stub_offset; |
| 5890 | mem.writeIntLittle(u32, &buf, bind_offset.offset); | 5646 | mem.writeIntLittle(u32, &buf, bind_offset.offset); |
| 5891 | log.debug("writing lazy bind offset in stub helper of 0x{x} for symbol {s} at offset 0x{x}", .{ | 5647 | log.debug("writing lazy bind offset in stub helper of 0x{x} for symbol {s} at offset 0x{x}", .{ |
| 5892 | bind_offset.offset, | 5648 | bind_offset.offset, |
| ... | @@ -5899,14 +5655,14 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { | ... | @@ -5899,14 +5655,14 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5899 | | 5655 | |
| 5900 | const asc_u64 = std.sort.asc(u64); | 5656 | const asc_u64 = std.sort.asc(u64); |
| 5901 | | 5657 | |
| 5902 | fn writeFunctionStarts(self: *MachO) !void { | 5658 | fn writeFunctionStarts(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 5903 | const text_seg_index = self.text_segment_cmd_index orelse return; | | |
| 5904 | const text_sect_index = self.text_section_index orelse return; | | |
| 5905 | const text_seg = self.load_commands.items[text_seg_index].segment; | | |
| 5906 | | | |
| 5907 | const tracy = trace(@src()); | 5659 | const tracy = trace(@src()); |
| 5908 | defer tracy.end(); | 5660 | defer tracy.end(); |
| 5909 | | 5661 | |
| | 5662 | const text_seg_index = self.text_segment_cmd_index orelse return; |
| | 5663 | const text_sect_index = self.text_section_index orelse return; |
| | 5664 | const text_seg = self.segments.items[text_seg_index]; |
| | 5665 | |
| 5910 | const gpa = self.base.allocator; | 5666 | const gpa = self.base.allocator; |
| 5911 | | 5667 | |
| 5912 | // We need to sort by address first | 5668 | // We need to sort by address first |
| ... | @@ -5918,8 +5674,8 @@ fn writeFunctionStarts(self: *MachO) !void { | ... | @@ -5918,8 +5674,8 @@ fn writeFunctionStarts(self: *MachO) !void { |
| 5918 | const sym = self.getSymbol(global); | 5674 | const sym = self.getSymbol(global); |
| 5919 | if (sym.undf()) continue; | 5675 | if (sym.undf()) continue; |
| 5920 | if (sym.n_desc == N_DESC_GCED) continue; | 5676 | if (sym.n_desc == N_DESC_GCED) continue; |
| 5921 | const match = self.getMatchingSectionFromOrdinal(sym.n_sect); | 5677 | const sect_id = sym.n_sect - 1; |
| 5922 | if (match.seg != text_seg_index or match.sect != text_sect_index) continue; | 5678 | if (sect_id != text_sect_index) continue; |
| 5923 | | 5679 | |
| 5924 | addresses.appendAssumeCapacity(sym.n_value); | 5680 | addresses.appendAssumeCapacity(sym.n_value); |
| 5925 | } | 5681 | } |
| ... | @@ -5932,7 +5688,7 @@ fn writeFunctionStarts(self: *MachO) !void { | ... | @@ -5932,7 +5688,7 @@ fn writeFunctionStarts(self: *MachO) !void { |
| 5932 | | 5688 | |
| 5933 | var last_off: u32 = 0; | 5689 | var last_off: u32 = 0; |
| 5934 | for (addresses.items) |addr| { | 5690 | for (addresses.items) |addr| { |
| 5935 | const offset = @intCast(u32, addr - text_seg.inner.vmaddr); | 5691 | const offset = @intCast(u32, addr - text_seg.vmaddr); |
| 5936 | const diff = offset - last_off; | 5692 | const diff = offset - last_off; |
| 5937 | | 5693 | |
| 5938 | if (diff == 0) continue; | 5694 | if (diff == 0) continue; |
| ... | @@ -5951,22 +5707,22 @@ fn writeFunctionStarts(self: *MachO) !void { | ... | @@ -5951,22 +5707,22 @@ fn writeFunctionStarts(self: *MachO) !void { |
| 5951 | try std.leb.writeULEB128(buffer.writer(), offset); | 5707 | try std.leb.writeULEB128(buffer.writer(), offset); |
| 5952 | } | 5708 | } |
| 5953 | | 5709 | |
| 5954 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; | 5710 | const link_seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| 5955 | const fn_cmd = &self.load_commands.items[self.function_starts_cmd_index.?].linkedit_data; | 5711 | const offset = mem.alignForwardGeneric(u64, link_seg.fileoff + link_seg.filesize, @alignOf(u64)); |
| | 5712 | const needed_size = buffer.items.len; |
| | 5713 | link_seg.filesize = offset + needed_size - link_seg.fileoff; |
| 5956 | | 5714 | |
| 5957 | const dataoff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(u64)); | 5715 | log.debug("writing function starts info from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 5958 | const datasize = buffer.items.len; | | |
| 5959 | fn_cmd.dataoff = @intCast(u32, dataoff); | | |
| 5960 | fn_cmd.datasize = @intCast(u32, datasize); | | |
| 5961 | seg.inner.filesize = fn_cmd.dataoff + fn_cmd.datasize - seg.inner.fileoff; | | |
| 5962 | | 5716 | |
| 5963 | log.debug("writing function starts info from 0x{x} to 0x{x}", .{ | 5717 | try self.base.file.?.pwriteAll(buffer.items, offset); |
| 5964 | fn_cmd.dataoff, | | |
| 5965 | fn_cmd.dataoff + fn_cmd.datasize, | | |
| 5966 | }); | | |
| 5967 | | 5718 | |
| 5968 | try self.base.file.?.pwriteAll(buffer.items, fn_cmd.dataoff); | 5719 | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 5969 | self.load_commands_dirty = true; | 5720 | .cmd = .FUNCTION_STARTS, |
| | 5721 | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| | 5722 | .dataoff = @intCast(u32, offset), |
| | 5723 | .datasize = @intCast(u32, needed_size), |
| | 5724 | }); |
| | 5725 | ncmds.* += 1; |
| 5970 | } | 5726 | } |
| 5971 | | 5727 | |
| 5972 | fn filterDataInCode( | 5728 | fn filterDataInCode( |
| ... | @@ -5988,17 +5744,15 @@ fn filterDataInCode( | ... | @@ -5988,17 +5744,15 @@ fn filterDataInCode( |
| 5988 | return dices[start..end]; | 5744 | return dices[start..end]; |
| 5989 | } | 5745 | } |
| 5990 | | 5746 | |
| 5991 | fn writeDataInCode(self: *MachO) !void { | 5747 | fn writeDataInCode(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 5992 | const tracy = trace(@src()); | 5748 | const tracy = trace(@src()); |
| 5993 | defer tracy.end(); | 5749 | defer tracy.end(); |
| 5994 | | 5750 | |
| 5995 | var out_dice = std.ArrayList(macho.data_in_code_entry).init(self.base.allocator); | 5751 | var out_dice = std.ArrayList(macho.data_in_code_entry).init(self.base.allocator); |
| 5996 | defer out_dice.deinit(); | 5752 | defer out_dice.deinit(); |
| 5997 | | 5753 | |
| 5998 | const text_sect = self.getSection(.{ | 5754 | const text_sect_id = self.text_section_index orelse return; |
| 5999 | .seg = self.text_segment_cmd_index orelse return, | 5755 | const text_sect_header = self.sections.items(.header)[text_sect_id]; |
| 6000 | .sect = self.text_section_index orelse return, | | |
| 6001 | }); | | |
| 6002 | | 5756 | |
| 6003 | for (self.objects.items) |object| { | 5757 | for (self.objects.items) |object| { |
| 6004 | const dice = object.parseDataInCode() orelse continue; | 5758 | const dice = object.parseDataInCode() orelse continue; |
| ... | @@ -6008,15 +5762,15 @@ fn writeDataInCode(self: *MachO) !void { | ... | @@ -6008,15 +5762,15 @@ fn writeDataInCode(self: *MachO) !void { |
| 6008 | const sym = atom.getSymbol(self); | 5762 | const sym = atom.getSymbol(self); |
| 6009 | if (sym.n_desc == N_DESC_GCED) continue; | 5763 | if (sym.n_desc == N_DESC_GCED) continue; |
| 6010 | | 5764 | |
| 6011 | const match = self.getMatchingSectionFromOrdinal(sym.n_sect); | 5765 | const sect_id = sym.n_sect - 1; |
| 6012 | if (match.seg != self.text_segment_cmd_index.? and match.sect != self.text_section_index.?) { | 5766 | if (sect_id != self.text_section_index.?) { |
| 6013 | continue; | 5767 | continue; |
| 6014 | } | 5768 | } |
| 6015 | | 5769 | |
| 6016 | const source_sym = object.getSourceSymbol(atom.sym_index) orelse continue; | 5770 | const source_sym = object.getSourceSymbol(atom.sym_index) orelse continue; |
| 6017 | const source_addr = math.cast(u32, source_sym.n_value) orelse return error.Overflow; | 5771 | const source_addr = math.cast(u32, source_sym.n_value) orelse return error.Overflow; |
| 6018 | const filtered_dice = filterDataInCode(dice, source_addr, source_addr + atom.size); | 5772 | const filtered_dice = filterDataInCode(dice, source_addr, source_addr + atom.size); |
| 6019 | const base = math.cast(u32, sym.n_value - text_sect.addr + text_sect.offset) orelse | 5773 | const base = math.cast(u32, sym.n_value - text_sect_header.addr + text_sect_header.offset) orelse |
| 6020 | return error.Overflow; | 5774 | return error.Overflow; |
| 6021 | | 5775 | |
| 6022 | for (filtered_dice) |single| { | 5776 | for (filtered_dice) |single| { |
| ... | @@ -6030,33 +5784,63 @@ fn writeDataInCode(self: *MachO) !void { | ... | @@ -6030,33 +5784,63 @@ fn writeDataInCode(self: *MachO) !void { |
| 6030 | } | 5784 | } |
| 6031 | } | 5785 | } |
| 6032 | | 5786 | |
| 6033 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; | 5787 | const seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| 6034 | const dice_cmd = &self.load_commands.items[self.data_in_code_cmd_index.?].linkedit_data; | 5788 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| | 5789 | const needed_size = out_dice.items.len * @sizeOf(macho.data_in_code_entry); |
| | 5790 | seg.filesize = offset + needed_size - seg.fileoff; |
| 6035 | | 5791 | |
| 6036 | const dataoff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(u64)); | 5792 | log.debug("writing data-in-code from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 6037 | const datasize = out_dice.items.len * @sizeOf(macho.data_in_code_entry); | | |
| 6038 | dice_cmd.dataoff = @intCast(u32, dataoff); | | |
| 6039 | dice_cmd.datasize = @intCast(u32, datasize); | | |
| 6040 | seg.inner.filesize = dice_cmd.dataoff + dice_cmd.datasize - seg.inner.fileoff; | | |
| 6041 | | 5793 | |
| 6042 | log.debug("writing data-in-code from 0x{x} to 0x{x}", .{ | 5794 | try self.base.file.?.pwriteAll(mem.sliceAsBytes(out_dice.items), offset); |
| 6043 | dice_cmd.dataoff, | 5795 | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 6044 | dice_cmd.dataoff + dice_cmd.datasize, | 5796 | .cmd = .DATA_IN_CODE, |
| | 5797 | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| | 5798 | .dataoff = @intCast(u32, offset), |
| | 5799 | .datasize = @intCast(u32, needed_size), |
| 6045 | }); | 5800 | }); |
| 6046 | | 5801 | ncmds.* += 1; |
| 6047 | try self.base.file.?.pwriteAll(mem.sliceAsBytes(out_dice.items), dice_cmd.dataoff); | | |
| 6048 | self.load_commands_dirty = true; | | |
| 6049 | } | 5802 | } |
| 6050 | | 5803 | |
| 6051 | fn writeSymtab(self: *MachO) !void { | 5804 | fn writeSymtabs(self: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 6052 | const tracy = trace(@src()); | 5805 | var symtab_cmd = macho.symtab_command{ |
| 6053 | defer tracy.end(); | 5806 | .cmdsize = @sizeOf(macho.symtab_command), |
| | 5807 | .symoff = 0, |
| | 5808 | .nsyms = 0, |
| | 5809 | .stroff = 0, |
| | 5810 | .strsize = 0, |
| | 5811 | }; |
| | 5812 | var dysymtab_cmd = macho.dysymtab_command{ |
| | 5813 | .cmdsize = @sizeOf(macho.dysymtab_command), |
| | 5814 | .ilocalsym = 0, |
| | 5815 | .nlocalsym = 0, |
| | 5816 | .iextdefsym = 0, |
| | 5817 | .nextdefsym = 0, |
| | 5818 | .iundefsym = 0, |
| | 5819 | .nundefsym = 0, |
| | 5820 | .tocoff = 0, |
| | 5821 | .ntoc = 0, |
| | 5822 | .modtaboff = 0, |
| | 5823 | .nmodtab = 0, |
| | 5824 | .extrefsymoff = 0, |
| | 5825 | .nextrefsyms = 0, |
| | 5826 | .indirectsymoff = 0, |
| | 5827 | .nindirectsyms = 0, |
| | 5828 | .extreloff = 0, |
| | 5829 | .nextrel = 0, |
| | 5830 | .locreloff = 0, |
| | 5831 | .nlocrel = 0, |
| | 5832 | }; |
| | 5833 | var ctx = try self.writeSymtab(&symtab_cmd); |
| | 5834 | defer ctx.imports_table.deinit(); |
| | 5835 | try self.writeDysymtab(ctx, &dysymtab_cmd); |
| | 5836 | try self.writeStrtab(&symtab_cmd); |
| | 5837 | try lc_writer.writeStruct(symtab_cmd); |
| | 5838 | try lc_writer.writeStruct(dysymtab_cmd); |
| | 5839 | ncmds.* += 2; |
| | 5840 | } |
| 6054 | | 5841 | |
| | 5842 | fn writeSymtab(self: *MachO, lc: *macho.symtab_command) !SymtabCtx { |
| 6055 | const gpa = self.base.allocator; | 5843 | const gpa = self.base.allocator; |
| 6056 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; | | |
| 6057 | const symtab = &self.load_commands.items[self.symtab_cmd_index.?].symtab; | | |
| 6058 | const symoff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(macho.nlist_64)); | | |
| 6059 | symtab.symoff = @intCast(u32, symoff); | | |
| 6060 | | 5844 | |
| 6061 | var locals = std.ArrayList(macho.nlist_64).init(gpa); | 5845 | var locals = std.ArrayList(macho.nlist_64).init(gpa); |
| 6062 | defer locals.deinit(); | 5846 | defer locals.deinit(); |
| ... | @@ -6101,8 +5885,8 @@ fn writeSymtab(self: *MachO) !void { | ... | @@ -6101,8 +5885,8 @@ fn writeSymtab(self: *MachO) !void { |
| 6101 | | 5885 | |
| 6102 | var imports = std.ArrayList(macho.nlist_64).init(gpa); | 5886 | var imports = std.ArrayList(macho.nlist_64).init(gpa); |
| 6103 | defer imports.deinit(); | 5887 | defer imports.deinit(); |
| | 5888 | |
| 6104 | var imports_table = std.AutoHashMap(SymbolWithLoc, u32).init(gpa); | 5889 | var imports_table = std.AutoHashMap(SymbolWithLoc, u32).init(gpa); |
| 6105 | defer imports_table.deinit(); | | |
| 6106 | | 5890 | |
| 6107 | for (self.globals.values()) |global| { | 5891 | for (self.globals.values()) |global| { |
| 6108 | const sym = self.getSymbol(global); | 5892 | const sym = self.getSymbol(global); |
| ... | @@ -6115,56 +5899,84 @@ fn writeSymtab(self: *MachO) !void { | ... | @@ -6115,56 +5899,84 @@ fn writeSymtab(self: *MachO) !void { |
| 6115 | try imports_table.putNoClobber(global, new_index); | 5899 | try imports_table.putNoClobber(global, new_index); |
| 6116 | } | 5900 | } |
| 6117 | | 5901 | |
| 6118 | const nlocals = locals.items.len; | 5902 | const nlocals = @intCast(u32, locals.items.len); |
| 6119 | const nexports = exports.items.len; | 5903 | const nexports = @intCast(u32, exports.items.len); |
| 6120 | const nimports = imports.items.len; | 5904 | const nimports = @intCast(u32, imports.items.len); |
| 6121 | symtab.nsyms = @intCast(u32, nlocals + nexports + nimports); | 5905 | const nsyms = nlocals + nexports + nimports; |
| | 5906 | |
| | 5907 | const seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| | 5908 | const offset = mem.alignForwardGeneric( |
| | 5909 | u64, |
| | 5910 | seg.fileoff + seg.filesize, |
| | 5911 | @alignOf(macho.nlist_64), |
| | 5912 | ); |
| | 5913 | const needed_size = nsyms * @sizeOf(macho.nlist_64); |
| | 5914 | seg.filesize = offset + needed_size - seg.fileoff; |
| 6122 | | 5915 | |
| 6123 | var buffer = std.ArrayList(u8).init(gpa); | 5916 | var buffer = std.ArrayList(u8).init(gpa); |
| 6124 | defer buffer.deinit(); | 5917 | defer buffer.deinit(); |
| 6125 | try buffer.ensureTotalCapacityPrecise(symtab.nsyms * @sizeOf(macho.nlist_64)); | 5918 | try buffer.ensureTotalCapacityPrecise(needed_size); |
| 6126 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(locals.items)); | 5919 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(locals.items)); |
| 6127 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(exports.items)); | 5920 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(exports.items)); |
| 6128 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(imports.items)); | 5921 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(imports.items)); |
| 6129 | | 5922 | |
| 6130 | log.debug("writing symtab from 0x{x} to 0x{x}", .{ symtab.symoff, symtab.symoff + buffer.items.len }); | 5923 | log.debug("writing symtab from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 6131 | try self.base.file.?.pwriteAll(buffer.items, symtab.symoff); | 5924 | try self.base.file.?.pwriteAll(buffer.items, offset); |
| | 5925 | |
| | 5926 | lc.symoff = @intCast(u32, offset); |
| | 5927 | lc.nsyms = nsyms; |
| 6132 | | 5928 | |
| 6133 | seg.inner.filesize = symtab.symoff + buffer.items.len - seg.inner.fileoff; | 5929 | return SymtabCtx{ |
| | 5930 | .nlocalsym = nlocals, |
| | 5931 | .nextdefsym = nexports, |
| | 5932 | .nundefsym = nimports, |
| | 5933 | .imports_table = imports_table, |
| | 5934 | }; |
| | 5935 | } |
| 6134 | | 5936 | |
| 6135 | // Update dynamic symbol table. | 5937 | fn writeStrtab(self: *MachO, lc: *macho.symtab_command) !void { |
| 6136 | const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].dysymtab; | 5938 | const seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| 6137 | dysymtab.nlocalsym = @intCast(u32, nlocals); | 5939 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 6138 | dysymtab.iextdefsym = dysymtab.nlocalsym; | 5940 | const needed_size = self.strtab.buffer.items.len; |
| 6139 | dysymtab.nextdefsym = @intCast(u32, nexports); | 5941 | seg.filesize = offset + needed_size - seg.fileoff; |
| 6140 | dysymtab.iundefsym = dysymtab.nlocalsym + dysymtab.nextdefsym; | | |
| 6141 | dysymtab.nundefsym = @intCast(u32, nimports); | | |
| 6142 | | 5942 | |
| | 5943 | log.debug("writing string table from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| | 5944 | |
| | 5945 | try self.base.file.?.pwriteAll(self.strtab.buffer.items, offset); |
| | 5946 | |
| | 5947 | lc.stroff = @intCast(u32, offset); |
| | 5948 | lc.strsize = @intCast(u32, needed_size); |
| | 5949 | } |
| | 5950 | |
| | 5951 | const SymtabCtx = struct { |
| | 5952 | nlocalsym: u32, |
| | 5953 | nextdefsym: u32, |
| | 5954 | nundefsym: u32, |
| | 5955 | imports_table: std.AutoHashMap(SymbolWithLoc, u32), |
| | 5956 | }; |
| | 5957 | |
| | 5958 | fn writeDysymtab(self: *MachO, ctx: SymtabCtx, lc: *macho.dysymtab_command) !void { |
| | 5959 | const gpa = self.base.allocator; |
| 6143 | const nstubs = @intCast(u32, self.stubs_table.count()); | 5960 | const nstubs = @intCast(u32, self.stubs_table.count()); |
| 6144 | const ngot_entries = @intCast(u32, self.got_entries_table.count()); | 5961 | const ngot_entries = @intCast(u32, self.got_entries_table.count()); |
| | 5962 | const nindirectsyms = nstubs * 2 + ngot_entries; |
| | 5963 | const iextdefsym = ctx.nlocalsym; |
| | 5964 | const iundefsym = iextdefsym + ctx.nextdefsym; |
| 6145 | | 5965 | |
| 6146 | const indirectsymoff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(u64)); | 5966 | const seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| 6147 | dysymtab.indirectsymoff = @intCast(u32, indirectsymoff); | 5967 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 6148 | dysymtab.nindirectsyms = nstubs * 2 + ngot_entries; | 5968 | const needed_size = nindirectsyms * @sizeOf(u32); |
| | 5969 | seg.filesize = offset + needed_size - seg.fileoff; |
| 6149 | | 5970 | |
| 6150 | seg.inner.filesize = dysymtab.indirectsymoff + dysymtab.nindirectsyms * @sizeOf(u32) - seg.inner.fileoff; | 5971 | log.debug("writing indirect symbol table from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 6151 | | | |
| 6152 | log.debug("writing indirect symbol table from 0x{x} to 0x{x}", .{ | | |
| 6153 | dysymtab.indirectsymoff, | | |
| 6154 | dysymtab.indirectsymoff + dysymtab.nindirectsyms * @sizeOf(u32), | | |
| 6155 | }); | | |
| 6156 | | 5972 | |
| 6157 | var buf = std.ArrayList(u8).init(gpa); | 5973 | var buf = std.ArrayList(u8).init(gpa); |
| 6158 | defer buf.deinit(); | 5974 | defer buf.deinit(); |
| 6159 | try buf.ensureTotalCapacity(dysymtab.nindirectsyms * @sizeOf(u32)); | 5975 | try buf.ensureTotalCapacity(needed_size); |
| 6160 | const writer = buf.writer(); | 5976 | const writer = buf.writer(); |
| 6161 | | 5977 | |
| 6162 | if (self.text_segment_cmd_index) |text_segment_cmd_index| blk: { | 5978 | if (self.stubs_section_index) |sect_id| { |
| 6163 | const stubs_section_index = self.stubs_section_index orelse break :blk; | 5979 | const stubs = &self.sections.items(.header)[sect_id]; |
| 6164 | const stubs = self.getSectionPtr(.{ | | |
| 6165 | .seg = text_segment_cmd_index, | | |
| 6166 | .sect = stubs_section_index, | | |
| 6167 | }); | | |
| 6168 | stubs.reserved1 = 0; | 5980 | stubs.reserved1 = 0; |
| 6169 | for (self.stubs.items) |entry| { | 5981 | for (self.stubs.items) |entry| { |
| 6170 | if (entry.sym_index == 0) continue; | 5982 | if (entry.sym_index == 0) continue; |
| ... | @@ -6172,16 +5984,12 @@ fn writeSymtab(self: *MachO) !void { | ... | @@ -6172,16 +5984,12 @@ fn writeSymtab(self: *MachO) !void { |
| 6172 | if (atom_sym.n_desc == N_DESC_GCED) continue; | 5984 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 6173 | const target_sym = self.getSymbol(entry.target); | 5985 | const target_sym = self.getSymbol(entry.target); |
| 6174 | assert(target_sym.undf()); | 5986 | assert(target_sym.undf()); |
| 6175 | try writer.writeIntLittle(u32, dysymtab.iundefsym + imports_table.get(entry.target).?); | 5987 | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 6176 | } | 5988 | } |
| 6177 | } | 5989 | } |
| 6178 | | 5990 | |
| 6179 | if (self.data_const_segment_cmd_index) |data_const_segment_cmd_index| blk: { | 5991 | if (self.got_section_index) |sect_id| { |
| 6180 | const got_section_index = self.got_section_index orelse break :blk; | 5992 | const got = &self.sections.items(.header)[sect_id]; |
| 6181 | const got = self.getSectionPtr(.{ | | |
| 6182 | .seg = data_const_segment_cmd_index, | | |
| 6183 | .sect = got_section_index, | | |
| 6184 | }); | | |
| 6185 | got.reserved1 = nstubs; | 5993 | got.reserved1 = nstubs; |
| 6186 | for (self.got_entries.items) |entry| { | 5994 | for (self.got_entries.items) |entry| { |
| 6187 | if (entry.sym_index == 0) continue; | 5995 | if (entry.sym_index == 0) continue; |
| ... | @@ -6189,19 +5997,15 @@ fn writeSymtab(self: *MachO) !void { | ... | @@ -6189,19 +5997,15 @@ fn writeSymtab(self: *MachO) !void { |
| 6189 | if (atom_sym.n_desc == N_DESC_GCED) continue; | 5997 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 6190 | const target_sym = self.getSymbol(entry.target); | 5998 | const target_sym = self.getSymbol(entry.target); |
| 6191 | if (target_sym.undf()) { | 5999 | if (target_sym.undf()) { |
| 6192 | try writer.writeIntLittle(u32, dysymtab.iundefsym + imports_table.get(entry.target).?); | 6000 | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 6193 | } else { | 6001 | } else { |
| 6194 | try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL); | 6002 | try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL); |
| 6195 | } | 6003 | } |
| 6196 | } | 6004 | } |
| 6197 | } | 6005 | } |
| 6198 | | 6006 | |
| 6199 | if (self.data_segment_cmd_index) |data_segment_cmd_index| blk: { | 6007 | if (self.la_symbol_ptr_section_index) |sect_id| { |
| 6200 | const la_symbol_ptr_section_index = self.la_symbol_ptr_section_index orelse break :blk; | 6008 | const la_symbol_ptr = &self.sections.items(.header)[sect_id]; |
| 6201 | const la_symbol_ptr = self.getSectionPtr(.{ | | |
| 6202 | .seg = data_segment_cmd_index, | | |
| 6203 | .sect = la_symbol_ptr_section_index, | | |
| 6204 | }); | | |
| 6205 | la_symbol_ptr.reserved1 = nstubs + ngot_entries; | 6009 | la_symbol_ptr.reserved1 = nstubs + ngot_entries; |
| 6206 | for (self.stubs.items) |entry| { | 6010 | for (self.stubs.items) |entry| { |
| 6207 | if (entry.sym_index == 0) continue; | 6011 | if (entry.sym_index == 0) continue; |
| ... | @@ -6209,131 +6013,76 @@ fn writeSymtab(self: *MachO) !void { | ... | @@ -6209,131 +6013,76 @@ fn writeSymtab(self: *MachO) !void { |
| 6209 | if (atom_sym.n_desc == N_DESC_GCED) continue; | 6013 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 6210 | const target_sym = self.getSymbol(entry.target); | 6014 | const target_sym = self.getSymbol(entry.target); |
| 6211 | assert(target_sym.undf()); | 6015 | assert(target_sym.undf()); |
| 6212 | try writer.writeIntLittle(u32, dysymtab.iundefsym + imports_table.get(entry.target).?); | 6016 | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 6213 | } | 6017 | } |
| 6214 | } | 6018 | } |
| 6215 | | 6019 | |
| 6216 | assert(buf.items.len == dysymtab.nindirectsyms * @sizeOf(u32)); | 6020 | assert(buf.items.len == needed_size); |
| 6217 | | 6021 | try self.base.file.?.pwriteAll(buf.items, offset); |
| 6218 | try self.base.file.?.pwriteAll(buf.items, dysymtab.indirectsymoff); | | |
| 6219 | self.load_commands_dirty = true; | | |
| 6220 | } | | |
| 6221 | | | |
| 6222 | fn writeStrtab(self: *MachO) !void { | | |
| 6223 | const tracy = trace(@src()); | | |
| 6224 | defer tracy.end(); | | |
| 6225 | | | |
| 6226 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; | | |
| 6227 | const symtab = &self.load_commands.items[self.symtab_cmd_index.?].symtab; | | |
| 6228 | const stroff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(u64)); | | |
| 6229 | | | |
| 6230 | const strsize = self.strtab.buffer.items.len; | | |
| 6231 | symtab.stroff = @intCast(u32, stroff); | | |
| 6232 | symtab.strsize = @intCast(u32, strsize); | | |
| 6233 | seg.inner.filesize = symtab.stroff + symtab.strsize - seg.inner.fileoff; | | |
| 6234 | | 6022 | |
| 6235 | log.debug("writing string table from 0x{x} to 0x{x}", .{ symtab.stroff, symtab.stroff + symtab.strsize }); | 6023 | lc.nlocalsym = ctx.nlocalsym; |
| 6236 | | 6024 | lc.iextdefsym = iextdefsym; |
| 6237 | try self.base.file.?.pwriteAll(self.strtab.buffer.items, symtab.stroff); | 6025 | lc.nextdefsym = ctx.nextdefsym; |
| 6238 | | 6026 | lc.iundefsym = iundefsym; |
| 6239 | self.load_commands_dirty = true; | 6027 | lc.nundefsym = ctx.nundefsym; |
| 6240 | } | 6028 | lc.indirectsymoff = @intCast(u32, offset); |
| 6241 | | 6029 | lc.nindirectsyms = nindirectsyms; |
| 6242 | fn writeLinkeditSegment(self: *MachO) !void { | | |
| 6243 | const tracy = trace(@src()); | | |
| 6244 | defer tracy.end(); | | |
| 6245 | | | |
| 6246 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; | | |
| 6247 | seg.inner.filesize = 0; | | |
| 6248 | | | |
| 6249 | try self.writeDyldInfoData(); | | |
| 6250 | try self.writeFunctionStarts(); | | |
| 6251 | try self.writeDataInCode(); | | |
| 6252 | try self.writeSymtab(); | | |
| 6253 | try self.writeStrtab(); | | |
| 6254 | | | |
| 6255 | seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size); | | |
| 6256 | } | 6030 | } |
| 6257 | | 6031 | |
| 6258 | fn writeCodeSignaturePadding(self: *MachO, code_sig: *CodeSignature) !void { | 6032 | fn writeCodeSignaturePadding( |
| 6259 | const tracy = trace(@src()); | 6033 | self: *MachO, |
| 6260 | defer tracy.end(); | 6034 | code_sig: *CodeSignature, |
| 6261 | | 6035 | ncmds: *u32, |
| 6262 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; | 6036 | lc_writer: anytype, |
| 6263 | const cs_cmd = &self.load_commands.items[self.code_signature_cmd_index.?].linkedit_data; | 6037 | ) !u32 { |
| | 6038 | const seg = &self.segments.items[self.linkedit_segment_cmd_index.?]; |
| 6264 | // Code signature data has to be 16-bytes aligned for Apple tools to recognize the file | 6039 | // Code signature data has to be 16-bytes aligned for Apple tools to recognize the file |
| 6265 | // https://github.com/opensource-apple/cctools/blob/fdb4825f303fd5c0751be524babd32958181b3ed/libstuff/checkout.c#L271 | 6040 | // https://github.com/opensource-apple/cctools/blob/fdb4825f303fd5c0751be524babd32958181b3ed/libstuff/checkout.c#L271 |
| 6266 | const dataoff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, 16); | 6041 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, 16); |
| 6267 | const datasize = code_sig.estimateSize(dataoff); | 6042 | const needed_size = code_sig.estimateSize(offset); |
| 6268 | cs_cmd.dataoff = @intCast(u32, dataoff); | 6043 | seg.filesize = offset + needed_size - seg.fileoff; |
| 6269 | cs_cmd.datasize = @intCast(u32, code_sig.estimateSize(dataoff)); | 6044 | seg.vmsize = mem.alignForwardGeneric(u64, seg.filesize, self.page_size); |
| 6270 | | 6045 | log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 6271 | // Advance size of __LINKEDIT segment | | |
| 6272 | seg.inner.filesize = cs_cmd.dataoff + cs_cmd.datasize - seg.inner.fileoff; | | |
| 6273 | seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size); | | |
| 6274 | log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ dataoff, dataoff + datasize }); | | |
| 6275 | // Pad out the space. We need to do this to calculate valid hashes for everything in the file | 6046 | // Pad out the space. We need to do this to calculate valid hashes for everything in the file |
| 6276 | // except for code signature data. | 6047 | // except for code signature data. |
| 6277 | try self.base.file.?.pwriteAll(&[_]u8{0}, dataoff + datasize - 1); | 6048 | try self.base.file.?.pwriteAll(&[_]u8{0}, offset + needed_size - 1); |
| 6278 | self.load_commands_dirty = true; | | |
| 6279 | } | | |
| 6280 | | 6049 | |
| 6281 | fn writeCodeSignature(self: *MachO, code_sig: *CodeSignature) !void { | 6050 | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 6282 | const tracy = trace(@src()); | 6051 | .cmd = .CODE_SIGNATURE, |
| 6283 | defer tracy.end(); | 6052 | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| | 6053 | .dataoff = @intCast(u32, offset), |
| | 6054 | .datasize = @intCast(u32, needed_size), |
| | 6055 | }); |
| | 6056 | ncmds.* += 1; |
| | 6057 | |
| | 6058 | return @intCast(u32, offset); |
| | 6059 | } |
| 6284 | | 6060 | |
| 6285 | const code_sig_cmd = self.load_commands.items[self.code_signature_cmd_index.?].linkedit_data; | 6061 | fn writeCodeSignature(self: *MachO, code_sig: *CodeSignature, offset: u32) !void { |
| 6286 | const seg = self.load_commands.items[self.text_segment_cmd_index.?].segment; | 6062 | const seg = self.segments.items[self.text_segment_cmd_index.?]; |
| 6287 | | 6063 | |
| 6288 | var buffer = std.ArrayList(u8).init(self.base.allocator); | 6064 | var buffer = std.ArrayList(u8).init(self.base.allocator); |
| 6289 | defer buffer.deinit(); | 6065 | defer buffer.deinit(); |
| 6290 | try buffer.ensureTotalCapacityPrecise(code_sig.size()); | 6066 | try buffer.ensureTotalCapacityPrecise(code_sig.size()); |
| 6291 | try code_sig.writeAdhocSignature(self.base.allocator, .{ | 6067 | try code_sig.writeAdhocSignature(self.base.allocator, .{ |
| 6292 | .file = self.base.file.?, | 6068 | .file = self.base.file.?, |
| 6293 | .exec_seg_base = seg.inner.fileoff, | 6069 | .exec_seg_base = seg.fileoff, |
| 6294 | .exec_seg_limit = seg.inner.filesize, | 6070 | .exec_seg_limit = seg.filesize, |
| 6295 | .code_sig_cmd = code_sig_cmd, | 6071 | .file_size = offset, |
| 6296 | .output_mode = self.base.options.output_mode, | 6072 | .output_mode = self.base.options.output_mode, |
| 6297 | }, buffer.writer()); | 6073 | }, buffer.writer()); |
| 6298 | assert(buffer.items.len == code_sig.size()); | 6074 | assert(buffer.items.len == code_sig.size()); |
| 6299 | | 6075 | |
| 6300 | log.debug("writing code signature from 0x{x} to 0x{x}", .{ | 6076 | log.debug("writing code signature from 0x{x} to 0x{x}", .{ |
| 6301 | code_sig_cmd.dataoff, | 6077 | offset, |
| 6302 | code_sig_cmd.dataoff + buffer.items.len, | 6078 | offset + buffer.items.len, |
| 6303 | }); | 6079 | }); |
| 6304 | | 6080 | |
| 6305 | try self.base.file.?.pwriteAll(buffer.items, code_sig_cmd.dataoff); | 6081 | try self.base.file.?.pwriteAll(buffer.items, offset); |
| 6306 | } | | |
| 6307 | | | |
| 6308 | /// Writes all load commands and section headers. | | |
| 6309 | fn writeLoadCommands(self: *MachO) !void { | | |
| 6310 | if (!self.load_commands_dirty) return; | | |
| 6311 | | | |
| 6312 | var sizeofcmds: u32 = 0; | | |
| 6313 | for (self.load_commands.items) |lc| { | | |
| 6314 | if (lc.cmd() == .NONE) continue; | | |
| 6315 | sizeofcmds += lc.cmdsize(); | | |
| 6316 | } | | |
| 6317 | | | |
| 6318 | var buffer = try self.base.allocator.alloc(u8, sizeofcmds); | | |
| 6319 | defer self.base.allocator.free(buffer); | | |
| 6320 | var fib = std.io.fixedBufferStream(buffer); | | |
| 6321 | const writer = fib.writer(); | | |
| 6322 | for (self.load_commands.items) |lc| { | | |
| 6323 | if (lc.cmd() == .NONE) continue; | | |
| 6324 | try lc.write(writer); | | |
| 6325 | } | | |
| 6326 | | | |
| 6327 | const off = @sizeOf(macho.mach_header_64); | | |
| 6328 | | | |
| 6329 | log.debug("writing load commands from 0x{x} to 0x{x}", .{ off, off + sizeofcmds }); | | |
| 6330 | | | |
| 6331 | try self.base.file.?.pwriteAll(buffer, off); | | |
| 6332 | self.load_commands_dirty = false; | | |
| 6333 | } | 6082 | } |
| 6334 | | 6083 | |
| 6335 | /// Writes Mach-O file header. | 6084 | /// Writes Mach-O file header. |
| 6336 | fn writeHeader(self: *MachO) !void { | 6085 | fn writeHeader(self: *MachO, ncmds: u32, sizeofcmds: u32) !void { |
| 6337 | var header: macho.mach_header_64 = .{}; | 6086 | var header: macho.mach_header_64 = .{}; |
| 6338 | header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE | macho.MH_TWOLEVEL; | 6087 | header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE | macho.MH_TWOLEVEL; |
| 6339 | | 6088 | |
| ... | @@ -6365,14 +6114,8 @@ fn writeHeader(self: *MachO) !void { | ... | @@ -6365,14 +6114,8 @@ fn writeHeader(self: *MachO) !void { |
| 6365 | header.flags |= macho.MH_HAS_TLV_DESCRIPTORS; | 6114 | header.flags |= macho.MH_HAS_TLV_DESCRIPTORS; |
| 6366 | } | 6115 | } |
| 6367 | | 6116 | |
| 6368 | header.ncmds = 0; | 6117 | header.ncmds = ncmds; |
| 6369 | header.sizeofcmds = 0; | 6118 | header.sizeofcmds = sizeofcmds; |
| 6370 | | | |
| 6371 | for (self.load_commands.items) |cmd| { | | |
| 6372 | if (cmd.cmd() == .NONE) continue; | | |
| 6373 | header.sizeofcmds += cmd.cmdsize(); | | |
| 6374 | header.ncmds += 1; | | |
| 6375 | } | | |
| 6376 | | 6119 | |
| 6377 | log.debug("writing Mach-O header {}", .{header}); | 6120 | log.debug("writing Mach-O header {}", .{header}); |
| 6378 | | 6121 | |
| ... | @@ -6392,33 +6135,13 @@ pub fn makeStaticString(bytes: []const u8) [16]u8 { | ... | @@ -6392,33 +6135,13 @@ pub fn makeStaticString(bytes: []const u8) [16]u8 { |
| 6392 | return buf; | 6135 | return buf; |
| 6393 | } | 6136 | } |
| 6394 | | 6137 | |
| 6395 | pub fn getSectionOrdinal(self: *MachO, match: MatchingSection) u8 { | 6138 | fn getSectionIndexes(self: MachO, segment_index: u8) struct { start: u8, end: u8 } { |
| 6396 | return @intCast(u8, self.section_ordinals.getIndex(match).?) + 1; | 6139 | var start: u8 = 0; |
| 6397 | } | 6140 | const nsects = for (self.segments.items) |seg, i| { |
| 6398 | | 6141 | if (i == segment_index) break @intCast(u8, seg.nsects); |
| 6399 | pub fn getMatchingSectionFromOrdinal(self: *MachO, ord: u8) MatchingSection { | 6142 | start += @intCast(u8, seg.nsects); |
| 6400 | const index = ord - 1; | 6143 | } else 0; |
| 6401 | assert(index < self.section_ordinals.count()); | 6144 | return .{ .start = start, .end = start + nsects }; |
| 6402 | return self.section_ordinals.keys()[index]; | | |
| 6403 | } | | |
| 6404 | | | |
| 6405 | pub fn getSegmentPtr(self: *MachO, match: MatchingSection) *macho.SegmentCommand { | | |
| 6406 | assert(match.seg < self.load_commands.items.len); | | |
| 6407 | return &self.load_commands.items[match.seg].segment; | | |
| 6408 | } | | |
| 6409 | | | |
| 6410 | pub fn getSegment(self: *MachO, match: MatchingSection) macho.SegmentCommand { | | |
| 6411 | return self.getSegmentPtr(match).*; | | |
| 6412 | } | | |
| 6413 | | | |
| 6414 | pub fn getSectionPtr(self: *MachO, match: MatchingSection) *macho.section_64 { | | |
| 6415 | const seg = self.getSegmentPtr(match); | | |
| 6416 | assert(match.sect < seg.sections.items.len); | | |
| 6417 | return &seg.sections.items[match.sect]; | | |
| 6418 | } | | |
| 6419 | | | |
| 6420 | pub fn getSection(self: *MachO, match: MatchingSection) macho.section_64 { | | |
| 6421 | return self.getSectionPtr(match).*; | | |
| 6422 | } | 6145 | } |
| 6423 | | 6146 | |
| 6424 | pub fn symbolIsTemp(self: *MachO, sym_with_loc: SymbolWithLoc) bool { | 6147 | pub fn symbolIsTemp(self: *MachO, sym_with_loc: SymbolWithLoc) bool { |
| ... | @@ -6512,72 +6235,6 @@ pub fn findFirst(comptime T: type, haystack: []const T, start: usize, predicate: | ... | @@ -6512,72 +6235,6 @@ pub fn findFirst(comptime T: type, haystack: []const T, start: usize, predicate: |
| 6512 | return i; | 6235 | return i; |
| 6513 | } | 6236 | } |
| 6514 | | 6237 | |
| 6515 | const DebugInfo = struct { | | |
| 6516 | inner: dwarf.DwarfInfo, | | |
| 6517 | debug_info: []const u8, | | |
| 6518 | debug_abbrev: []const u8, | | |
| 6519 | debug_str: []const u8, | | |
| 6520 | debug_line: []const u8, | | |
| 6521 | debug_line_str: []const u8, | | |
| 6522 | debug_ranges: []const u8, | | |
| 6523 | | | |
| 6524 | pub fn parse(allocator: Allocator, object: Object) !?DebugInfo { | | |
| 6525 | var debug_info = blk: { | | |
| 6526 | const index = object.dwarf_debug_info_index orelse return null; | | |
| 6527 | break :blk try object.getSectionContents(index); | | |
| 6528 | }; | | |
| 6529 | var debug_abbrev = blk: { | | |
| 6530 | const index = object.dwarf_debug_abbrev_index orelse return null; | | |
| 6531 | break :blk try object.getSectionContents(index); | | |
| 6532 | }; | | |
| 6533 | var debug_str = blk: { | | |
| 6534 | const index = object.dwarf_debug_str_index orelse return null; | | |
| 6535 | break :blk try object.getSectionContents(index); | | |
| 6536 | }; | | |
| 6537 | var debug_line = blk: { | | |
| 6538 | const index = object.dwarf_debug_line_index orelse return null; | | |
| 6539 | break :blk try object.getSectionContents(index); | | |
| 6540 | }; | | |
| 6541 | var debug_line_str = blk: { | | |
| 6542 | if (object.dwarf_debug_line_str_index) |ind| { | | |
| 6543 | break :blk try object.getSectionContents(ind); | | |
| 6544 | } | | |
| 6545 | break :blk &[0]u8{}; | | |
| 6546 | }; | | |
| 6547 | var debug_ranges = blk: { | | |
| 6548 | if (object.dwarf_debug_ranges_index) |ind| { | | |
| 6549 | break :blk try object.getSectionContents(ind); | | |
| 6550 | } | | |
| 6551 | break :blk &[0]u8{}; | | |
| 6552 | }; | | |
| 6553 | | | |
| 6554 | var inner: dwarf.DwarfInfo = .{ | | |
| 6555 | .endian = .Little, | | |
| 6556 | .debug_info = debug_info, | | |
| 6557 | .debug_abbrev = debug_abbrev, | | |
| 6558 | .debug_str = debug_str, | | |
| 6559 | .debug_line = debug_line, | | |
| 6560 | .debug_line_str = debug_line_str, | | |
| 6561 | .debug_ranges = debug_ranges, | | |
| 6562 | }; | | |
| 6563 | try dwarf.openDwarfDebugInfo(&inner, allocator); | | |
| 6564 | | | |
| 6565 | return DebugInfo{ | | |
| 6566 | .inner = inner, | | |
| 6567 | .debug_info = debug_info, | | |
| 6568 | .debug_abbrev = debug_abbrev, | | |
| 6569 | .debug_str = debug_str, | | |
| 6570 | .debug_line = debug_line, | | |
| 6571 | .debug_line_str = debug_line_str, | | |
| 6572 | .debug_ranges = debug_ranges, | | |
| 6573 | }; | | |
| 6574 | } | | |
| 6575 | | | |
| 6576 | pub fn deinit(self: *DebugInfo, allocator: Allocator) void { | | |
| 6577 | self.inner.deinit(allocator); | | |
| 6578 | } | | |
| 6579 | }; | | |
| 6580 | | | |
| 6581 | pub fn generateSymbolStabs( | 6238 | pub fn generateSymbolStabs( |
| 6582 | self: *MachO, | 6239 | self: *MachO, |
| 6583 | object: Object, | 6240 | object: Object, |
| ... | @@ -6585,14 +6242,15 @@ pub fn generateSymbolStabs( | ... | @@ -6585,14 +6242,15 @@ pub fn generateSymbolStabs( |
| 6585 | ) !void { | 6242 | ) !void { |
| 6586 | assert(!self.base.options.strip); | 6243 | assert(!self.base.options.strip); |
| 6587 | | 6244 | |
| 6588 | const gpa = self.base.allocator; | | |
| 6589 | | | |
| 6590 | log.debug("parsing debug info in '{s}'", .{object.name}); | 6245 | log.debug("parsing debug info in '{s}'", .{object.name}); |
| 6591 | | 6246 | |
| 6592 | var debug_info = (try DebugInfo.parse(gpa, object)) orelse return; | 6247 | const gpa = self.base.allocator; |
| | 6248 | var debug_info = try object.parseDwarfInfo(); |
| | 6249 | defer debug_info.deinit(gpa); |
| | 6250 | try dwarf.openDwarfDebugInfo(&debug_info, gpa); |
| 6593 | | 6251 | |
| 6594 | // We assume there is only one CU. | 6252 | // We assume there is only one CU. |
| 6595 | const compile_unit = debug_info.inner.findCompileUnit(0x0) catch |err| switch (err) { | 6253 | const compile_unit = debug_info.findCompileUnit(0x0) catch |err| switch (err) { |
| 6596 | error.MissingDebugInfo => { | 6254 | error.MissingDebugInfo => { |
| 6597 | // TODO audit cases with missing debug info and audit our dwarf.zig module. | 6255 | // TODO audit cases with missing debug info and audit our dwarf.zig module. |
| 6598 | log.debug("invalid or missing debug info in {s}; skipping", .{object.name}); | 6256 | log.debug("invalid or missing debug info in {s}; skipping", .{object.name}); |
| ... | @@ -6600,8 +6258,8 @@ pub fn generateSymbolStabs( | ... | @@ -6600,8 +6258,8 @@ pub fn generateSymbolStabs( |
| 6600 | }, | 6258 | }, |
| 6601 | else => |e| return e, | 6259 | else => |e| return e, |
| 6602 | }; | 6260 | }; |
| 6603 | const tu_name = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT.name); | 6261 | const tu_name = try compile_unit.die.getAttrString(&debug_info, dwarf.AT.name); |
| 6604 | const tu_comp_dir = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT.comp_dir); | 6262 | const tu_comp_dir = try compile_unit.die.getAttrString(&debug_info, dwarf.AT.comp_dir); |
| 6605 | | 6263 | |
| 6606 | // Open scope | 6264 | // Open scope |
| 6607 | try locals.ensureUnusedCapacity(3); | 6265 | try locals.ensureUnusedCapacity(3); |
| ... | @@ -6664,7 +6322,7 @@ pub fn generateSymbolStabs( | ... | @@ -6664,7 +6322,7 @@ pub fn generateSymbolStabs( |
| 6664 | fn generateSymbolStabsForSymbol( | 6322 | fn generateSymbolStabsForSymbol( |
| 6665 | self: *MachO, | 6323 | self: *MachO, |
| 6666 | sym_loc: SymbolWithLoc, | 6324 | sym_loc: SymbolWithLoc, |
| 6667 | debug_info: DebugInfo, | 6325 | debug_info: dwarf.DwarfInfo, |
| 6668 | buf: *[4]macho.nlist_64, | 6326 | buf: *[4]macho.nlist_64, |
| 6669 | ) ![]const macho.nlist_64 { | 6327 | ) ![]const macho.nlist_64 { |
| 6670 | const gpa = self.base.allocator; | 6328 | const gpa = self.base.allocator; |
| ... | @@ -6679,7 +6337,7 @@ fn generateSymbolStabsForSymbol( | ... | @@ -6679,7 +6337,7 @@ fn generateSymbolStabsForSymbol( |
| 6679 | const source_sym = object.getSourceSymbol(sym_loc.sym_index) orelse return buf[0..0]; | 6337 | const source_sym = object.getSourceSymbol(sym_loc.sym_index) orelse return buf[0..0]; |
| 6680 | const size: ?u64 = size: { | 6338 | const size: ?u64 = size: { |
| 6681 | if (source_sym.tentative()) break :size null; | 6339 | if (source_sym.tentative()) break :size null; |
| 6682 | for (debug_info.inner.func_list.items) |func| { | 6340 | for (debug_info.func_list.items) |func| { |
| 6683 | if (func.pc_range) |range| { | 6341 | if (func.pc_range) |range| { |
| 6684 | if (source_sym.n_value >= range.start and source_sym.n_value < range.end) { | 6342 | if (source_sym.n_value >= range.start and source_sym.n_value < range.end) { |
| 6685 | break :size range.end - range.start; | 6343 | break :size range.end - range.start; |
| ... | @@ -6731,260 +6389,260 @@ fn generateSymbolStabsForSymbol( | ... | @@ -6731,260 +6389,260 @@ fn generateSymbolStabsForSymbol( |
| 6731 | } | 6389 | } |
| 6732 | } | 6390 | } |
| 6733 | | 6391 | |
| 6734 | fn snapshotState(self: *MachO) !void { | 6392 | // fn snapshotState(self: *MachO) !void { |
| 6735 | const emit = self.base.options.emit orelse { | 6393 | // const emit = self.base.options.emit orelse { |
| 6736 | log.debug("no emit directory found; skipping snapshot...", .{}); | 6394 | // log.debug("no emit directory found; skipping snapshot...", .{}); |
| 6737 | return; | 6395 | // return; |
| 6738 | }; | 6396 | // }; |
| 6739 | | 6397 | |
| 6740 | const Snapshot = struct { | 6398 | // const Snapshot = struct { |
| 6741 | const Node = struct { | 6399 | // const Node = struct { |
| 6742 | const Tag = enum { | 6400 | // const Tag = enum { |
| 6743 | section_start, | 6401 | // section_start, |
| 6744 | section_end, | 6402 | // section_end, |
| 6745 | atom_start, | 6403 | // atom_start, |
| 6746 | atom_end, | 6404 | // atom_end, |
| 6747 | relocation, | 6405 | // relocation, |
| 6748 | | 6406 | |
| 6749 | pub fn jsonStringify( | 6407 | // pub fn jsonStringify( |
| 6750 | tag: Tag, | 6408 | // tag: Tag, |
| 6751 | options: std.json.StringifyOptions, | 6409 | // options: std.json.StringifyOptions, |
| 6752 | out_stream: anytype, | 6410 | // out_stream: anytype, |
| 6753 | ) !void { | 6411 | // ) !void { |
| 6754 | _ = options; | 6412 | // _ = options; |
| 6755 | switch (tag) { | 6413 | // switch (tag) { |
| 6756 | .section_start => try out_stream.writeAll("\"section_start\""), | 6414 | // .section_start => try out_stream.writeAll("\"section_start\""), |
| 6757 | .section_end => try out_stream.writeAll("\"section_end\""), | 6415 | // .section_end => try out_stream.writeAll("\"section_end\""), |
| 6758 | .atom_start => try out_stream.writeAll("\"atom_start\""), | 6416 | // .atom_start => try out_stream.writeAll("\"atom_start\""), |
| 6759 | .atom_end => try out_stream.writeAll("\"atom_end\""), | 6417 | // .atom_end => try out_stream.writeAll("\"atom_end\""), |
| 6760 | .relocation => try out_stream.writeAll("\"relocation\""), | 6418 | // .relocation => try out_stream.writeAll("\"relocation\""), |
| 6761 | } | 6419 | // } |
| 6762 | } | 6420 | // } |
| 6763 | }; | 6421 | // }; |
| 6764 | const Payload = struct { | 6422 | // const Payload = struct { |
| 6765 | name: []const u8 = "", | 6423 | // name: []const u8 = "", |
| 6766 | aliases: [][]const u8 = &[0][]const u8{}, | 6424 | // aliases: [][]const u8 = &[0][]const u8{}, |
| 6767 | is_global: bool = false, | 6425 | // is_global: bool = false, |
| 6768 | target: u64 = 0, | 6426 | // target: u64 = 0, |
| 6769 | }; | 6427 | // }; |
| 6770 | address: u64, | 6428 | // address: u64, |
| 6771 | tag: Tag, | 6429 | // tag: Tag, |
| 6772 | payload: Payload, | 6430 | // payload: Payload, |
| 6773 | }; | 6431 | // }; |
| 6774 | timestamp: i128, | 6432 | // timestamp: i128, |
| 6775 | nodes: []Node, | 6433 | // nodes: []Node, |
| 6776 | }; | 6434 | // }; |
| 6777 | | 6435 | |
| 6778 | var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator); | 6436 | // var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator); |
| 6779 | defer arena_allocator.deinit(); | 6437 | // defer arena_allocator.deinit(); |
| 6780 | const arena = arena_allocator.allocator(); | 6438 | // const arena = arena_allocator.allocator(); |
| 6781 | | 6439 | |
| 6782 | const out_file = try emit.directory.handle.createFile("snapshots.json", .{ | 6440 | // const out_file = try emit.directory.handle.createFile("snapshots.json", .{ |
| 6783 | .truncate = false, | 6441 | // .truncate = false, |
| 6784 | .read = true, | 6442 | // .read = true, |
| 6785 | }); | 6443 | // }); |
| 6786 | defer out_file.close(); | 6444 | // defer out_file.close(); |
| 6787 | | 6445 | |
| 6788 | if (out_file.seekFromEnd(-1)) { | 6446 | // if (out_file.seekFromEnd(-1)) { |
| 6789 | try out_file.writer().writeByte(','); | 6447 | // try out_file.writer().writeByte(','); |
| 6790 | } else |err| switch (err) { | 6448 | // } else |err| switch (err) { |
| 6791 | error.Unseekable => try out_file.writer().writeByte('['), | 6449 | // error.Unseekable => try out_file.writer().writeByte('['), |
| 6792 | else => |e| return e, | 6450 | // else => |e| return e, |
| 6793 | } | 6451 | // } |
| 6794 | const writer = out_file.writer(); | 6452 | // const writer = out_file.writer(); |
| 6795 | | 6453 | |
| 6796 | var snapshot = Snapshot{ | 6454 | // var snapshot = Snapshot{ |
| 6797 | .timestamp = std.time.nanoTimestamp(), | 6455 | // .timestamp = std.time.nanoTimestamp(), |
| 6798 | .nodes = undefined, | 6456 | // .nodes = undefined, |
| 6799 | }; | 6457 | // }; |
| 6800 | var nodes = std.ArrayList(Snapshot.Node).init(arena); | 6458 | // var nodes = std.ArrayList(Snapshot.Node).init(arena); |
| 6801 | | 6459 | |
| 6802 | for (self.section_ordinals.keys()) |key| { | 6460 | // for (self.section_ordinals.keys()) |key| { |
| 6803 | const sect = self.getSection(key); | 6461 | // const sect = self.getSection(key); |
| 6804 | const sect_name = try std.fmt.allocPrint(arena, "{s},{s}", .{ sect.segName(), sect.sectName() }); | 6462 | // const sect_name = try std.fmt.allocPrint(arena, "{s},{s}", .{ sect.segName(), sect.sectName() }); |
| 6805 | try nodes.append(.{ | 6463 | // try nodes.append(.{ |
| 6806 | .address = sect.addr, | 6464 | // .address = sect.addr, |
| 6807 | .tag = .section_start, | 6465 | // .tag = .section_start, |
| 6808 | .payload = .{ .name = sect_name }, | 6466 | // .payload = .{ .name = sect_name }, |
| 6809 | }); | 6467 | // }); |
| 6810 | | 6468 | |
| 6811 | const is_tlv = sect.type_() == macho.S_THREAD_LOCAL_VARIABLES; | 6469 | // const is_tlv = sect.type_() == macho.S_THREAD_LOCAL_VARIABLES; |
| 6812 | | 6470 | |
| 6813 | var atom: *Atom = self.atoms.get(key) orelse { | 6471 | // var atom: *Atom = self.atoms.get(key) orelse { |
| 6814 | try nodes.append(.{ | 6472 | // try nodes.append(.{ |
| 6815 | .address = sect.addr + sect.size, | 6473 | // .address = sect.addr + sect.size, |
| 6816 | .tag = .section_end, | 6474 | // .tag = .section_end, |
| 6817 | .payload = .{}, | 6475 | // .payload = .{}, |
| 6818 | }); | 6476 | // }); |
| 6819 | continue; | 6477 | // continue; |
| 6820 | }; | 6478 | // }; |
| 6821 | | 6479 | |
| 6822 | while (atom.prev) |prev| { | 6480 | // while (atom.prev) |prev| { |
| 6823 | atom = prev; | 6481 | // atom = prev; |
| 6824 | } | 6482 | // } |
| 6825 | | 6483 | |
| 6826 | while (true) { | 6484 | // while (true) { |
| 6827 | const atom_sym = atom.getSymbol(self); | 6485 | // const atom_sym = atom.getSymbol(self); |
| 6828 | var node = Snapshot.Node{ | 6486 | // var node = Snapshot.Node{ |
| 6829 | .address = atom_sym.n_value, | 6487 | // .address = atom_sym.n_value, |
| 6830 | .tag = .atom_start, | 6488 | // .tag = .atom_start, |
| 6831 | .payload = .{ | 6489 | // .payload = .{ |
| 6832 | .name = atom.getName(self), | 6490 | // .name = atom.getName(self), |
| 6833 | .is_global = self.globals.contains(atom.getName(self)), | 6491 | // .is_global = self.globals.contains(atom.getName(self)), |
| 6834 | }, | 6492 | // }, |
| 6835 | }; | 6493 | // }; |
| 6836 | | 6494 | |
| 6837 | var aliases = std.ArrayList([]const u8).init(arena); | 6495 | // var aliases = std.ArrayList([]const u8).init(arena); |
| 6838 | for (atom.contained.items) |sym_off| { | 6496 | // for (atom.contained.items) |sym_off| { |
| 6839 | if (sym_off.offset == 0) { | 6497 | // if (sym_off.offset == 0) { |
| 6840 | try aliases.append(self.getSymbolName(.{ | 6498 | // try aliases.append(self.getSymbolName(.{ |
| 6841 | .sym_index = sym_off.sym_index, | 6499 | // .sym_index = sym_off.sym_index, |
| 6842 | .file = atom.file, | 6500 | // .file = atom.file, |
| 6843 | })); | 6501 | // })); |
| 6844 | } | 6502 | // } |
| 6845 | } | 6503 | // } |
| 6846 | node.payload.aliases = aliases.toOwnedSlice(); | 6504 | // node.payload.aliases = aliases.toOwnedSlice(); |
| 6847 | try nodes.append(node); | 6505 | // try nodes.append(node); |
| 6848 | | 6506 | |
| 6849 | var relocs = try std.ArrayList(Snapshot.Node).initCapacity(arena, atom.relocs.items.len); | 6507 | // var relocs = try std.ArrayList(Snapshot.Node).initCapacity(arena, atom.relocs.items.len); |
| 6850 | for (atom.relocs.items) |rel| { | 6508 | // for (atom.relocs.items) |rel| { |
| 6851 | const source_addr = blk: { | 6509 | // const source_addr = blk: { |
| 6852 | const source_sym = atom.getSymbol(self); | 6510 | // const source_sym = atom.getSymbol(self); |
| 6853 | break :blk source_sym.n_value + rel.offset; | 6511 | // break :blk source_sym.n_value + rel.offset; |
| 6854 | }; | 6512 | // }; |
| 6855 | const target_addr = blk: { | 6513 | // const target_addr = blk: { |
| 6856 | const target_atom = rel.getTargetAtom(self) orelse { | 6514 | // const target_atom = rel.getTargetAtom(self) orelse { |
| 6857 | // If there is no atom for target, we still need to check for special, atom-less | 6515 | // // If there is no atom for target, we still need to check for special, atom-less |
| 6858 | // symbols such as `___dso_handle`. | 6516 | // // symbols such as `___dso_handle`. |
| 6859 | const target_name = self.getSymbolName(rel.target); | 6517 | // const target_name = self.getSymbolName(rel.target); |
| 6860 | if (self.globals.contains(target_name)) { | 6518 | // if (self.globals.contains(target_name)) { |
| 6861 | const atomless_sym = self.getSymbol(rel.target); | 6519 | // const atomless_sym = self.getSymbol(rel.target); |
| 6862 | break :blk atomless_sym.n_value; | 6520 | // break :blk atomless_sym.n_value; |
| 6863 | } | 6521 | // } |
| 6864 | break :blk 0; | 6522 | // break :blk 0; |
| 6865 | }; | 6523 | // }; |
| 6866 | const target_sym = if (target_atom.isSymbolContained(rel.target, self)) | 6524 | // const target_sym = if (target_atom.isSymbolContained(rel.target, self)) |
| 6867 | self.getSymbol(rel.target) | 6525 | // self.getSymbol(rel.target) |
| 6868 | else | 6526 | // else |
| 6869 | target_atom.getSymbol(self); | 6527 | // target_atom.getSymbol(self); |
| 6870 | const base_address: u64 = if (is_tlv) base_address: { | 6528 | // const base_address: u64 = if (is_tlv) base_address: { |
| 6871 | const sect_id: u16 = sect_id: { | 6529 | // const sect_id: u16 = sect_id: { |
| 6872 | if (self.tlv_data_section_index) |i| { | 6530 | // if (self.tlv_data_section_index) |i| { |
| 6873 | break :sect_id i; | 6531 | // break :sect_id i; |
| 6874 | } else if (self.tlv_bss_section_index) |i| { | 6532 | // } else if (self.tlv_bss_section_index) |i| { |
| 6875 | break :sect_id i; | 6533 | // break :sect_id i; |
| 6876 | } else unreachable; | 6534 | // } else unreachable; |
| 6877 | }; | 6535 | // }; |
| 6878 | break :base_address self.getSection(.{ | 6536 | // break :base_address self.getSection(.{ |
| 6879 | .seg = self.data_segment_cmd_index.?, | 6537 | // .seg = self.data_segment_cmd_index.?, |
| 6880 | .sect = sect_id, | 6538 | // .sect = sect_id, |
| 6881 | }).addr; | 6539 | // }).addr; |
| 6882 | } else 0; | 6540 | // } else 0; |
| 6883 | break :blk target_sym.n_value - base_address; | 6541 | // break :blk target_sym.n_value - base_address; |
| 6884 | }; | 6542 | // }; |
| 6885 | | 6543 | |
| 6886 | relocs.appendAssumeCapacity(.{ | 6544 | // relocs.appendAssumeCapacity(.{ |
| 6887 | .address = source_addr, | 6545 | // .address = source_addr, |
| 6888 | .tag = .relocation, | 6546 | // .tag = .relocation, |
| 6889 | .payload = .{ .target = target_addr }, | 6547 | // .payload = .{ .target = target_addr }, |
| 6890 | }); | 6548 | // }); |
| 6891 | } | 6549 | // } |
| 6892 | | 6550 | |
| 6893 | if (atom.contained.items.len == 0) { | 6551 | // if (atom.contained.items.len == 0) { |
| 6894 | try nodes.appendSlice(relocs.items); | 6552 | // try nodes.appendSlice(relocs.items); |
| 6895 | } else { | 6553 | // } else { |
| 6896 | // Need to reverse iteration order of relocs since by default for relocatable sources | 6554 | // // Need to reverse iteration order of relocs since by default for relocatable sources |
| 6897 | // they come in reverse. For linking, this doesn't matter in any way, however, for | 6555 | // // they come in reverse. For linking, this doesn't matter in any way, however, for |
| 6898 | // arranging the memoryline for displaying it does. | 6556 | // // arranging the memoryline for displaying it does. |
| 6899 | std.mem.reverse(Snapshot.Node, relocs.items); | 6557 | // std.mem.reverse(Snapshot.Node, relocs.items); |
| 6900 | | 6558 | |
| 6901 | var next_i: usize = 0; | 6559 | // var next_i: usize = 0; |
| 6902 | var last_rel: usize = 0; | 6560 | // var last_rel: usize = 0; |
| 6903 | while (next_i < atom.contained.items.len) : (next_i += 1) { | 6561 | // while (next_i < atom.contained.items.len) : (next_i += 1) { |
| 6904 | const loc = SymbolWithLoc{ | 6562 | // const loc = SymbolWithLoc{ |
| 6905 | .sym_index = atom.contained.items[next_i].sym_index, | 6563 | // .sym_index = atom.contained.items[next_i].sym_index, |
| 6906 | .file = atom.file, | 6564 | // .file = atom.file, |
| 6907 | }; | 6565 | // }; |
| 6908 | const cont_sym = self.getSymbol(loc); | 6566 | // const cont_sym = self.getSymbol(loc); |
| 6909 | const cont_sym_name = self.getSymbolName(loc); | 6567 | // const cont_sym_name = self.getSymbolName(loc); |
| 6910 | var contained_node = Snapshot.Node{ | 6568 | // var contained_node = Snapshot.Node{ |
| 6911 | .address = cont_sym.n_value, | 6569 | // .address = cont_sym.n_value, |
| 6912 | .tag = .atom_start, | 6570 | // .tag = .atom_start, |
| 6913 | .payload = .{ | 6571 | // .payload = .{ |
| 6914 | .name = cont_sym_name, | 6572 | // .name = cont_sym_name, |
| 6915 | .is_global = self.globals.contains(cont_sym_name), | 6573 | // .is_global = self.globals.contains(cont_sym_name), |
| 6916 | }, | 6574 | // }, |
| 6917 | }; | 6575 | // }; |
| 6918 | | 6576 | |
| 6919 | // Accumulate aliases | 6577 | // // Accumulate aliases |
| 6920 | var inner_aliases = std.ArrayList([]const u8).init(arena); | 6578 | // var inner_aliases = std.ArrayList([]const u8).init(arena); |
| 6921 | while (true) { | 6579 | // while (true) { |
| 6922 | if (next_i + 1 >= atom.contained.items.len) break; | 6580 | // if (next_i + 1 >= atom.contained.items.len) break; |
| 6923 | const next_sym_loc = SymbolWithLoc{ | 6581 | // const next_sym_loc = SymbolWithLoc{ |
| 6924 | .sym_index = atom.contained.items[next_i + 1].sym_index, | 6582 | // .sym_index = atom.contained.items[next_i + 1].sym_index, |
| 6925 | .file = atom.file, | 6583 | // .file = atom.file, |
| 6926 | }; | 6584 | // }; |
| 6927 | const next_sym = self.getSymbol(next_sym_loc); | 6585 | // const next_sym = self.getSymbol(next_sym_loc); |
| 6928 | if (next_sym.n_value != cont_sym.n_value) break; | 6586 | // if (next_sym.n_value != cont_sym.n_value) break; |
| 6929 | const next_sym_name = self.getSymbolName(next_sym_loc); | 6587 | // const next_sym_name = self.getSymbolName(next_sym_loc); |
| 6930 | if (self.globals.contains(next_sym_name)) { | 6588 | // if (self.globals.contains(next_sym_name)) { |
| 6931 | try inner_aliases.append(contained_node.payload.name); | 6589 | // try inner_aliases.append(contained_node.payload.name); |
| 6932 | contained_node.payload.name = next_sym_name; | 6590 | // contained_node.payload.name = next_sym_name; |
| 6933 | contained_node.payload.is_global = true; | 6591 | // contained_node.payload.is_global = true; |
| 6934 | } else try inner_aliases.append(next_sym_name); | 6592 | // } else try inner_aliases.append(next_sym_name); |
| 6935 | next_i += 1; | 6593 | // next_i += 1; |
| 6936 | } | 6594 | // } |
| 6937 | | 6595 | |
| 6938 | const cont_size = if (next_i + 1 < atom.contained.items.len) | 6596 | // const cont_size = if (next_i + 1 < atom.contained.items.len) |
| 6939 | self.getSymbol(.{ | 6597 | // self.getSymbol(.{ |
| 6940 | .sym_index = atom.contained.items[next_i + 1].sym_index, | 6598 | // .sym_index = atom.contained.items[next_i + 1].sym_index, |
| 6941 | .file = atom.file, | 6599 | // .file = atom.file, |
| 6942 | }).n_value - cont_sym.n_value | 6600 | // }).n_value - cont_sym.n_value |
| 6943 | else | 6601 | // else |
| 6944 | atom_sym.n_value + atom.size - cont_sym.n_value; | 6602 | // atom_sym.n_value + atom.size - cont_sym.n_value; |
| 6945 | | 6603 | |
| 6946 | contained_node.payload.aliases = inner_aliases.toOwnedSlice(); | 6604 | // contained_node.payload.aliases = inner_aliases.toOwnedSlice(); |
| 6947 | try nodes.append(contained_node); | 6605 | // try nodes.append(contained_node); |
| 6948 | | 6606 | |
| 6949 | for (relocs.items[last_rel..]) |rel| { | 6607 | // for (relocs.items[last_rel..]) |rel| { |
| 6950 | if (rel.address >= cont_sym.n_value + cont_size) { | 6608 | // if (rel.address >= cont_sym.n_value + cont_size) { |
| 6951 | break; | 6609 | // break; |
| 6952 | } | 6610 | // } |
| 6953 | try nodes.append(rel); | 6611 | // try nodes.append(rel); |
| 6954 | last_rel += 1; | 6612 | // last_rel += 1; |
| 6955 | } | 6613 | // } |
| 6956 | | 6614 | |
| 6957 | try nodes.append(.{ | 6615 | // try nodes.append(.{ |
| 6958 | .address = cont_sym.n_value + cont_size, | 6616 | // .address = cont_sym.n_value + cont_size, |
| 6959 | .tag = .atom_end, | 6617 | // .tag = .atom_end, |
| 6960 | .payload = .{}, | 6618 | // .payload = .{}, |
| 6961 | }); | 6619 | // }); |
| 6962 | } | 6620 | // } |
| 6963 | } | 6621 | // } |
| 6964 | | 6622 | |
| 6965 | try nodes.append(.{ | 6623 | // try nodes.append(.{ |
| 6966 | .address = atom_sym.n_value + atom.size, | 6624 | // .address = atom_sym.n_value + atom.size, |
| 6967 | .tag = .atom_end, | 6625 | // .tag = .atom_end, |
| 6968 | .payload = .{}, | 6626 | // .payload = .{}, |
| 6969 | }); | 6627 | // }); |
| 6970 | | 6628 | |
| 6971 | if (atom.next) |next| { | 6629 | // if (atom.next) |next| { |
| 6972 | atom = next; | 6630 | // atom = next; |
| 6973 | } else break; | 6631 | // } else break; |
| 6974 | } | 6632 | // } |
| 6975 | | 6633 | |
| 6976 | try nodes.append(.{ | 6634 | // try nodes.append(.{ |
| 6977 | .address = sect.addr + sect.size, | 6635 | // .address = sect.addr + sect.size, |
| 6978 | .tag = .section_end, | 6636 | // .tag = .section_end, |
| 6979 | .payload = .{}, | 6637 | // .payload = .{}, |
| 6980 | }); | 6638 | // }); |
| 6981 | } | 6639 | // } |
| 6982 | | 6640 | |
| 6983 | snapshot.nodes = nodes.toOwnedSlice(); | 6641 | // snapshot.nodes = nodes.toOwnedSlice(); |
| 6984 | | 6642 | |
| 6985 | try std.json.stringify(snapshot, .{}, writer); | 6643 | // try std.json.stringify(snapshot, .{}, writer); |
| 6986 | try writer.writeByte(']'); | 6644 | // try writer.writeByte(']'); |
| 6987 | } | 6645 | // } |
| 6988 | | 6646 | |
| 6989 | fn logSymAttributes(sym: macho.nlist_64, buf: *[9]u8) []const u8 { | 6647 | fn logSymAttributes(sym: macho.nlist_64, buf: *[9]u8) []const u8 { |
| 6990 | mem.set(u8, buf[0..4], '_'); | 6648 | mem.set(u8, buf[0..4], '_'); |
| ... | @@ -7104,26 +6762,19 @@ fn logSymtab(self: *MachO) void { | ... | @@ -7104,26 +6762,19 @@ fn logSymtab(self: *MachO) void { |
| 7104 | } | 6762 | } |
| 7105 | } | 6763 | } |
| 7106 | | 6764 | |
| 7107 | fn logSectionOrdinals(self: *MachO) void { | | |
| 7108 | for (self.section_ordinals.keys()) |match, i| { | | |
| 7109 | const sect = self.getSection(match); | | |
| 7110 | log.debug("sect({d}, '{s},{s}')", .{ i + 1, sect.segName(), sect.sectName() }); | | |
| 7111 | } | | |
| 7112 | } | | |
| 7113 | | | |
| 7114 | fn logAtoms(self: *MachO) void { | 6765 | fn logAtoms(self: *MachO) void { |
| 7115 | log.debug("atoms:", .{}); | 6766 | log.debug("atoms:", .{}); |
| 7116 | var it = self.atoms.iterator(); | 6767 | |
| 7117 | while (it.next()) |entry| { | 6768 | const slice = self.sections.slice(); |
| 7118 | const match = entry.key_ptr.*; | 6769 | for (slice.items(.last_atom)) |last, i| { |
| 7119 | var atom = entry.value_ptr.*; | 6770 | var atom = last orelse continue; |
| | 6771 | const header = slice.items(.header)[i]; |
| 7120 | | 6772 | |
| 7121 | while (atom.prev) |prev| { | 6773 | while (atom.prev) |prev| { |
| 7122 | atom = prev; | 6774 | atom = prev; |
| 7123 | } | 6775 | } |
| 7124 | | 6776 | |
| 7125 | const sect = self.getSection(match); | 6777 | log.debug("{s},{s}", .{ header.segName(), header.sectName() }); |
| 7126 | log.debug("{s},{s}", .{ sect.segName(), sect.sectName() }); | | |
| 7127 | | 6778 | |
| 7128 | while (true) { | 6779 | while (true) { |
| 7129 | self.logAtom(atom); | 6780 | self.logAtom(atom); |