| ... | ... | @@ -4,6 +4,7 @@ const std = @import("std"); |
| 4 | 4 | const build_options = @import("build_options"); |
| 5 | 5 | const builtin = @import("builtin"); |
| 6 | 6 | const assert = std.debug.assert; |
| 7 | const dwarf = std.dwarf; |
| 7 | 8 | const fmt = std.fmt; |
| 8 | 9 | const fs = std.fs; |
| 9 | 10 | const log = std.log.scoped(.link); |
| ... | ... | @@ -15,6 +16,7 @@ const meta = std.meta; |
| 15 | 16 | const aarch64 = @import("../arch/aarch64/bits.zig"); |
| 16 | 17 | const bind = @import("MachO/bind.zig"); |
| 17 | 18 | const codegen = @import("../codegen.zig"); |
| 19 | const dead_strip = @import("MachO/dead_strip.zig"); |
| 18 | 20 | const link = @import("../link.zig"); |
| 19 | 21 | const llvm_backend = @import("../codegen/llvm.zig"); |
| 20 | 22 | const target_util = @import("../target.zig"); |
| ... | ... | @@ -35,8 +37,7 @@ const LibStub = @import("tapi.zig").LibStub; |
| 35 | 37 | const Liveness = @import("../Liveness.zig"); |
| 36 | 38 | const LlvmObject = @import("../codegen/llvm.zig").Object; |
| 37 | 39 | const Module = @import("../Module.zig"); |
| 38 | | const StringIndexAdapter = std.hash_map.StringIndexAdapter; |
| 39 | | const StringIndexContext = std.hash_map.StringIndexContext; |
| 40 | const StringTable = @import("strtab.zig").StringTable; |
| 40 | 41 | const Trie = @import("MachO/Trie.zig"); |
| 41 | 42 | const Type = @import("../type.zig").Type; |
| 42 | 43 | const TypedValue = @import("../TypedValue.zig"); |
| ... | ... | @@ -52,6 +53,8 @@ pub const SearchStrategy = enum { |
| 52 | 53 | dylibs_first, |
| 53 | 54 | }; |
| 54 | 55 | |
| 56 | pub const N_DESC_GCED: u16 = @bitCast(u16, @as(i16, -1)); |
| 57 | |
| 55 | 58 | const SystemLib = struct { |
| 56 | 59 | needed: bool = false, |
| 57 | 60 | weak: bool = false, |
| ... | ... | @@ -69,10 +72,10 @@ d_sym: ?DebugSymbols = null, |
| 69 | 72 | /// For x86_64 that's 4KB, whereas for aarch64, that's 16KB. |
| 70 | 73 | page_size: u16, |
| 71 | 74 | |
| 72 | | /// If true, the linker will preallocate several sections and segments before starting the linking |
| 73 | | /// process. This is for example true for stage2 debug builds, however, this is false for stage1 |
| 74 | | /// and potentially stage2 release builds in the future. |
| 75 | | needs_prealloc: bool = true, |
| 75 | /// Mode of operation: incremental - will preallocate segments/sections and is compatible with |
| 76 | /// watch and HCS modes of operation; one_shot - will link relocatables in a traditional, one-shot |
| 77 | /// fashion (default for LLVM backend). |
| 78 | mode: enum { incremental, one_shot }, |
| 76 | 79 | |
| 77 | 80 | /// The absolute address of the entry point. |
| 78 | 81 | entry_addr: ?u64 = null, |
| ... | ... | @@ -151,53 +154,48 @@ rustc_section_index: ?u16 = null, |
| 151 | 154 | rustc_section_size: u64 = 0, |
| 152 | 155 | |
| 153 | 156 | locals: std.ArrayListUnmanaged(macho.nlist_64) = .{}, |
| 154 | | globals: std.ArrayListUnmanaged(macho.nlist_64) = .{}, |
| 155 | | undefs: std.ArrayListUnmanaged(macho.nlist_64) = .{}, |
| 156 | | symbol_resolver: std.AutoHashMapUnmanaged(u32, SymbolWithLoc) = .{}, |
| 157 | | unresolved: std.AutoArrayHashMapUnmanaged(u32, enum { |
| 158 | | none, |
| 159 | | stub, |
| 160 | | got, |
| 161 | | }) = .{}, |
| 162 | | tentatives: std.AutoArrayHashMapUnmanaged(u32, void) = .{}, |
| 157 | globals: std.StringArrayHashMapUnmanaged(SymbolWithLoc) = .{}, |
| 158 | // FIXME Jakub |
| 159 | // TODO storing index into globals might be dangerous if we delete a global |
| 160 | // while not having everything resolved. Actually, perhaps `unresolved` |
| 161 | // should not be stored at the global scope? Is this possible? |
| 162 | // Otherwise, audit if this can be a problem. |
| 163 | // An alternative, which I still need to investigate for perf reasons is to |
| 164 | // store all global names in an adapted with context strtab. |
| 165 | unresolved: std.AutoArrayHashMapUnmanaged(u32, bool) = .{}, |
| 163 | 166 | |
| 164 | 167 | locals_free_list: std.ArrayListUnmanaged(u32) = .{}, |
| 165 | | globals_free_list: std.ArrayListUnmanaged(u32) = .{}, |
| 166 | 168 | |
| 167 | 169 | dyld_stub_binder_index: ?u32 = null, |
| 168 | 170 | dyld_private_atom: ?*Atom = null, |
| 169 | 171 | stub_helper_preamble_atom: ?*Atom = null, |
| 170 | 172 | |
| 171 | | mh_execute_header_sym_index: ?u32 = null, |
| 172 | | dso_handle_sym_index: ?u32 = null, |
| 173 | | |
| 174 | | strtab: std.ArrayListUnmanaged(u8) = .{}, |
| 175 | | strtab_dir: std.HashMapUnmanaged(u32, void, StringIndexContext, std.hash_map.default_max_load_percentage) = .{}, |
| 173 | strtab: StringTable(.strtab) = .{}, |
| 176 | 174 | |
| 175 | // TODO I think synthetic tables are a perfect match for some generic refactoring, |
| 176 | // and probably reusable between linker backends too. |
| 177 | 177 | tlv_ptr_entries: std.ArrayListUnmanaged(Entry) = .{}, |
| 178 | 178 | tlv_ptr_entries_free_list: std.ArrayListUnmanaged(u32) = .{}, |
| 179 | | tlv_ptr_entries_table: std.AutoArrayHashMapUnmanaged(Atom.Relocation.Target, u32) = .{}, |
| 179 | tlv_ptr_entries_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, |
| 180 | 180 | |
| 181 | 181 | got_entries: std.ArrayListUnmanaged(Entry) = .{}, |
| 182 | 182 | got_entries_free_list: std.ArrayListUnmanaged(u32) = .{}, |
| 183 | | got_entries_table: std.AutoArrayHashMapUnmanaged(Atom.Relocation.Target, u32) = .{}, |
| 183 | got_entries_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, |
| 184 | 184 | |
| 185 | | stubs: std.ArrayListUnmanaged(*Atom) = .{}, |
| 185 | stubs: std.ArrayListUnmanaged(Entry) = .{}, |
| 186 | 186 | stubs_free_list: std.ArrayListUnmanaged(u32) = .{}, |
| 187 | | stubs_table: std.AutoArrayHashMapUnmanaged(u32, u32) = .{}, |
| 187 | stubs_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, |
| 188 | 188 | |
| 189 | 189 | error_flags: File.ErrorFlags = File.ErrorFlags{}, |
| 190 | 190 | |
| 191 | 191 | load_commands_dirty: bool = false, |
| 192 | 192 | sections_order_dirty: bool = false, |
| 193 | | has_dices: bool = false, |
| 194 | | has_stabs: bool = false, |
| 193 | |
| 195 | 194 | /// A helper var to indicate if we are at the start of the incremental updates, or |
| 196 | 195 | /// already somewhere further along the update-and-run chain. |
| 197 | 196 | /// TODO once we add opening a prelinked output binary from file, this will become |
| 198 | 197 | /// obsolete as we will carry on where we left off. |
| 199 | | cold_start: bool = false, |
| 200 | | invalidate_relocs: bool = false, |
| 198 | cold_start: bool = true, |
| 201 | 199 | |
| 202 | 200 | section_ordinals: std.AutoArrayHashMapUnmanaged(MatchingSection, void) = .{}, |
| 203 | 201 | |
| ... | ... | @@ -221,12 +219,10 @@ atom_free_lists: std.AutoHashMapUnmanaged(MatchingSection, std.ArrayListUnmanage |
| 221 | 219 | /// Pointer to the last allocated atom |
| 222 | 220 | atoms: std.AutoHashMapUnmanaged(MatchingSection, *Atom) = .{}, |
| 223 | 221 | |
| 224 | | /// List of atoms that are owned directly by the linker. |
| 225 | | /// Currently these are only atoms that are the result of linking |
| 226 | | /// object files. Atoms which take part in incremental linking are |
| 227 | | /// at present owned by Module.Decl. |
| 228 | | /// TODO consolidate this. |
| 222 | /// List of atoms that are either synthetic or map directly to the Zig source program. |
| 229 | 223 | managed_atoms: std.ArrayListUnmanaged(*Atom) = .{}, |
| 224 | |
| 225 | /// Table of atoms indexed by the symbol index. |
| 230 | 226 | atom_by_index_table: std.AutoHashMapUnmanaged(u32, *Atom) = .{}, |
| 231 | 227 | |
| 232 | 228 | /// Table of unnamed constants associated with a parent `Decl`. |
| ... | ... | @@ -257,8 +253,25 @@ unnamed_const_atoms: UnnamedConstTable = .{}, |
| 257 | 253 | decls: std.AutoArrayHashMapUnmanaged(Module.Decl.Index, ?MatchingSection) = .{}, |
| 258 | 254 | |
| 259 | 255 | const Entry = struct { |
| 260 | | target: Atom.Relocation.Target, |
| 261 | | atom: *Atom, |
| 256 | target: SymbolWithLoc, |
| 257 | // Index into the synthetic symbol table (i.e., file == null). |
| 258 | sym_index: u32, |
| 259 | |
| 260 | pub fn getSymbol(entry: Entry, macho_file: *MachO) macho.nlist_64 { |
| 261 | return macho_file.getSymbol(.{ .sym_index = entry.sym_index, .file = null }); |
| 262 | } |
| 263 | |
| 264 | pub fn getSymbolPtr(entry: Entry, macho_file: *MachO) *macho.nlist_64 { |
| 265 | return macho_file.getSymbolPtr(.{ .sym_index = entry.sym_index, .file = null }); |
| 266 | } |
| 267 | |
| 268 | pub fn getAtom(entry: Entry, macho_file: *MachO) *Atom { |
| 269 | return macho_file.getAtomForSymbol(.{ .sym_index = entry.sym_index, .file = null }).?; |
| 270 | } |
| 271 | |
| 272 | pub fn getName(entry: Entry, macho_file: *MachO) []const u8 { |
| 273 | return macho_file.getSymbolName(.{ .sym_index = entry.sym_index, .file = null }); |
| 274 | } |
| 262 | 275 | }; |
| 263 | 276 | |
| 264 | 277 | const UnnamedConstTable = std.AutoHashMapUnmanaged(Module.Decl.Index, std.ArrayListUnmanaged(*Atom)); |
| ... | ... | @@ -269,15 +282,12 @@ const PendingUpdate = union(enum) { |
| 269 | 282 | add_got_entry: u32, |
| 270 | 283 | }; |
| 271 | 284 | |
| 272 | | const SymbolWithLoc = struct { |
| 273 | | // Table where the symbol can be found. |
| 274 | | where: enum { |
| 275 | | global, |
| 276 | | undef, |
| 277 | | }, |
| 278 | | where_index: u32, |
| 279 | | local_sym_index: u32 = 0, |
| 280 | | file: ?u16 = null, // null means Zig module |
| 285 | pub const SymbolWithLoc = struct { |
| 286 | // Index into the respective symbol table. |
| 287 | sym_index: u32, |
| 288 | |
| 289 | // null means it's a synthetic global. |
| 290 | file: ?u32 = null, |
| 281 | 291 | }; |
| 282 | 292 | |
| 283 | 293 | /// When allocating, the ideal_capacity is calculated by |
| ... | ... | @@ -385,7 +395,7 @@ pub fn openPath(allocator: Allocator, options: link.Options) !*MachO { |
| 385 | 395 | .n_desc = 0, |
| 386 | 396 | .n_value = 0, |
| 387 | 397 | }); |
| 388 | | try self.strtab.append(allocator, 0); |
| 398 | try self.strtab.buffer.append(allocator, 0); |
| 389 | 399 | |
| 390 | 400 | try self.populateMissingMetadata(); |
| 391 | 401 | |
| ... | ... | @@ -406,7 +416,6 @@ pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO { |
| 406 | 416 | const requires_adhoc_codesig = cpu_arch == .aarch64 and (os_tag == .macos or abi == .simulator); |
| 407 | 417 | const use_llvm = build_options.have_llvm and options.use_llvm; |
| 408 | 418 | const use_stage1 = build_options.is_stage1 and options.use_stage1; |
| 409 | | const needs_prealloc = !(use_stage1 or use_llvm or options.cache_mode == .whole); |
| 410 | 419 | |
| 411 | 420 | const self = try gpa.create(MachO); |
| 412 | 421 | errdefer gpa.destroy(self); |
| ... | ... | @@ -419,14 +428,22 @@ pub fn createEmpty(gpa: Allocator, options: link.Options) !*MachO { |
| 419 | 428 | .file = null, |
| 420 | 429 | }, |
| 421 | 430 | .page_size = page_size, |
| 422 | | .code_signature = if (requires_adhoc_codesig) CodeSignature.init(page_size) else null, |
| 423 | | .needs_prealloc = needs_prealloc, |
| 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) |
| 436 | .one_shot |
| 437 | else |
| 438 | .incremental, |
| 424 | 439 | }; |
| 425 | 440 | |
| 426 | 441 | if (use_llvm and !use_stage1) { |
| 427 | 442 | self.llvm_object = try LlvmObject.create(gpa, options); |
| 428 | 443 | } |
| 429 | 444 | |
| 445 | log.debug("selected linker mode '{s}'", .{@tagName(self.mode)}); |
| 446 | |
| 430 | 447 | return self; |
| 431 | 448 | } |
| 432 | 449 | |
| ... | ... | @@ -448,33 +465,209 @@ pub fn flush(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) !v |
| 448 | 465 | return error.TODOImplementWritingStaticLibFiles; |
| 449 | 466 | } |
| 450 | 467 | } |
| 451 | | return self.flushModule(comp, prog_node); |
| 468 | |
| 469 | switch (self.mode) { |
| 470 | .one_shot => return self.linkOneShot(comp, prog_node), |
| 471 | .incremental => return self.flushModule(comp, prog_node), |
| 472 | } |
| 452 | 473 | } |
| 453 | 474 | |
| 454 | 475 | pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) !void { |
| 455 | 476 | const tracy = trace(@src()); |
| 456 | 477 | defer tracy.end(); |
| 457 | 478 | |
| 458 | | const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1; |
| 459 | | |
| 460 | | if (build_options.have_llvm and !use_stage1) { |
| 479 | if (build_options.have_llvm) { |
| 461 | 480 | if (self.llvm_object) |llvm_object| { |
| 462 | | try llvm_object.flushModule(comp, prog_node); |
| 463 | | |
| 464 | | llvm_object.destroy(self.base.allocator); |
| 465 | | self.llvm_object = null; |
| 466 | | |
| 467 | | if (self.base.options.output_mode == .Lib and self.base.options.link_mode == .Static) { |
| 468 | | return; |
| 469 | | } |
| 481 | return try llvm_object.flushModule(comp, prog_node); |
| 470 | 482 | } |
| 471 | 483 | } |
| 472 | 484 | |
| 485 | var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator); |
| 486 | defer arena_allocator.deinit(); |
| 487 | const arena = arena_allocator.allocator(); |
| 488 | |
| 473 | 489 | var sub_prog_node = prog_node.start("MachO Flush", 0); |
| 474 | 490 | sub_prog_node.activate(); |
| 475 | 491 | defer sub_prog_node.end(); |
| 476 | 492 | |
| 477 | | var arena_allocator = std.heap.ArenaAllocator.init(self.base.allocator); |
| 493 | const module = self.base.options.module orelse return error.LinkingWithoutZigSourceUnimplemented; |
| 494 | |
| 495 | if (self.d_sym) |*d_sym| { |
| 496 | try d_sym.dwarf.flushModule(&self.base, module); |
| 497 | } |
| 498 | |
| 499 | var libs = std.StringArrayHashMap(SystemLib).init(arena); |
| 500 | try self.resolveLibSystem(arena, comp, &.{}, &libs); |
| 501 | |
| 502 | const id_symlink_basename = "zld.id"; |
| 503 | |
| 504 | const cache_dir_handle = module.zig_cache_artifact_directory.handle; |
| 505 | var man: Cache.Manifest = undefined; |
| 506 | defer if (!self.base.options.disable_lld_caching) man.deinit(); |
| 507 | |
| 508 | var digest: [Cache.hex_digest_len]u8 = undefined; |
| 509 | man = comp.cache_parent.obtain(); |
| 510 | self.base.releaseLock(); |
| 511 | |
| 512 | man.hash.addListOfBytes(libs.keys()); |
| 513 | |
| 514 | _ = try man.hit(); |
| 515 | digest = man.final(); |
| 516 | |
| 517 | var prev_digest_buf: [digest.len]u8 = undefined; |
| 518 | const prev_digest: []u8 = Cache.readSmallFile( |
| 519 | cache_dir_handle, |
| 520 | id_symlink_basename, |
| 521 | &prev_digest_buf, |
| 522 | ) catch |err| blk: { |
| 523 | log.debug("MachO Zld new_digest={s} error: {s}", .{ |
| 524 | std.fmt.fmtSliceHexLower(&digest), |
| 525 | @errorName(err), |
| 526 | }); |
| 527 | // Handle this as a cache miss. |
| 528 | break :blk prev_digest_buf[0..0]; |
| 529 | }; |
| 530 | const cache_miss: bool = cache_miss: { |
| 531 | if (mem.eql(u8, prev_digest, &digest)) { |
| 532 | log.debug("MachO Zld digest={s} match", .{ |
| 533 | std.fmt.fmtSliceHexLower(&digest), |
| 534 | }); |
| 535 | if (!self.cold_start) { |
| 536 | log.debug(" skipping parsing linker line objects", .{}); |
| 537 | break :cache_miss false; |
| 538 | } else { |
| 539 | log.debug(" TODO parse prelinked binary and continue linking where we left off", .{}); |
| 540 | } |
| 541 | } |
| 542 | log.debug("MachO Zld prev_digest={s} new_digest={s}", .{ |
| 543 | std.fmt.fmtSliceHexLower(prev_digest), |
| 544 | std.fmt.fmtSliceHexLower(&digest), |
| 545 | }); |
| 546 | // We are about to change the output file to be different, so we invalidate the build hash now. |
| 547 | cache_dir_handle.deleteFile(id_symlink_basename) catch |err| switch (err) { |
| 548 | error.FileNotFound => {}, |
| 549 | else => |e| return e, |
| 550 | }; |
| 551 | break :cache_miss true; |
| 552 | }; |
| 553 | |
| 554 | if (cache_miss) { |
| 555 | for (self.dylibs.items) |*dylib| { |
| 556 | dylib.deinit(self.base.allocator); |
| 557 | } |
| 558 | self.dylibs.clearRetainingCapacity(); |
| 559 | self.dylibs_map.clearRetainingCapacity(); |
| 560 | self.referenced_dylibs.clearRetainingCapacity(); |
| 561 | |
| 562 | var dependent_libs = std.fifo.LinearFifo(struct { |
| 563 | id: Dylib.Id, |
| 564 | parent: u16, |
| 565 | }, .Dynamic).init(self.base.allocator); |
| 566 | defer dependent_libs.deinit(); |
| 567 | try self.parseLibs(libs.keys(), libs.values(), self.base.options.sysroot, &dependent_libs); |
| 568 | try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs); |
| 569 | } |
| 570 | |
| 571 | try self.createMhExecuteHeaderSymbol(); |
| 572 | try self.resolveDyldStubBinder(); |
| 573 | try self.createDyldPrivateAtom(); |
| 574 | try self.createStubHelperPreambleAtom(); |
| 575 | try self.resolveSymbolsInDylibs(); |
| 576 | try self.addCodeSignatureLC(); |
| 577 | |
| 578 | if (self.unresolved.count() > 0) { |
| 579 | return error.UndefinedSymbolReference; |
| 580 | } |
| 581 | |
| 582 | try self.allocateSpecialSymbols(); |
| 583 | |
| 584 | if (build_options.enable_logging) { |
| 585 | self.logSymtab(); |
| 586 | self.logSectionOrdinals(); |
| 587 | self.logAtoms(); |
| 588 | } |
| 589 | |
| 590 | try self.writeAtomsIncremental(); |
| 591 | |
| 592 | try self.setEntryPoint(); |
| 593 | try self.updateSectionOrdinals(); |
| 594 | try self.writeLinkeditSegment(); |
| 595 | |
| 596 | if (self.d_sym) |*d_sym| { |
| 597 | // Flush debug symbols bundle. |
| 598 | try d_sym.flushModule(self.base.allocator, self.base.options); |
| 599 | } |
| 600 | |
| 601 | // code signature and entitlements |
| 602 | if (self.base.options.entitlements) |path| { |
| 603 | if (self.code_signature) |*csig| { |
| 604 | try csig.addEntitlements(self.base.allocator, path); |
| 605 | csig.code_directory.ident = self.base.options.emit.?.sub_path; |
| 606 | } else { |
| 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 | } |
| 613 | |
| 614 | if (self.code_signature) |*csig| { |
| 615 | csig.clear(self.base.allocator); |
| 616 | csig.code_directory.ident = self.base.options.emit.?.sub_path; |
| 617 | // 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 |
| 619 | // written out to the file. |
| 620 | // The most important here is to have the correct vm and filesize of the __LINKEDIT segment |
| 621 | // where the code signature goes into. |
| 622 | try self.writeCodeSignaturePadding(csig); |
| 623 | } |
| 624 | |
| 625 | try self.writeLoadCommands(); |
| 626 | try self.writeHeader(); |
| 627 | |
| 628 | if (self.entry_addr == null and self.base.options.output_mode == .Exe) { |
| 629 | log.debug("flushing. no_entry_point_found = true", .{}); |
| 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 | |
| 636 | assert(!self.load_commands_dirty); |
| 637 | |
| 638 | if (self.code_signature) |*csig| { |
| 639 | try self.writeCodeSignature(csig); // code signing always comes last |
| 640 | } |
| 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) { |
| 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. |
| 650 | Cache.writeSmallFile(cache_dir_handle, id_symlink_basename, &digest) catch |err| { |
| 651 | log.debug("failed to save linking hash digest file: {s}", .{@errorName(err)}); |
| 652 | }; |
| 653 | // Again failure here only means an unnecessary cache miss. |
| 654 | man.writeManifest() catch |err| { |
| 655 | log.debug("failed to write cache manifest when linking: {s}", .{@errorName(err)}); |
| 656 | }; |
| 657 | // We hang on to this lock so that the output file path can be used without |
| 658 | // other processes clobbering it. |
| 659 | self.base.lock = man.toOwnedLock(); |
| 660 | } |
| 661 | |
| 662 | self.cold_start = false; |
| 663 | } |
| 664 | |
| 665 | fn linkOneShot(self: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) !void { |
| 666 | const tracy = trace(@src()); |
| 667 | defer tracy.end(); |
| 668 | |
| 669 | const gpa = self.base.allocator; |
| 670 | var arena_allocator = std.heap.ArenaAllocator.init(gpa); |
| 478 | 671 | defer arena_allocator.deinit(); |
| 479 | 672 | const arena = arena_allocator.allocator(); |
| 480 | 673 | |
| ... | ... | @@ -484,7 +677,7 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 484 | 677 | // If there is no Zig code to compile, then we should skip flushing the output file because it |
| 485 | 678 | // will not be part of the linker line anyway. |
| 486 | 679 | const module_obj_path: ?[]const u8 = if (self.base.options.module) |module| blk: { |
| 487 | | if (use_stage1) { |
| 680 | if (self.base.options.use_stage1) { |
| 488 | 681 | const obj_basename = try std.zig.binNameAlloc(arena, .{ |
| 489 | 682 | .root_name = self.base.options.root_name, |
| 490 | 683 | .target = self.base.options.target, |
| ... | ... | @@ -501,48 +694,35 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 501 | 694 | } |
| 502 | 695 | } |
| 503 | 696 | |
| 504 | | const obj_basename = self.base.intermediary_basename orelse break :blk null; |
| 697 | try self.flushModule(comp, prog_node); |
| 505 | 698 | |
| 506 | 699 | if (fs.path.dirname(full_out_path)) |dirname| { |
| 507 | | break :blk try fs.path.join(arena, &.{ dirname, obj_basename }); |
| 700 | break :blk try fs.path.join(arena, &.{ dirname, self.base.intermediary_basename.? }); |
| 508 | 701 | } else { |
| 509 | | break :blk obj_basename; |
| 702 | break :blk self.base.intermediary_basename.?; |
| 510 | 703 | } |
| 511 | 704 | } else null; |
| 512 | 705 | |
| 513 | | if (self.d_sym) |*d_sym| { |
| 514 | | if (self.base.options.module) |module| { |
| 515 | | try d_sym.dwarf.flushModule(&self.base, module); |
| 516 | | } |
| 517 | | } |
| 706 | var sub_prog_node = prog_node.start("MachO Flush", 0); |
| 707 | sub_prog_node.activate(); |
| 708 | sub_prog_node.context.refresh(); |
| 709 | defer sub_prog_node.end(); |
| 518 | 710 | |
| 519 | 711 | const is_lib = self.base.options.output_mode == .Lib; |
| 520 | 712 | const is_dyn_lib = self.base.options.link_mode == .Dynamic and is_lib; |
| 521 | 713 | const is_exe_or_dyn_lib = is_dyn_lib or self.base.options.output_mode == .Exe; |
| 522 | 714 | const stack_size = self.base.options.stack_size_override orelse 0; |
| 523 | | const allow_undef = is_dyn_lib and (self.base.options.allow_shlib_undefined orelse false); |
| 715 | const is_debug_build = self.base.options.optimize_mode == .Debug; |
| 716 | const gc_sections = self.base.options.gc_sections orelse !is_debug_build; |
| 524 | 717 | |
| 525 | 718 | const id_symlink_basename = "zld.id"; |
| 526 | | const cache_dir_handle = blk: { |
| 527 | | if (use_stage1) { |
| 528 | | break :blk directory.handle; |
| 529 | | } |
| 530 | | if (self.base.options.module) |module| { |
| 531 | | break :blk module.zig_cache_artifact_directory.handle; |
| 532 | | } |
| 533 | | break :blk directory.handle; |
| 534 | | }; |
| 535 | 719 | |
| 536 | 720 | var man: Cache.Manifest = undefined; |
| 537 | 721 | defer if (!self.base.options.disable_lld_caching) man.deinit(); |
| 538 | 722 | |
| 539 | 723 | var digest: [Cache.hex_digest_len]u8 = undefined; |
| 540 | | var needs_full_relink = true; |
| 541 | | |
| 542 | | cache: { |
| 543 | | if ((use_stage1 and self.base.options.disable_lld_caching) or self.base.options.cache_mode == .whole) |
| 544 | | break :cache; |
| 545 | 724 | |
| 725 | if (!self.base.options.disable_lld_caching) { |
| 546 | 726 | man = comp.cache_parent.obtain(); |
| 547 | 727 | |
| 548 | 728 | // We are about to obtain this lock, so here we give other processes a chance first. |
| ... | ... | @@ -565,7 +745,9 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 565 | 745 | man.hash.addOptional(self.base.options.search_strategy); |
| 566 | 746 | man.hash.addOptional(self.base.options.headerpad_size); |
| 567 | 747 | man.hash.add(self.base.options.headerpad_max_install_names); |
| 748 | man.hash.add(gc_sections); |
| 568 | 749 | man.hash.add(self.base.options.dead_strip_dylibs); |
| 750 | man.hash.add(self.base.options.strip); |
| 569 | 751 | man.hash.addListOfBytes(self.base.options.lib_dirs); |
| 570 | 752 | man.hash.addListOfBytes(self.base.options.framework_dirs); |
| 571 | 753 | link.hashAddSystemLibs(&man.hash, self.base.options.frameworks); |
| ... | ... | @@ -584,7 +766,7 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 584 | 766 | |
| 585 | 767 | var prev_digest_buf: [digest.len]u8 = undefined; |
| 586 | 768 | const prev_digest: []u8 = Cache.readSmallFile( |
| 587 | | cache_dir_handle, |
| 769 | directory.handle, |
| 588 | 770 | id_symlink_basename, |
| 589 | 771 | &prev_digest_buf, |
| 590 | 772 | ) catch |err| blk: { |
| ... | ... | @@ -597,23 +779,11 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 597 | 779 | }; |
| 598 | 780 | if (mem.eql(u8, prev_digest, &digest)) { |
| 599 | 781 | // Hot diggity dog! The output binary is already there. |
| 600 | | |
| 601 | | const use_llvm = build_options.have_llvm and self.base.options.use_llvm; |
| 602 | | if (use_llvm or use_stage1) { |
| 603 | | log.debug("MachO Zld digest={s} match - skipping invocation", .{std.fmt.fmtSliceHexLower(&digest)}); |
| 604 | | self.base.lock = man.toOwnedLock(); |
| 605 | | return; |
| 606 | | } else { |
| 607 | | log.debug("MachO Zld digest={s} match", .{std.fmt.fmtSliceHexLower(&digest)}); |
| 608 | | if (!self.cold_start) { |
| 609 | | log.debug(" no need to relink objects", .{}); |
| 610 | | needs_full_relink = false; |
| 611 | | } else { |
| 612 | | log.debug(" TODO parse prelinked binary and continue linking where we left off", .{}); |
| 613 | | // TODO until such time however, perform a full relink of objects. |
| 614 | | needs_full_relink = true; |
| 615 | | } |
| 616 | | } |
| 782 | log.debug("MachO Zld digest={s} match - skipping invocation", .{ |
| 783 | std.fmt.fmtSliceHexLower(&digest), |
| 784 | }); |
| 785 | self.base.lock = man.toOwnedLock(); |
| 786 | return; |
| 617 | 787 | } |
| 618 | 788 | log.debug("MachO Zld prev_digest={s} new_digest={s}", .{ |
| 619 | 789 | std.fmt.fmtSliceHexLower(prev_digest), |
| ... | ... | @@ -621,7 +791,7 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 621 | 791 | }); |
| 622 | 792 | |
| 623 | 793 | // We are about to change the output file to be different, so we invalidate the build hash now. |
| 624 | | cache_dir_handle.deleteFile(id_symlink_basename) catch |err| switch (err) { |
| 794 | directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) { |
| 625 | 795 | error.FileNotFound => {}, |
| 626 | 796 | else => |e| return e, |
| 627 | 797 | }; |
| ... | ... | @@ -652,450 +822,350 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 652 | 822 | try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{}); |
| 653 | 823 | } |
| 654 | 824 | } else { |
| 655 | | if (use_stage1) { |
| 656 | | const sub_path = self.base.options.emit.?.sub_path; |
| 657 | | self.base.file = try cache_dir_handle.createFile(sub_path, .{ |
| 658 | | .truncate = true, |
| 659 | | .read = true, |
| 660 | | .mode = link.determineMode(self.base.options), |
| 661 | | }); |
| 662 | | // Index 0 is always a null symbol. |
| 663 | | try self.locals.append(self.base.allocator, .{ |
| 664 | | .n_strx = 0, |
| 665 | | .n_type = 0, |
| 666 | | .n_sect = 0, |
| 667 | | .n_desc = 0, |
| 668 | | .n_value = 0, |
| 669 | | }); |
| 670 | | try self.strtab.append(self.base.allocator, 0); |
| 671 | | try self.populateMissingMetadata(); |
| 672 | | } |
| 825 | const sub_path = self.base.options.emit.?.sub_path; |
| 826 | self.base.file = try directory.handle.createFile(sub_path, .{ |
| 827 | .truncate = true, |
| 828 | .read = true, |
| 829 | .mode = link.determineMode(self.base.options), |
| 830 | }); |
| 831 | // Index 0 is always a null symbol. |
| 832 | try self.locals.append(gpa, .{ |
| 833 | .n_strx = 0, |
| 834 | .n_type = 0, |
| 835 | .n_sect = 0, |
| 836 | .n_desc = 0, |
| 837 | .n_value = 0, |
| 838 | }); |
| 839 | try self.strtab.buffer.append(gpa, 0); |
| 840 | try self.populateMissingMetadata(); |
| 673 | 841 | |
| 674 | 842 | var lib_not_found = false; |
| 675 | 843 | var framework_not_found = false; |
| 676 | 844 | |
| 677 | | if (needs_full_relink) { |
| 678 | | for (self.objects.items) |*object| { |
| 679 | | object.free(self.base.allocator, self); |
| 680 | | object.deinit(self.base.allocator); |
| 681 | | } |
| 682 | | self.objects.clearRetainingCapacity(); |
| 683 | | |
| 684 | | for (self.archives.items) |*archive| { |
| 685 | | archive.deinit(self.base.allocator); |
| 686 | | } |
| 687 | | self.archives.clearRetainingCapacity(); |
| 845 | // Positional arguments to the linker such as object files and static archives. |
| 846 | var positionals = std.ArrayList([]const u8).init(arena); |
| 847 | try positionals.ensureUnusedCapacity(self.base.options.objects.len); |
| 688 | 848 | |
| 689 | | for (self.dylibs.items) |*dylib| { |
| 690 | | dylib.deinit(self.base.allocator); |
| 691 | | } |
| 692 | | self.dylibs.clearRetainingCapacity(); |
| 693 | | self.dylibs_map.clearRetainingCapacity(); |
| 694 | | self.referenced_dylibs.clearRetainingCapacity(); |
| 695 | | |
| 696 | | { |
| 697 | | var to_remove = std.ArrayList(u32).init(self.base.allocator); |
| 698 | | defer to_remove.deinit(); |
| 699 | | var it = self.symbol_resolver.iterator(); |
| 700 | | while (it.next()) |entry| { |
| 701 | | const key = entry.key_ptr.*; |
| 702 | | const value = entry.value_ptr.*; |
| 703 | | if (value.file != null) { |
| 704 | | try to_remove.append(key); |
| 705 | | } |
| 706 | | } |
| 849 | var must_link_archives = std.StringArrayHashMap(void).init(arena); |
| 850 | try must_link_archives.ensureUnusedCapacity(self.base.options.objects.len); |
| 707 | 851 | |
| 708 | | for (to_remove.items) |key| { |
| 709 | | if (self.symbol_resolver.fetchRemove(key)) |entry| { |
| 710 | | const resolv = entry.value; |
| 711 | | switch (resolv.where) { |
| 712 | | .global => { |
| 713 | | self.globals_free_list.append(self.base.allocator, resolv.where_index) catch {}; |
| 714 | | const sym = &self.globals.items[resolv.where_index]; |
| 715 | | sym.n_strx = 0; |
| 716 | | sym.n_type = 0; |
| 717 | | sym.n_value = 0; |
| 718 | | }, |
| 719 | | .undef => { |
| 720 | | const sym = &self.undefs.items[resolv.where_index]; |
| 721 | | sym.n_strx = 0; |
| 722 | | sym.n_desc = 0; |
| 723 | | }, |
| 724 | | } |
| 725 | | if (self.got_entries_table.get(.{ .global = entry.key })) |i| { |
| 726 | | self.got_entries_free_list.append(self.base.allocator, @intCast(u32, i)) catch {}; |
| 727 | | self.got_entries.items[i] = .{ .target = .{ .local = 0 }, .atom = undefined }; |
| 728 | | _ = self.got_entries_table.swapRemove(.{ .global = entry.key }); |
| 729 | | } |
| 730 | | if (self.stubs_table.get(entry.key)) |i| { |
| 731 | | self.stubs_free_list.append(self.base.allocator, @intCast(u32, i)) catch {}; |
| 732 | | self.stubs.items[i] = undefined; |
| 733 | | _ = self.stubs_table.swapRemove(entry.key); |
| 734 | | } |
| 735 | | } |
| 736 | | } |
| 852 | for (self.base.options.objects) |obj| { |
| 853 | if (must_link_archives.contains(obj.path)) continue; |
| 854 | if (obj.must_link) { |
| 855 | _ = must_link_archives.getOrPutAssumeCapacity(obj.path); |
| 856 | } else { |
| 857 | _ = positionals.appendAssumeCapacity(obj.path); |
| 737 | 858 | } |
| 738 | | // Invalidate all relocs |
| 739 | | // TODO we only need to invalidate the backlinks to the relinked atoms from |
| 740 | | // the relocatable object files. |
| 741 | | self.invalidate_relocs = true; |
| 742 | | |
| 743 | | // Positional arguments to the linker such as object files and static archives. |
| 744 | | var positionals = std.ArrayList([]const u8).init(arena); |
| 745 | | try positionals.ensureUnusedCapacity(self.base.options.objects.len); |
| 859 | } |
| 746 | 860 | |
| 747 | | var must_link_archives = std.StringArrayHashMap(void).init(arena); |
| 748 | | try must_link_archives.ensureUnusedCapacity(self.base.options.objects.len); |
| 861 | for (comp.c_object_table.keys()) |key| { |
| 862 | try positionals.append(key.status.success.object_path); |
| 863 | } |
| 749 | 864 | |
| 750 | | for (self.base.options.objects) |obj| { |
| 751 | | if (must_link_archives.contains(obj.path)) continue; |
| 752 | | if (obj.must_link) { |
| 753 | | _ = must_link_archives.getOrPutAssumeCapacity(obj.path); |
| 754 | | } else { |
| 755 | | _ = positionals.appendAssumeCapacity(obj.path); |
| 756 | | } |
| 757 | | } |
| 865 | if (module_obj_path) |p| { |
| 866 | try positionals.append(p); |
| 867 | } |
| 758 | 868 | |
| 759 | | for (comp.c_object_table.keys()) |key| { |
| 760 | | try positionals.append(key.status.success.object_path); |
| 761 | | } |
| 869 | if (comp.compiler_rt_lib) |lib| { |
| 870 | try positionals.append(lib.full_object_path); |
| 871 | } |
| 762 | 872 | |
| 763 | | if (module_obj_path) |p| { |
| 764 | | try positionals.append(p); |
| 765 | | } |
| 873 | // libc++ dep |
| 874 | if (self.base.options.link_libcpp) { |
| 875 | try positionals.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 876 | try positionals.append(comp.libcxx_static_lib.?.full_object_path); |
| 877 | } |
| 766 | 878 | |
| 767 | | if (comp.compiler_rt_lib) |lib| { |
| 768 | | try positionals.append(lib.full_object_path); |
| 769 | | } |
| 879 | // Shared and static libraries passed via `-l` flag. |
| 880 | var candidate_libs = std.StringArrayHashMap(SystemLib).init(arena); |
| 770 | 881 | |
| 771 | | // libc++ dep |
| 772 | | if (self.base.options.link_libcpp) { |
| 773 | | try positionals.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 774 | | try positionals.append(comp.libcxx_static_lib.?.full_object_path); |
| 882 | const system_lib_names = self.base.options.system_libs.keys(); |
| 883 | for (system_lib_names) |system_lib_name| { |
| 884 | // By this time, we depend on these libs being dynamically linked libraries and not static libraries |
| 885 | // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which |
| 886 | // case we want to avoid prepending "-l". |
| 887 | if (Compilation.classifyFileExt(system_lib_name) == .shared_library) { |
| 888 | try positionals.append(system_lib_name); |
| 889 | continue; |
| 775 | 890 | } |
| 776 | 891 | |
| 777 | | // Shared and static libraries passed via `-l` flag. |
| 778 | | var candidate_libs = std.StringArrayHashMap(SystemLib).init(arena); |
| 779 | | |
| 780 | | const system_lib_names = self.base.options.system_libs.keys(); |
| 781 | | for (system_lib_names) |system_lib_name| { |
| 782 | | // By this time, we depend on these libs being dynamically linked libraries and not static libraries |
| 783 | | // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which |
| 784 | | // case we want to avoid prepending "-l". |
| 785 | | if (Compilation.classifyFileExt(system_lib_name) == .shared_library) { |
| 786 | | try positionals.append(system_lib_name); |
| 787 | | continue; |
| 788 | | } |
| 789 | | |
| 790 | | const system_lib_info = self.base.options.system_libs.get(system_lib_name).?; |
| 791 | | try candidate_libs.put(system_lib_name, .{ |
| 792 | | .needed = system_lib_info.needed, |
| 793 | | .weak = system_lib_info.weak, |
| 794 | | }); |
| 795 | | } |
| 892 | const system_lib_info = self.base.options.system_libs.get(system_lib_name).?; |
| 893 | try candidate_libs.put(system_lib_name, .{ |
| 894 | .needed = system_lib_info.needed, |
| 895 | .weak = system_lib_info.weak, |
| 896 | }); |
| 897 | } |
| 796 | 898 | |
| 797 | | var lib_dirs = std.ArrayList([]const u8).init(arena); |
| 798 | | for (self.base.options.lib_dirs) |dir| { |
| 799 | | if (try resolveSearchDir(arena, dir, self.base.options.sysroot)) |search_dir| { |
| 800 | | try lib_dirs.append(search_dir); |
| 801 | | } else { |
| 802 | | log.warn("directory not found for '-L{s}'", .{dir}); |
| 803 | | } |
| 899 | var lib_dirs = std.ArrayList([]const u8).init(arena); |
| 900 | for (self.base.options.lib_dirs) |dir| { |
| 901 | if (try resolveSearchDir(arena, dir, self.base.options.sysroot)) |search_dir| { |
| 902 | try lib_dirs.append(search_dir); |
| 903 | } else { |
| 904 | log.warn("directory not found for '-L{s}'", .{dir}); |
| 804 | 905 | } |
| 906 | } |
| 805 | 907 | |
| 806 | | var libs = std.StringArrayHashMap(SystemLib).init(arena); |
| 807 | | |
| 808 | | // Assume ld64 default -search_paths_first if no strategy specified. |
| 809 | | const search_strategy = self.base.options.search_strategy orelse .paths_first; |
| 810 | | outer: for (candidate_libs.keys()) |lib_name| { |
| 811 | | switch (search_strategy) { |
| 812 | | .paths_first => { |
| 813 | | // Look in each directory for a dylib (stub first), and then for archive |
| 814 | | for (lib_dirs.items) |dir| { |
| 815 | | for (&[_][]const u8{ ".tbd", ".dylib", ".a" }) |ext| { |
| 816 | | if (try resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 817 | | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 818 | | continue :outer; |
| 819 | | } |
| 908 | var libs = std.StringArrayHashMap(SystemLib).init(arena); |
| 909 | |
| 910 | // Assume ld64 default -search_paths_first if no strategy specified. |
| 911 | const search_strategy = self.base.options.search_strategy orelse .paths_first; |
| 912 | outer: for (candidate_libs.keys()) |lib_name| { |
| 913 | switch (search_strategy) { |
| 914 | .paths_first => { |
| 915 | // Look in each directory for a dylib (stub first), and then for archive |
| 916 | for (lib_dirs.items) |dir| { |
| 917 | for (&[_][]const u8{ ".tbd", ".dylib", ".a" }) |ext| { |
| 918 | if (try resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 919 | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 920 | continue :outer; |
| 820 | 921 | } |
| 821 | | } else { |
| 822 | | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 823 | | lib_not_found = true; |
| 824 | 922 | } |
| 825 | | }, |
| 826 | | .dylibs_first => { |
| 827 | | // First, look for a dylib in each search dir |
| 828 | | for (lib_dirs.items) |dir| { |
| 829 | | for (&[_][]const u8{ ".tbd", ".dylib" }) |ext| { |
| 830 | | if (try resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 831 | | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 832 | | continue :outer; |
| 833 | | } |
| 834 | | } |
| 835 | | } else for (lib_dirs.items) |dir| { |
| 836 | | if (try resolveLib(arena, dir, lib_name, ".a")) |full_path| { |
| 923 | } else { |
| 924 | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 925 | lib_not_found = true; |
| 926 | } |
| 927 | }, |
| 928 | .dylibs_first => { |
| 929 | // First, look for a dylib in each search dir |
| 930 | for (lib_dirs.items) |dir| { |
| 931 | for (&[_][]const u8{ ".tbd", ".dylib" }) |ext| { |
| 932 | if (try resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 837 | 933 | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 838 | | } else { |
| 839 | | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 840 | | lib_not_found = true; |
| 934 | continue :outer; |
| 841 | 935 | } |
| 842 | 936 | } |
| 843 | | }, |
| 844 | | } |
| 845 | | } |
| 846 | | |
| 847 | | if (lib_not_found) { |
| 848 | | log.warn("Library search paths:", .{}); |
| 849 | | for (lib_dirs.items) |dir| { |
| 850 | | log.warn(" {s}", .{dir}); |
| 851 | | } |
| 852 | | } |
| 853 | | |
| 854 | | // If we were given the sysroot, try to look there first for libSystem.B.{dylib, tbd}. |
| 855 | | var libsystem_available = false; |
| 856 | | if (self.base.options.sysroot != null) blk: { |
| 857 | | // Try stub file first. If we hit it, then we're done as the stub file |
| 858 | | // re-exports every single symbol definition. |
| 859 | | for (lib_dirs.items) |dir| { |
| 860 | | if (try resolveLib(arena, dir, "System", ".tbd")) |full_path| { |
| 861 | | try libs.put(full_path, .{ .needed = true }); |
| 862 | | libsystem_available = true; |
| 863 | | break :blk; |
| 864 | | } |
| 865 | | } |
| 866 | | // If we didn't hit the stub file, try .dylib next. However, libSystem.dylib |
| 867 | | // doesn't export libc.dylib which we'll need to resolve subsequently also. |
| 868 | | for (lib_dirs.items) |dir| { |
| 869 | | if (try resolveLib(arena, dir, "System", ".dylib")) |libsystem_path| { |
| 870 | | if (try resolveLib(arena, dir, "c", ".dylib")) |libc_path| { |
| 871 | | try libs.put(libsystem_path, .{ .needed = true }); |
| 872 | | try libs.put(libc_path, .{ .needed = true }); |
| 873 | | libsystem_available = true; |
| 874 | | break :blk; |
| 937 | } else for (lib_dirs.items) |dir| { |
| 938 | if (try resolveLib(arena, dir, lib_name, ".a")) |full_path| { |
| 939 | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 940 | } else { |
| 941 | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 942 | lib_not_found = true; |
| 875 | 943 | } |
| 876 | 944 | } |
| 877 | | } |
| 945 | }, |
| 878 | 946 | } |
| 879 | | if (!libsystem_available) { |
| 880 | | const libsystem_name = try std.fmt.allocPrint(arena, "libSystem.{d}.tbd", .{ |
| 881 | | self.base.options.target.os.version_range.semver.min.major, |
| 882 | | }); |
| 883 | | const full_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ |
| 884 | | "libc", "darwin", libsystem_name, |
| 885 | | }); |
| 886 | | try libs.put(full_path, .{ .needed = true }); |
| 947 | } |
| 948 | |
| 949 | if (lib_not_found) { |
| 950 | log.warn("Library search paths:", .{}); |
| 951 | for (lib_dirs.items) |dir| { |
| 952 | log.warn(" {s}", .{dir}); |
| 887 | 953 | } |
| 954 | } |
| 888 | 955 | |
| 889 | | // frameworks |
| 890 | | var framework_dirs = std.ArrayList([]const u8).init(arena); |
| 891 | | for (self.base.options.framework_dirs) |dir| { |
| 892 | | if (try resolveSearchDir(arena, dir, self.base.options.sysroot)) |search_dir| { |
| 893 | | try framework_dirs.append(search_dir); |
| 894 | | } else { |
| 895 | | log.warn("directory not found for '-F{s}'", .{dir}); |
| 896 | | } |
| 956 | try self.resolveLibSystem(arena, comp, lib_dirs.items, &libs); |
| 957 | |
| 958 | // frameworks |
| 959 | var framework_dirs = std.ArrayList([]const u8).init(arena); |
| 960 | for (self.base.options.framework_dirs) |dir| { |
| 961 | if (try resolveSearchDir(arena, dir, self.base.options.sysroot)) |search_dir| { |
| 962 | try framework_dirs.append(search_dir); |
| 963 | } else { |
| 964 | log.warn("directory not found for '-F{s}'", .{dir}); |
| 897 | 965 | } |
| 966 | } |
| 898 | 967 | |
| 899 | | outer: for (self.base.options.frameworks.keys()) |f_name| { |
| 900 | | for (framework_dirs.items) |dir| { |
| 901 | | for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| { |
| 902 | | if (try resolveFramework(arena, dir, f_name, ext)) |full_path| { |
| 903 | | const info = self.base.options.frameworks.get(f_name).?; |
| 904 | | try libs.put(full_path, .{ |
| 905 | | .needed = info.needed, |
| 906 | | .weak = info.weak, |
| 907 | | }); |
| 908 | | continue :outer; |
| 909 | | } |
| 968 | outer: for (self.base.options.frameworks.keys()) |f_name| { |
| 969 | for (framework_dirs.items) |dir| { |
| 970 | for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| { |
| 971 | if (try resolveFramework(arena, dir, f_name, ext)) |full_path| { |
| 972 | const info = self.base.options.frameworks.get(f_name).?; |
| 973 | try libs.put(full_path, .{ |
| 974 | .needed = info.needed, |
| 975 | .weak = info.weak, |
| 976 | }); |
| 977 | continue :outer; |
| 910 | 978 | } |
| 911 | | } else { |
| 912 | | log.warn("framework not found for '-framework {s}'", .{f_name}); |
| 913 | | framework_not_found = true; |
| 914 | 979 | } |
| 980 | } else { |
| 981 | log.warn("framework not found for '-framework {s}'", .{f_name}); |
| 982 | framework_not_found = true; |
| 915 | 983 | } |
| 984 | } |
| 916 | 985 | |
| 917 | | if (framework_not_found) { |
| 918 | | log.warn("Framework search paths:", .{}); |
| 919 | | for (framework_dirs.items) |dir| { |
| 920 | | log.warn(" {s}", .{dir}); |
| 921 | | } |
| 986 | if (framework_not_found) { |
| 987 | log.warn("Framework search paths:", .{}); |
| 988 | for (framework_dirs.items) |dir| { |
| 989 | log.warn(" {s}", .{dir}); |
| 922 | 990 | } |
| 991 | } |
| 923 | 992 | |
| 924 | | // rpaths |
| 925 | | var rpath_table = std.StringArrayHashMap(void).init(arena); |
| 926 | | for (self.base.options.rpath_list) |rpath| { |
| 927 | | if (rpath_table.contains(rpath)) continue; |
| 928 | | const cmdsize = @intCast(u32, mem.alignForwardGeneric( |
| 929 | | u64, |
| 930 | | @sizeOf(macho.rpath_command) + rpath.len + 1, |
| 931 | | @sizeOf(u64), |
| 932 | | )); |
| 933 | | var rpath_cmd = macho.emptyGenericCommandWithData(macho.rpath_command{ |
| 934 | | .cmdsize = cmdsize, |
| 935 | | .path = @sizeOf(macho.rpath_command), |
| 936 | | }); |
| 937 | | rpath_cmd.data = try self.base.allocator.alloc(u8, cmdsize - rpath_cmd.inner.path); |
| 938 | | mem.set(u8, rpath_cmd.data, 0); |
| 939 | | mem.copy(u8, rpath_cmd.data, rpath); |
| 940 | | try self.load_commands.append(self.base.allocator, .{ .rpath = rpath_cmd }); |
| 941 | | try rpath_table.putNoClobber(rpath, {}); |
| 942 | | self.load_commands_dirty = true; |
| 943 | | } |
| 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 | } |
| 944 | 1013 | |
| 945 | | // code signature and entitlements |
| 946 | | if (self.base.options.entitlements) |path| { |
| 947 | | if (self.code_signature) |*csig| { |
| 948 | | try csig.addEntitlements(self.base.allocator, path); |
| 949 | | csig.code_directory.ident = self.base.options.emit.?.sub_path; |
| 950 | | } else { |
| 951 | | var csig = CodeSignature.init(self.page_size); |
| 952 | | try csig.addEntitlements(self.base.allocator, path); |
| 953 | | csig.code_directory.ident = self.base.options.emit.?.sub_path; |
| 954 | | self.code_signature = csig; |
| 955 | | } |
| 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; |
| 956 | 1024 | } |
| 1025 | } |
| 957 | 1026 | |
| 958 | | if (self.base.options.verbose_link) { |
| 959 | | var argv = std.ArrayList([]const u8).init(arena); |
| 960 | | |
| 961 | | try argv.append("zig"); |
| 962 | | try argv.append("ld"); |
| 963 | | |
| 964 | | if (is_exe_or_dyn_lib) { |
| 965 | | try argv.append("-dynamic"); |
| 966 | | } |
| 1027 | if (self.base.options.verbose_link) { |
| 1028 | var argv = std.ArrayList([]const u8).init(arena); |
| 967 | 1029 | |
| 968 | | if (is_dyn_lib) { |
| 969 | | try argv.append("-dylib"); |
| 1030 | try argv.append("zig"); |
| 1031 | try argv.append("ld"); |
| 970 | 1032 | |
| 971 | | if (self.base.options.install_name) |install_name| { |
| 972 | | try argv.append("-install_name"); |
| 973 | | try argv.append(install_name); |
| 974 | | } |
| 975 | | } |
| 1033 | if (is_exe_or_dyn_lib) { |
| 1034 | try argv.append("-dynamic"); |
| 1035 | } |
| 976 | 1036 | |
| 977 | | if (self.base.options.sysroot) |syslibroot| { |
| 978 | | try argv.append("-syslibroot"); |
| 979 | | try argv.append(syslibroot); |
| 980 | | } |
| 1037 | if (is_dyn_lib) { |
| 1038 | try argv.append("-dylib"); |
| 981 | 1039 | |
| 982 | | for (rpath_table.keys()) |rpath| { |
| 983 | | try argv.append("-rpath"); |
| 984 | | try argv.append(rpath); |
| 1040 | if (self.base.options.install_name) |install_name| { |
| 1041 | try argv.append("-install_name"); |
| 1042 | try argv.append(install_name); |
| 985 | 1043 | } |
| 1044 | } |
| 986 | 1045 | |
| 987 | | if (self.base.options.pagezero_size) |pagezero_size| { |
| 988 | | try argv.append("-pagezero_size"); |
| 989 | | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{pagezero_size})); |
| 990 | | } |
| 1046 | if (self.base.options.sysroot) |syslibroot| { |
| 1047 | try argv.append("-syslibroot"); |
| 1048 | try argv.append(syslibroot); |
| 1049 | } |
| 991 | 1050 | |
| 992 | | if (self.base.options.search_strategy) |strat| switch (strat) { |
| 993 | | .paths_first => try argv.append("-search_paths_first"), |
| 994 | | .dylibs_first => try argv.append("-search_dylibs_first"), |
| 995 | | }; |
| 1051 | for (rpath_table.keys()) |rpath| { |
| 1052 | try argv.append("-rpath"); |
| 1053 | try argv.append(rpath); |
| 1054 | } |
| 996 | 1055 | |
| 997 | | if (self.base.options.headerpad_size) |headerpad_size| { |
| 998 | | try argv.append("-headerpad_size"); |
| 999 | | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{headerpad_size})); |
| 1000 | | } |
| 1056 | if (self.base.options.pagezero_size) |pagezero_size| { |
| 1057 | try argv.append("-pagezero_size"); |
| 1058 | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{pagezero_size})); |
| 1059 | } |
| 1001 | 1060 | |
| 1002 | | if (self.base.options.headerpad_max_install_names) { |
| 1003 | | try argv.append("-headerpad_max_install_names"); |
| 1004 | | } |
| 1061 | if (self.base.options.search_strategy) |strat| switch (strat) { |
| 1062 | .paths_first => try argv.append("-search_paths_first"), |
| 1063 | .dylibs_first => try argv.append("-search_dylibs_first"), |
| 1064 | }; |
| 1005 | 1065 | |
| 1006 | | if (self.base.options.dead_strip_dylibs) { |
| 1007 | | try argv.append("-dead_strip_dylibs"); |
| 1008 | | } |
| 1066 | if (self.base.options.headerpad_size) |headerpad_size| { |
| 1067 | try argv.append("-headerpad_size"); |
| 1068 | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{headerpad_size})); |
| 1069 | } |
| 1009 | 1070 | |
| 1010 | | if (self.base.options.entry) |entry| { |
| 1011 | | try argv.append("-e"); |
| 1012 | | try argv.append(entry); |
| 1013 | | } |
| 1071 | if (self.base.options.headerpad_max_install_names) { |
| 1072 | try argv.append("-headerpad_max_install_names"); |
| 1073 | } |
| 1014 | 1074 | |
| 1015 | | for (self.base.options.objects) |obj| { |
| 1016 | | try argv.append(obj.path); |
| 1017 | | } |
| 1075 | if (gc_sections) { |
| 1076 | try argv.append("-dead_strip"); |
| 1077 | } |
| 1018 | 1078 | |
| 1019 | | for (comp.c_object_table.keys()) |key| { |
| 1020 | | try argv.append(key.status.success.object_path); |
| 1021 | | } |
| 1079 | if (self.base.options.dead_strip_dylibs) { |
| 1080 | try argv.append("-dead_strip_dylibs"); |
| 1081 | } |
| 1022 | 1082 | |
| 1023 | | if (module_obj_path) |p| { |
| 1024 | | try argv.append(p); |
| 1025 | | } |
| 1083 | if (self.base.options.entry) |entry| { |
| 1084 | try argv.append("-e"); |
| 1085 | try argv.append(entry); |
| 1086 | } |
| 1026 | 1087 | |
| 1027 | | if (comp.compiler_rt_lib) |lib| { |
| 1028 | | try argv.append(lib.full_object_path); |
| 1029 | | } |
| 1088 | for (self.base.options.objects) |obj| { |
| 1089 | try argv.append(obj.path); |
| 1090 | } |
| 1030 | 1091 | |
| 1031 | | if (self.base.options.link_libcpp) { |
| 1032 | | try argv.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 1033 | | try argv.append(comp.libcxx_static_lib.?.full_object_path); |
| 1034 | | } |
| 1092 | for (comp.c_object_table.keys()) |key| { |
| 1093 | try argv.append(key.status.success.object_path); |
| 1094 | } |
| 1035 | 1095 | |
| 1036 | | try argv.append("-o"); |
| 1037 | | try argv.append(full_out_path); |
| 1096 | if (module_obj_path) |p| { |
| 1097 | try argv.append(p); |
| 1098 | } |
| 1038 | 1099 | |
| 1039 | | try argv.append("-lSystem"); |
| 1040 | | try argv.append("-lc"); |
| 1100 | if (comp.compiler_rt_lib) |lib| { |
| 1101 | try argv.append(lib.full_object_path); |
| 1102 | } |
| 1041 | 1103 | |
| 1042 | | for (self.base.options.system_libs.keys()) |l_name| { |
| 1043 | | const info = self.base.options.system_libs.get(l_name).?; |
| 1044 | | const arg = if (info.needed) |
| 1045 | | try std.fmt.allocPrint(arena, "-needed-l{s}", .{l_name}) |
| 1046 | | else if (info.weak) |
| 1047 | | try std.fmt.allocPrint(arena, "-weak-l{s}", .{l_name}) |
| 1048 | | else |
| 1049 | | try std.fmt.allocPrint(arena, "-l{s}", .{l_name}); |
| 1050 | | try argv.append(arg); |
| 1051 | | } |
| 1104 | if (self.base.options.link_libcpp) { |
| 1105 | try argv.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 1106 | try argv.append(comp.libcxx_static_lib.?.full_object_path); |
| 1107 | } |
| 1052 | 1108 | |
| 1053 | | for (self.base.options.lib_dirs) |lib_dir| { |
| 1054 | | try argv.append(try std.fmt.allocPrint(arena, "-L{s}", .{lib_dir})); |
| 1055 | | } |
| 1109 | try argv.append("-o"); |
| 1110 | try argv.append(full_out_path); |
| 1111 | |
| 1112 | try argv.append("-lSystem"); |
| 1113 | try argv.append("-lc"); |
| 1114 | |
| 1115 | for (self.base.options.system_libs.keys()) |l_name| { |
| 1116 | const info = self.base.options.system_libs.get(l_name).?; |
| 1117 | const arg = if (info.needed) |
| 1118 | try std.fmt.allocPrint(arena, "-needed-l{s}", .{l_name}) |
| 1119 | else if (info.weak) |
| 1120 | try std.fmt.allocPrint(arena, "-weak-l{s}", .{l_name}) |
| 1121 | else |
| 1122 | try std.fmt.allocPrint(arena, "-l{s}", .{l_name}); |
| 1123 | try argv.append(arg); |
| 1124 | } |
| 1056 | 1125 | |
| 1057 | | for (self.base.options.frameworks.keys()) |framework| { |
| 1058 | | const info = self.base.options.frameworks.get(framework).?; |
| 1059 | | const arg = if (info.needed) |
| 1060 | | try std.fmt.allocPrint(arena, "-needed_framework {s}", .{framework}) |
| 1061 | | else if (info.weak) |
| 1062 | | try std.fmt.allocPrint(arena, "-weak_framework {s}", .{framework}) |
| 1063 | | else |
| 1064 | | try std.fmt.allocPrint(arena, "-framework {s}", .{framework}); |
| 1065 | | try argv.append(arg); |
| 1066 | | } |
| 1126 | for (self.base.options.lib_dirs) |lib_dir| { |
| 1127 | try argv.append(try std.fmt.allocPrint(arena, "-L{s}", .{lib_dir})); |
| 1128 | } |
| 1067 | 1129 | |
| 1068 | | for (self.base.options.framework_dirs) |framework_dir| { |
| 1069 | | try argv.append(try std.fmt.allocPrint(arena, "-F{s}", .{framework_dir})); |
| 1070 | | } |
| 1130 | for (self.base.options.frameworks.keys()) |framework| { |
| 1131 | const info = self.base.options.frameworks.get(framework).?; |
| 1132 | const arg = if (info.needed) |
| 1133 | try std.fmt.allocPrint(arena, "-needed_framework {s}", .{framework}) |
| 1134 | else if (info.weak) |
| 1135 | try std.fmt.allocPrint(arena, "-weak_framework {s}", .{framework}) |
| 1136 | else |
| 1137 | try std.fmt.allocPrint(arena, "-framework {s}", .{framework}); |
| 1138 | try argv.append(arg); |
| 1139 | } |
| 1071 | 1140 | |
| 1072 | | if (allow_undef) { |
| 1073 | | try argv.append("-undefined"); |
| 1074 | | try argv.append("dynamic_lookup"); |
| 1075 | | } |
| 1141 | for (self.base.options.framework_dirs) |framework_dir| { |
| 1142 | try argv.append(try std.fmt.allocPrint(arena, "-F{s}", .{framework_dir})); |
| 1143 | } |
| 1076 | 1144 | |
| 1077 | | for (must_link_archives.keys()) |lib| { |
| 1078 | | try argv.append(try std.fmt.allocPrint(arena, "-force_load {s}", .{lib})); |
| 1079 | | } |
| 1145 | if (is_dyn_lib and (self.base.options.allow_shlib_undefined orelse false)) { |
| 1146 | try argv.append("-undefined"); |
| 1147 | try argv.append("dynamic_lookup"); |
| 1148 | } |
| 1080 | 1149 | |
| 1081 | | Compilation.dump_argv(argv.items); |
| 1150 | for (must_link_archives.keys()) |lib| { |
| 1151 | try argv.append(try std.fmt.allocPrint(arena, "-force_load {s}", .{lib})); |
| 1082 | 1152 | } |
| 1083 | 1153 | |
| 1084 | | var dependent_libs = std.fifo.LinearFifo(struct { |
| 1085 | | id: Dylib.Id, |
| 1086 | | parent: u16, |
| 1087 | | }, .Dynamic).init(self.base.allocator); |
| 1088 | | defer dependent_libs.deinit(); |
| 1089 | | try self.parseInputFiles(positionals.items, self.base.options.sysroot, &dependent_libs); |
| 1090 | | try self.parseAndForceLoadStaticArchives(must_link_archives.keys()); |
| 1091 | | try self.parseLibs(libs.keys(), libs.values(), self.base.options.sysroot, &dependent_libs); |
| 1092 | | try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs); |
| 1154 | Compilation.dump_argv(argv.items); |
| 1093 | 1155 | } |
| 1094 | 1156 | |
| 1095 | | try self.createMhExecuteHeaderSymbol(); |
| 1157 | var dependent_libs = std.fifo.LinearFifo(struct { |
| 1158 | id: Dylib.Id, |
| 1159 | parent: u16, |
| 1160 | }, .Dynamic).init(gpa); |
| 1161 | defer dependent_libs.deinit(); |
| 1162 | try self.parseInputFiles(positionals.items, self.base.options.sysroot, &dependent_libs); |
| 1163 | try self.parseAndForceLoadStaticArchives(must_link_archives.keys()); |
| 1164 | try self.parseLibs(libs.keys(), libs.values(), self.base.options.sysroot, &dependent_libs); |
| 1165 | try self.parseDependentLibs(self.base.options.sysroot, &dependent_libs); |
| 1166 | |
| 1096 | 1167 | for (self.objects.items) |*object, object_id| { |
| 1097 | | if (object.analyzed) continue; |
| 1098 | | try self.resolveSymbolsInObject(@intCast(u16, object_id)); |
| 1168 | try self.resolveSymbolsInObject(object, @intCast(u16, object_id)); |
| 1099 | 1169 | } |
| 1100 | 1170 | |
| 1101 | 1171 | try self.resolveSymbolsInArchives(); |
| ... | ... | @@ -1103,46 +1173,11 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 1103 | 1173 | try self.createDyldPrivateAtom(); |
| 1104 | 1174 | try self.createStubHelperPreambleAtom(); |
| 1105 | 1175 | try self.resolveSymbolsInDylibs(); |
| 1176 | try self.createMhExecuteHeaderSymbol(); |
| 1106 | 1177 | try self.createDsoHandleSymbol(); |
| 1107 | 1178 | try self.addCodeSignatureLC(); |
| 1179 | try self.resolveSymbolsAtLoading(); |
| 1108 | 1180 | |
| 1109 | | { |
| 1110 | | var next_sym: usize = 0; |
| 1111 | | while (next_sym < self.unresolved.count()) { |
| 1112 | | const sym = &self.undefs.items[self.unresolved.keys()[next_sym]]; |
| 1113 | | const sym_name = self.getString(sym.n_strx); |
| 1114 | | const resolv = self.symbol_resolver.get(sym.n_strx) orelse unreachable; |
| 1115 | | |
| 1116 | | if (sym.discarded()) { |
| 1117 | | sym.* = .{ |
| 1118 | | .n_strx = 0, |
| 1119 | | .n_type = macho.N_UNDF, |
| 1120 | | .n_sect = 0, |
| 1121 | | .n_desc = 0, |
| 1122 | | .n_value = 0, |
| 1123 | | }; |
| 1124 | | _ = self.unresolved.swapRemove(resolv.where_index); |
| 1125 | | continue; |
| 1126 | | } else if (allow_undef) { |
| 1127 | | const n_desc = @bitCast( |
| 1128 | | u16, |
| 1129 | | macho.BIND_SPECIAL_DYLIB_FLAT_LOOKUP * @intCast(i16, macho.N_SYMBOL_RESOLVER), |
| 1130 | | ); |
| 1131 | | // TODO allow_shlib_undefined is an ELF flag so figure out macOS specific flags too. |
| 1132 | | sym.n_type = macho.N_EXT; |
| 1133 | | sym.n_desc = n_desc; |
| 1134 | | _ = self.unresolved.swapRemove(resolv.where_index); |
| 1135 | | continue; |
| 1136 | | } |
| 1137 | | |
| 1138 | | log.err("undefined reference to symbol '{s}'", .{sym_name}); |
| 1139 | | if (resolv.file) |file| { |
| 1140 | | log.err(" first referenced in '{s}'", .{self.objects.items[file].name}); |
| 1141 | | } |
| 1142 | | |
| 1143 | | next_sym += 1; |
| 1144 | | } |
| 1145 | | } |
| 1146 | 1181 | if (self.unresolved.count() > 0) { |
| 1147 | 1182 | return error.UndefinedSymbolReference; |
| 1148 | 1183 | } |
| ... | ... | @@ -1154,46 +1189,42 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 1154 | 1189 | } |
| 1155 | 1190 | |
| 1156 | 1191 | try self.createTentativeDefAtoms(); |
| 1157 | | try self.parseObjectsIntoAtoms(); |
| 1158 | 1192 | |
| 1159 | | const use_llvm = build_options.have_llvm and self.base.options.use_llvm; |
| 1160 | | if (use_llvm or use_stage1) { |
| 1161 | | try self.pruneAndSortSections(); |
| 1162 | | try self.allocateSegments(); |
| 1163 | | try self.allocateLocals(); |
| 1193 | for (self.objects.items) |*object, object_id| { |
| 1194 | try object.splitIntoAtomsOneShot(self, @intCast(u32, object_id)); |
| 1164 | 1195 | } |
| 1165 | 1196 | |
| 1197 | if (gc_sections) { |
| 1198 | try dead_strip.gcAtoms(self); |
| 1199 | } |
| 1200 | |
| 1201 | try self.pruneAndSortSections(); |
| 1202 | try self.allocateSegments(); |
| 1203 | try self.allocateSymbols(); |
| 1204 | |
| 1166 | 1205 | try self.allocateSpecialSymbols(); |
| 1167 | | try self.allocateGlobals(); |
| 1168 | 1206 | |
| 1169 | 1207 | if (build_options.enable_logging) { |
| 1170 | 1208 | self.logSymtab(); |
| 1171 | 1209 | self.logSectionOrdinals(); |
| 1210 | self.logAtoms(); |
| 1172 | 1211 | } |
| 1173 | 1212 | |
| 1174 | | if (use_llvm or use_stage1) { |
| 1175 | | try self.writeAllAtoms(); |
| 1176 | | } else { |
| 1177 | | try self.writeAtoms(); |
| 1178 | | } |
| 1213 | try self.writeAtomsOneShot(); |
| 1179 | 1214 | |
| 1180 | 1215 | if (self.rustc_section_index) |id| { |
| 1181 | | const seg = &self.load_commands.items[self.data_segment_cmd_index.?].segment; |
| 1182 | | const sect = &seg.sections.items[id]; |
| 1216 | const sect = self.getSectionPtr(.{ |
| 1217 | .seg = self.data_segment_cmd_index.?, |
| 1218 | .sect = id, |
| 1219 | }); |
| 1183 | 1220 | sect.size = self.rustc_section_size; |
| 1184 | 1221 | } |
| 1185 | 1222 | |
| 1186 | 1223 | try self.setEntryPoint(); |
| 1187 | | try self.updateSectionOrdinals(); |
| 1188 | 1224 | try self.writeLinkeditSegment(); |
| 1189 | 1225 | |
| 1190 | | if (self.d_sym) |*d_sym| { |
| 1191 | | // Flush debug symbols bundle. |
| 1192 | | try d_sym.flushModule(self.base.allocator, self.base.options); |
| 1193 | | } |
| 1194 | | |
| 1195 | 1226 | if (self.code_signature) |*csig| { |
| 1196 | | csig.clear(self.base.allocator); |
| 1227 | csig.clear(gpa); |
| 1197 | 1228 | csig.code_directory.ident = self.base.options.emit.?.sub_path; |
| 1198 | 1229 | // Preallocate space for the code signature. |
| 1199 | 1230 | // We need to do this at this stage so that we have the load commands with proper values |
| ... | ... | @@ -1206,32 +1237,17 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 1206 | 1237 | try self.writeLoadCommands(); |
| 1207 | 1238 | try self.writeHeader(); |
| 1208 | 1239 | |
| 1209 | | if (self.entry_addr == null and self.base.options.output_mode == .Exe) { |
| 1210 | | log.debug("flushing. no_entry_point_found = true", .{}); |
| 1211 | | self.error_flags.no_entry_point_found = true; |
| 1212 | | } else { |
| 1213 | | log.debug("flushing. no_entry_point_found = false", .{}); |
| 1214 | | self.error_flags.no_entry_point_found = false; |
| 1215 | | } |
| 1216 | | |
| 1217 | 1240 | assert(!self.load_commands_dirty); |
| 1218 | 1241 | |
| 1219 | 1242 | if (self.code_signature) |*csig| { |
| 1220 | 1243 | try self.writeCodeSignature(csig); // code signing always comes last |
| 1221 | 1244 | } |
| 1222 | | |
| 1223 | | if (build_options.enable_link_snapshots) { |
| 1224 | | if (self.base.options.enable_link_snapshots) |
| 1225 | | try self.snapshotState(); |
| 1226 | | } |
| 1227 | 1245 | } |
| 1228 | 1246 | |
| 1229 | | cache: { |
| 1230 | | if ((use_stage1 and self.base.options.disable_lld_caching) or self.base.options.cache_mode == .whole) |
| 1231 | | break :cache; |
| 1247 | if (!self.base.options.disable_lld_caching) { |
| 1232 | 1248 | // Update the file with the digest. If it fails we can continue; it only |
| 1233 | 1249 | // means that the next invocation will have an unnecessary cache miss. |
| 1234 | | Cache.writeSmallFile(cache_dir_handle, id_symlink_basename, &digest) catch |err| { |
| 1250 | Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { |
| 1235 | 1251 | log.debug("failed to save linking hash digest file: {s}", .{@errorName(err)}); |
| 1236 | 1252 | }; |
| 1237 | 1253 | // Again failure here only means an unnecessary cache miss. |
| ... | ... | @@ -1242,8 +1258,49 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No |
| 1242 | 1258 | // other processes clobbering it. |
| 1243 | 1259 | self.base.lock = man.toOwnedLock(); |
| 1244 | 1260 | } |
| 1261 | } |
| 1245 | 1262 | |
| 1246 | | self.cold_start = false; |
| 1263 | fn resolveLibSystem( |
| 1264 | self: *MachO, |
| 1265 | arena: Allocator, |
| 1266 | comp: *Compilation, |
| 1267 | search_dirs: []const []const u8, |
| 1268 | out_libs: anytype, |
| 1269 | ) !void { |
| 1270 | // If we were given the sysroot, try to look there first for libSystem.B.{dylib, tbd}. |
| 1271 | var libsystem_available = false; |
| 1272 | if (self.base.options.sysroot != null) blk: { |
| 1273 | // Try stub file first. If we hit it, then we're done as the stub file |
| 1274 | // re-exports every single symbol definition. |
| 1275 | for (search_dirs) |dir| { |
| 1276 | if (try resolveLib(arena, dir, "System", ".tbd")) |full_path| { |
| 1277 | try out_libs.put(full_path, .{ .needed = true }); |
| 1278 | libsystem_available = true; |
| 1279 | break :blk; |
| 1280 | } |
| 1281 | } |
| 1282 | // If we didn't hit the stub file, try .dylib next. However, libSystem.dylib |
| 1283 | // doesn't export libc.dylib which we'll need to resolve subsequently also. |
| 1284 | for (search_dirs) |dir| { |
| 1285 | if (try resolveLib(arena, dir, "System", ".dylib")) |libsystem_path| { |
| 1286 | if (try resolveLib(arena, dir, "c", ".dylib")) |libc_path| { |
| 1287 | try out_libs.put(libsystem_path, .{ .needed = true }); |
| 1288 | try out_libs.put(libc_path, .{ .needed = true }); |
| 1289 | libsystem_available = true; |
| 1290 | break :blk; |
| 1291 | } |
| 1292 | } |
| 1293 | } |
| 1294 | } |
| 1295 | if (!libsystem_available) { |
| 1296 | const libsystem_name = try std.fmt.allocPrint(arena, "libSystem.{d}.tbd", .{ |
| 1297 | self.base.options.target.os.version_range.semver.min.major, |
| 1298 | }); |
| 1299 | const full_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ |
| 1300 | "libc", "darwin", libsystem_name, |
| 1301 | }); |
| 1302 | try out_libs.put(full_path, .{ .needed = true }); |
| 1303 | } |
| 1247 | 1304 | } |
| 1248 | 1305 | |
| 1249 | 1306 | fn resolveSearchDir( |
| ... | ... | @@ -1288,6 +1345,16 @@ fn resolveSearchDir( |
| 1288 | 1345 | return null; |
| 1289 | 1346 | } |
| 1290 | 1347 | |
| 1348 | fn resolveSearchDirs(arena: Allocator, dirs: []const []const u8, syslibroot: ?[]const u8, out_dirs: anytype) !void { |
| 1349 | for (dirs) |dir| { |
| 1350 | if (try resolveSearchDir(arena, dir, syslibroot)) |search_dir| { |
| 1351 | try out_dirs.append(search_dir); |
| 1352 | } else { |
| 1353 | log.warn("directory not found for '-L{s}'", .{dir}); |
| 1354 | } |
| 1355 | } |
| 1356 | } |
| 1357 | |
| 1291 | 1358 | fn resolveLib( |
| 1292 | 1359 | arena: Allocator, |
| 1293 | 1360 | search_dir: []const u8, |
| ... | ... | @@ -1337,9 +1404,15 @@ fn parseObject(self: *MachO, path: []const u8) !bool { |
| 1337 | 1404 | const name = try self.base.allocator.dupe(u8, path); |
| 1338 | 1405 | errdefer self.base.allocator.free(name); |
| 1339 | 1406 | |
| 1407 | const mtime: u64 = mtime: { |
| 1408 | const stat = file.stat() catch break :mtime 0; |
| 1409 | break :mtime @intCast(u64, @divFloor(stat.mtime, 1_000_000_000)); |
| 1410 | }; |
| 1411 | |
| 1340 | 1412 | var object = Object{ |
| 1341 | 1413 | .name = name, |
| 1342 | 1414 | .file = file, |
| 1415 | .mtime = mtime, |
| 1343 | 1416 | }; |
| 1344 | 1417 | |
| 1345 | 1418 | object.parse(self.base.allocator, self.base.options.target) catch |err| switch (err) { |
| ... | ... | @@ -1507,7 +1580,7 @@ fn parseInputFiles(self: *MachO, files: []const []const u8, syslibroot: ?[]const |
| 1507 | 1580 | .syslibroot = syslibroot, |
| 1508 | 1581 | })) continue; |
| 1509 | 1582 | |
| 1510 | | log.warn("unknown filetype for positional input file: '{s}'", .{file_name}); |
| 1583 | log.debug("unknown filetype for positional input file: '{s}'", .{file_name}); |
| 1511 | 1584 | } |
| 1512 | 1585 | } |
| 1513 | 1586 | |
| ... | ... | @@ -1522,7 +1595,7 @@ fn parseAndForceLoadStaticArchives(self: *MachO, files: []const []const u8) !voi |
| 1522 | 1595 | log.debug("parsing and force loading static archive '{s}'", .{full_path}); |
| 1523 | 1596 | |
| 1524 | 1597 | if (try self.parseArchive(full_path, true)) continue; |
| 1525 | | log.warn("unknown filetype: expected static archive: '{s}'", .{file_name}); |
| 1598 | log.debug("unknown filetype: expected static archive: '{s}'", .{file_name}); |
| 1526 | 1599 | } |
| 1527 | 1600 | } |
| 1528 | 1601 | |
| ... | ... | @@ -1543,7 +1616,7 @@ fn parseLibs( |
| 1543 | 1616 | })) continue; |
| 1544 | 1617 | if (try self.parseArchive(lib, false)) continue; |
| 1545 | 1618 | |
| 1546 | | log.warn("unknown filetype for a library: '{s}'", .{lib}); |
| 1619 | log.debug("unknown filetype for a library: '{s}'", .{lib}); |
| 1547 | 1620 | } |
| 1548 | 1621 | } |
| 1549 | 1622 | |
| ... | ... | @@ -1587,7 +1660,7 @@ fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: any |
| 1587 | 1660 | }); |
| 1588 | 1661 | if (did_parse_successfully) break; |
| 1589 | 1662 | } else { |
| 1590 | | log.warn("unable to resolve dependency {s}", .{dep_id.id.name}); |
| 1663 | log.debug("unable to resolve dependency {s}", .{dep_id.id.name}); |
| 1591 | 1664 | } |
| 1592 | 1665 | } |
| 1593 | 1666 | } |
| ... | ... | @@ -1595,6 +1668,15 @@ fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: any |
| 1595 | 1668 | pub const MatchingSection = struct { |
| 1596 | 1669 | seg: u16, |
| 1597 | 1670 | sect: u16, |
| 1671 | |
| 1672 | pub fn eql(this: MatchingSection, other: struct { |
| 1673 | seg: ?u16, |
| 1674 | sect: ?u16, |
| 1675 | }) bool { |
| 1676 | const seg = other.seg orelse return false; |
| 1677 | const sect = other.sect orelse return false; |
| 1678 | return this.seg == seg and this.sect == sect; |
| 1679 | } |
| 1598 | 1680 | }; |
| 1599 | 1681 | |
| 1600 | 1682 | pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSection { |
| ... | ... | @@ -2158,33 +2240,31 @@ pub fn getMatchingSection(self: *MachO, sect: macho.section_64) !?MatchingSectio |
| 2158 | 2240 | return res; |
| 2159 | 2241 | } |
| 2160 | 2242 | |
| 2161 | | pub fn createEmptyAtom(self: *MachO, local_sym_index: u32, size: u64, alignment: u32) !*Atom { |
| 2243 | pub fn createEmptyAtom(gpa: Allocator, sym_index: u32, size: u64, alignment: u32) !*Atom { |
| 2162 | 2244 | const size_usize = math.cast(usize, size) orelse return error.Overflow; |
| 2163 | | const atom = try self.base.allocator.create(Atom); |
| 2164 | | errdefer self.base.allocator.destroy(atom); |
| 2245 | const atom = try gpa.create(Atom); |
| 2246 | errdefer gpa.destroy(atom); |
| 2165 | 2247 | atom.* = Atom.empty; |
| 2166 | | atom.local_sym_index = local_sym_index; |
| 2248 | atom.sym_index = sym_index; |
| 2167 | 2249 | atom.size = size; |
| 2168 | 2250 | atom.alignment = alignment; |
| 2169 | 2251 | |
| 2170 | | try atom.code.resize(self.base.allocator, size_usize); |
| 2252 | try atom.code.resize(gpa, size_usize); |
| 2171 | 2253 | mem.set(u8, atom.code.items, 0); |
| 2172 | 2254 | |
| 2173 | | try self.managed_atoms.append(self.base.allocator, atom); |
| 2174 | 2255 | return atom; |
| 2175 | 2256 | } |
| 2176 | 2257 | |
| 2177 | 2258 | pub fn writeAtom(self: *MachO, atom: *Atom, match: MatchingSection) !void { |
| 2178 | | const seg = self.load_commands.items[match.seg].segment; |
| 2179 | | const sect = seg.sections.items[match.sect]; |
| 2180 | | const sym = self.locals.items[atom.local_sym_index]; |
| 2259 | const sect = self.getSection(match); |
| 2260 | const sym = atom.getSymbol(self); |
| 2181 | 2261 | const file_offset = sect.offset + sym.n_value - sect.addr; |
| 2182 | 2262 | try atom.resolveRelocs(self); |
| 2183 | | log.debug("writing atom for symbol {s} at file offset 0x{x}", .{ self.getString(sym.n_strx), file_offset }); |
| 2263 | log.debug("writing atom for symbol {s} at file offset 0x{x}", .{ atom.getName(self), file_offset }); |
| 2184 | 2264 | try self.base.file.?.pwriteAll(atom.code.items, file_offset); |
| 2185 | 2265 | } |
| 2186 | 2266 | |
| 2187 | | fn allocateLocals(self: *MachO) !void { |
| 2267 | fn allocateSymbols(self: *MachO) !void { |
| 2188 | 2268 | var it = self.atoms.iterator(); |
| 2189 | 2269 | while (it.next()) |entry| { |
| 2190 | 2270 | const match = entry.key_ptr.*; |
| ... | ... | @@ -2194,37 +2274,25 @@ fn allocateLocals(self: *MachO) !void { |
| 2194 | 2274 | atom = prev; |
| 2195 | 2275 | } |
| 2196 | 2276 | |
| 2197 | | const n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 2198 | | const seg = self.load_commands.items[match.seg].segment; |
| 2199 | | const sect = seg.sections.items[match.sect]; |
| 2277 | const n_sect = self.getSectionOrdinal(match); |
| 2278 | const sect = self.getSection(match); |
| 2200 | 2279 | var base_vaddr = sect.addr; |
| 2201 | 2280 | |
| 2202 | | log.debug("allocating local symbols in {s},{s}", .{ sect.segName(), sect.sectName() }); |
| 2281 | log.debug("allocating local symbols in sect({d}, '{s},{s}')", .{ n_sect, sect.segName(), sect.sectName() }); |
| 2203 | 2282 | |
| 2204 | 2283 | while (true) { |
| 2205 | 2284 | const alignment = try math.powi(u32, 2, atom.alignment); |
| 2206 | 2285 | base_vaddr = mem.alignForwardGeneric(u64, base_vaddr, alignment); |
| 2207 | 2286 | |
| 2208 | | const sym = &self.locals.items[atom.local_sym_index]; |
| 2287 | const sym = atom.getSymbolPtr(self); |
| 2209 | 2288 | sym.n_value = base_vaddr; |
| 2210 | 2289 | sym.n_sect = n_sect; |
| 2211 | 2290 | |
| 2212 | | log.debug(" {d}: {s} allocated at 0x{x}", .{ |
| 2213 | | atom.local_sym_index, |
| 2214 | | self.getString(sym.n_strx), |
| 2215 | | base_vaddr, |
| 2216 | | }); |
| 2217 | | |
| 2218 | | // Update each alias (if any) |
| 2219 | | for (atom.aliases.items) |index| { |
| 2220 | | const alias_sym = &self.locals.items[index]; |
| 2221 | | alias_sym.n_value = base_vaddr; |
| 2222 | | alias_sym.n_sect = n_sect; |
| 2223 | | } |
| 2291 | log.debug(" ATOM(%{d}, '{s}') @{x}", .{ atom.sym_index, atom.getName(self), base_vaddr }); |
| 2224 | 2292 | |
| 2225 | 2293 | // Update each symbol contained within the atom |
| 2226 | 2294 | for (atom.contained.items) |sym_at_off| { |
| 2227 | | const contained_sym = &self.locals.items[sym_at_off.local_sym_index]; |
| 2295 | const contained_sym = self.getSymbolPtr(.{ .sym_index = sym_at_off.sym_index, .file = atom.file }); |
| 2228 | 2296 | contained_sym.n_value = base_vaddr + sym_at_off.offset; |
| 2229 | 2297 | contained_sym.n_sect = n_sect; |
| 2230 | 2298 | } |
| ... | ... | @@ -2242,16 +2310,11 @@ fn shiftLocalsByOffset(self: *MachO, match: MatchingSection, offset: i64) !void |
| 2242 | 2310 | var atom = self.atoms.get(match) orelse return; |
| 2243 | 2311 | |
| 2244 | 2312 | while (true) { |
| 2245 | | const atom_sym = &self.locals.items[atom.local_sym_index]; |
| 2313 | const atom_sym = atom.getSymbolPtr(self); |
| 2246 | 2314 | atom_sym.n_value = @intCast(u64, @intCast(i64, atom_sym.n_value) + offset); |
| 2247 | 2315 | |
| 2248 | | for (atom.aliases.items) |index| { |
| 2249 | | const alias_sym = &self.locals.items[index]; |
| 2250 | | alias_sym.n_value = @intCast(u64, @intCast(i64, alias_sym.n_value) + offset); |
| 2251 | | } |
| 2252 | | |
| 2253 | 2316 | for (atom.contained.items) |sym_at_off| { |
| 2254 | | const contained_sym = &self.locals.items[sym_at_off.local_sym_index]; |
| 2317 | const contained_sym = self.getSymbolPtr(.{ .sym_index = sym_at_off.sym_index, .file = atom.file }); |
| 2255 | 2318 | contained_sym.n_value = @intCast(u64, @intCast(i64, contained_sym.n_value) + offset); |
| 2256 | 2319 | } |
| 2257 | 2320 | |
| ... | ... | @@ -2262,53 +2325,33 @@ fn shiftLocalsByOffset(self: *MachO, match: MatchingSection, offset: i64) !void |
| 2262 | 2325 | } |
| 2263 | 2326 | |
| 2264 | 2327 | fn allocateSpecialSymbols(self: *MachO) !void { |
| 2265 | | for (&[_]?u32{ |
| 2266 | | self.mh_execute_header_sym_index, |
| 2267 | | self.dso_handle_sym_index, |
| 2268 | | }) |maybe_sym_index| { |
| 2269 | | const sym_index = maybe_sym_index orelse continue; |
| 2270 | | const sym = &self.locals.items[sym_index]; |
| 2328 | for (&[_][]const u8{ |
| 2329 | "___dso_handle", |
| 2330 | "__mh_execute_header", |
| 2331 | }) |name| { |
| 2332 | const global = self.globals.get(name) orelse continue; |
| 2333 | if (global.file != null) continue; |
| 2334 | const sym = self.getSymbolPtr(global); |
| 2271 | 2335 | const seg = self.load_commands.items[self.text_segment_cmd_index.?].segment; |
| 2272 | | sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(.{ |
| 2336 | sym.n_sect = self.getSectionOrdinal(.{ |
| 2273 | 2337 | .seg = self.text_segment_cmd_index.?, |
| 2274 | 2338 | .sect = 0, |
| 2275 | | }).? + 1); |
| 2339 | }); |
| 2276 | 2340 | sym.n_value = seg.inner.vmaddr; |
| 2277 | 2341 | |
| 2278 | 2342 | log.debug("allocating {s} at the start of {s}", .{ |
| 2279 | | self.getString(sym.n_strx), |
| 2343 | name, |
| 2280 | 2344 | seg.inner.segName(), |
| 2281 | 2345 | }); |
| 2282 | 2346 | } |
| 2283 | 2347 | } |
| 2284 | 2348 | |
| 2285 | | fn allocateGlobals(self: *MachO) !void { |
| 2286 | | log.debug("allocating global symbols", .{}); |
| 2349 | fn writeAtomsOneShot(self: *MachO) !void { |
| 2350 | assert(self.mode == .one_shot); |
| 2287 | 2351 | |
| 2288 | | var sym_it = self.symbol_resolver.valueIterator(); |
| 2289 | | while (sym_it.next()) |resolv| { |
| 2290 | | if (resolv.where != .global) continue; |
| 2291 | | |
| 2292 | | assert(resolv.local_sym_index != 0); |
| 2293 | | const local_sym = self.locals.items[resolv.local_sym_index]; |
| 2294 | | const sym = &self.globals.items[resolv.where_index]; |
| 2295 | | sym.n_value = local_sym.n_value; |
| 2296 | | sym.n_sect = local_sym.n_sect; |
| 2297 | | |
| 2298 | | log.debug(" {d}: {s} allocated at 0x{x}", .{ |
| 2299 | | resolv.where_index, |
| 2300 | | self.getString(sym.n_strx), |
| 2301 | | local_sym.n_value, |
| 2302 | | }); |
| 2303 | | } |
| 2304 | | } |
| 2305 | | |
| 2306 | | fn writeAllAtoms(self: *MachO) !void { |
| 2307 | 2352 | var it = self.atoms.iterator(); |
| 2308 | 2353 | while (it.next()) |entry| { |
| 2309 | | const match = entry.key_ptr.*; |
| 2310 | | const seg = self.load_commands.items[match.seg].segment; |
| 2311 | | const sect = seg.sections.items[match.sect]; |
| 2354 | const sect = self.getSection(entry.key_ptr.*); |
| 2312 | 2355 | var atom: *Atom = entry.value_ptr.*; |
| 2313 | 2356 | |
| 2314 | 2357 | if (sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL) continue; |
| ... | ... | @@ -2324,20 +2367,28 @@ fn writeAllAtoms(self: *MachO) !void { |
| 2324 | 2367 | } |
| 2325 | 2368 | |
| 2326 | 2369 | while (true) { |
| 2327 | | const atom_sym = self.locals.items[atom.local_sym_index]; |
| 2370 | const this_sym = atom.getSymbol(self); |
| 2328 | 2371 | const padding_size: usize = if (atom.next) |next| blk: { |
| 2329 | | const next_sym = self.locals.items[next.local_sym_index]; |
| 2330 | | const size = next_sym.n_value - (atom_sym.n_value + atom.size); |
| 2372 | const next_sym = next.getSymbol(self); |
| 2373 | const size = next_sym.n_value - (this_sym.n_value + atom.size); |
| 2331 | 2374 | break :blk math.cast(usize, size) orelse return error.Overflow; |
| 2332 | 2375 | } else 0; |
| 2333 | 2376 | |
| 2334 | | log.debug(" (adding atom {s} to buffer: {})", .{ self.getString(atom_sym.n_strx), atom_sym }); |
| 2377 | log.debug(" (adding ATOM(%{d}, '{s}') from object({d}) to buffer)", .{ |
| 2378 | atom.sym_index, |
| 2379 | atom.getName(self), |
| 2380 | atom.file, |
| 2381 | }); |
| 2382 | if (padding_size > 0) { |
| 2383 | log.debug(" (with padding {x})", .{padding_size}); |
| 2384 | } |
| 2335 | 2385 | |
| 2336 | 2386 | try atom.resolveRelocs(self); |
| 2337 | 2387 | buffer.appendSliceAssumeCapacity(atom.code.items); |
| 2338 | 2388 | |
| 2339 | 2389 | var i: usize = 0; |
| 2340 | 2390 | while (i < padding_size) : (i += 1) { |
| 2391 | // TODO with NOPs |
| 2341 | 2392 | buffer.appendAssumeCapacity(0); |
| 2342 | 2393 | } |
| 2343 | 2394 | |
| ... | ... | @@ -2381,12 +2432,13 @@ fn writePadding(self: *MachO, match: MatchingSection, size: usize, writer: anyty |
| 2381 | 2432 | } |
| 2382 | 2433 | } |
| 2383 | 2434 | |
| 2384 | | fn writeAtoms(self: *MachO) !void { |
| 2435 | fn writeAtomsIncremental(self: *MachO) !void { |
| 2436 | assert(self.mode == .incremental); |
| 2437 | |
| 2385 | 2438 | var it = self.atoms.iterator(); |
| 2386 | 2439 | while (it.next()) |entry| { |
| 2387 | 2440 | const match = entry.key_ptr.*; |
| 2388 | | const seg = self.load_commands.items[match.seg].segment; |
| 2389 | | const sect = seg.sections.items[match.sect]; |
| 2441 | const sect = self.getSection(match); |
| 2390 | 2442 | var atom: *Atom = entry.value_ptr.*; |
| 2391 | 2443 | |
| 2392 | 2444 | // TODO handle zerofill in stage2 |
| ... | ... | @@ -2395,7 +2447,7 @@ fn writeAtoms(self: *MachO) !void { |
| 2395 | 2447 | log.debug("writing atoms in {s},{s}", .{ sect.segName(), sect.sectName() }); |
| 2396 | 2448 | |
| 2397 | 2449 | while (true) { |
| 2398 | | if (atom.dirty or self.invalidate_relocs) { |
| 2450 | if (atom.dirty) { |
| 2399 | 2451 | try self.writeAtom(atom, match); |
| 2400 | 2452 | atom.dirty = false; |
| 2401 | 2453 | } |
| ... | ... | @@ -2407,17 +2459,19 @@ fn writeAtoms(self: *MachO) !void { |
| 2407 | 2459 | } |
| 2408 | 2460 | } |
| 2409 | 2461 | |
| 2410 | | pub fn createGotAtom(self: *MachO, target: Atom.Relocation.Target) !*Atom { |
| 2411 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2412 | | try self.locals.append(self.base.allocator, .{ |
| 2462 | pub fn createGotAtom(self: *MachO, target: SymbolWithLoc) !*Atom { |
| 2463 | const gpa = self.base.allocator; |
| 2464 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2465 | try self.locals.append(gpa, .{ |
| 2413 | 2466 | .n_strx = 0, |
| 2414 | 2467 | .n_type = macho.N_SECT, |
| 2415 | 2468 | .n_sect = 0, |
| 2416 | 2469 | .n_desc = 0, |
| 2417 | 2470 | .n_value = 0, |
| 2418 | 2471 | }); |
| 2419 | | const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3); |
| 2420 | | try atom.relocs.append(self.base.allocator, .{ |
| 2472 | |
| 2473 | const atom = try MachO.createEmptyAtom(gpa, sym_index, @sizeOf(u64), 3); |
| 2474 | try atom.relocs.append(gpa, .{ |
| 2421 | 2475 | .offset = 0, |
| 2422 | 2476 | .target = target, |
| 2423 | 2477 | .addend = 0, |
| ... | ... | @@ -2430,35 +2484,60 @@ pub fn createGotAtom(self: *MachO, target: Atom.Relocation.Target) !*Atom { |
| 2430 | 2484 | else => unreachable, |
| 2431 | 2485 | }, |
| 2432 | 2486 | }); |
| 2433 | | switch (target) { |
| 2434 | | .local => { |
| 2435 | | try atom.rebases.append(self.base.allocator, 0); |
| 2436 | | }, |
| 2437 | | .global => |n_strx| { |
| 2438 | | try atom.bindings.append(self.base.allocator, .{ |
| 2439 | | .n_strx = n_strx, |
| 2440 | | .offset = 0, |
| 2441 | | }); |
| 2442 | | }, |
| 2487 | |
| 2488 | const target_sym = self.getSymbol(target); |
| 2489 | if (target_sym.undf()) { |
| 2490 | const global = self.globals.get(self.getSymbolName(target)).?; |
| 2491 | try atom.bindings.append(gpa, .{ |
| 2492 | .target = global, |
| 2493 | .offset = 0, |
| 2494 | }); |
| 2495 | } else { |
| 2496 | try atom.rebases.append(gpa, 0); |
| 2443 | 2497 | } |
| 2498 | |
| 2499 | try self.managed_atoms.append(gpa, atom); |
| 2500 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2501 | |
| 2502 | try self.allocateAtomCommon(atom, .{ |
| 2503 | .seg = self.data_const_segment_cmd_index.?, |
| 2504 | .sect = self.got_section_index.?, |
| 2505 | }); |
| 2506 | |
| 2444 | 2507 | return atom; |
| 2445 | 2508 | } |
| 2446 | 2509 | |
| 2447 | | pub fn createTlvPtrAtom(self: *MachO, target: Atom.Relocation.Target) !*Atom { |
| 2448 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2449 | | try self.locals.append(self.base.allocator, .{ |
| 2510 | pub fn createTlvPtrAtom(self: *MachO, target: SymbolWithLoc) !*Atom { |
| 2511 | const gpa = self.base.allocator; |
| 2512 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2513 | try self.locals.append(gpa, .{ |
| 2450 | 2514 | .n_strx = 0, |
| 2451 | 2515 | .n_type = macho.N_SECT, |
| 2452 | 2516 | .n_sect = 0, |
| 2453 | 2517 | .n_desc = 0, |
| 2454 | 2518 | .n_value = 0, |
| 2455 | 2519 | }); |
| 2456 | | const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3); |
| 2457 | | assert(target == .global); |
| 2458 | | try atom.bindings.append(self.base.allocator, .{ |
| 2459 | | .n_strx = target.global, |
| 2520 | |
| 2521 | const atom = try MachO.createEmptyAtom(gpa, sym_index, @sizeOf(u64), 3); |
| 2522 | const target_sym = self.getSymbol(target); |
| 2523 | assert(target_sym.undf()); |
| 2524 | |
| 2525 | const global = self.globals.get(self.getSymbolName(target)).?; |
| 2526 | try atom.bindings.append(gpa, .{ |
| 2527 | .target = global, |
| 2460 | 2528 | .offset = 0, |
| 2461 | 2529 | }); |
| 2530 | |
| 2531 | try self.managed_atoms.append(gpa, atom); |
| 2532 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2533 | |
| 2534 | const match = (try self.getMatchingSection(.{ |
| 2535 | .segname = makeStaticString("__DATA"), |
| 2536 | .sectname = makeStaticString("__thread_ptrs"), |
| 2537 | .flags = macho.S_THREAD_LOCAL_VARIABLE_POINTERS, |
| 2538 | })).?; |
| 2539 | try self.allocateAtomCommon(atom, match); |
| 2540 | |
| 2462 | 2541 | return atom; |
| 2463 | 2542 | } |
| 2464 | 2543 | |
| ... | ... | @@ -2466,34 +2545,32 @@ fn createDyldPrivateAtom(self: *MachO) !void { |
| 2466 | 2545 | if (self.dyld_stub_binder_index == null) return; |
| 2467 | 2546 | if (self.dyld_private_atom != null) return; |
| 2468 | 2547 | |
| 2469 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2470 | | const sym = try self.locals.addOne(self.base.allocator); |
| 2471 | | sym.* = .{ |
| 2548 | const gpa = self.base.allocator; |
| 2549 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2550 | try self.locals.append(gpa, .{ |
| 2472 | 2551 | .n_strx = 0, |
| 2473 | 2552 | .n_type = macho.N_SECT, |
| 2474 | 2553 | .n_sect = 0, |
| 2475 | 2554 | .n_desc = 0, |
| 2476 | 2555 | .n_value = 0, |
| 2477 | | }; |
| 2478 | | const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3); |
| 2556 | }); |
| 2557 | const atom = try MachO.createEmptyAtom(gpa, sym_index, @sizeOf(u64), 3); |
| 2479 | 2558 | self.dyld_private_atom = atom; |
| 2480 | | const match = MatchingSection{ |
| 2559 | |
| 2560 | try self.allocateAtomCommon(atom, .{ |
| 2481 | 2561 | .seg = self.data_segment_cmd_index.?, |
| 2482 | 2562 | .sect = self.data_section_index.?, |
| 2483 | | }; |
| 2484 | | if (self.needs_prealloc) { |
| 2485 | | const vaddr = try self.allocateAtom(atom, @sizeOf(u64), 8, match); |
| 2486 | | log.debug("allocated {s} atom at 0x{x}", .{ self.getString(sym.n_strx), vaddr }); |
| 2487 | | sym.n_value = vaddr; |
| 2488 | | } else try self.addAtomToSection(atom, match); |
| 2563 | }); |
| 2489 | 2564 | |
| 2490 | | sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 2565 | try self.managed_atoms.append(gpa, atom); |
| 2566 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2491 | 2567 | } |
| 2492 | 2568 | |
| 2493 | 2569 | fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2494 | 2570 | if (self.dyld_stub_binder_index == null) return; |
| 2495 | 2571 | if (self.stub_helper_preamble_atom != null) return; |
| 2496 | 2572 | |
| 2573 | const gpa = self.base.allocator; |
| 2497 | 2574 | const arch = self.base.options.target.cpu.arch; |
| 2498 | 2575 | const size: u64 = switch (arch) { |
| 2499 | 2576 | .x86_64 => 15, |
| ... | ... | @@ -2505,17 +2582,16 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2505 | 2582 | .aarch64 => 2, |
| 2506 | 2583 | else => unreachable, |
| 2507 | 2584 | }; |
| 2508 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2509 | | const sym = try self.locals.addOne(self.base.allocator); |
| 2510 | | sym.* = .{ |
| 2585 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2586 | try self.locals.append(gpa, .{ |
| 2511 | 2587 | .n_strx = 0, |
| 2512 | 2588 | .n_type = macho.N_SECT, |
| 2513 | 2589 | .n_sect = 0, |
| 2514 | 2590 | .n_desc = 0, |
| 2515 | 2591 | .n_value = 0, |
| 2516 | | }; |
| 2517 | | const atom = try self.createEmptyAtom(local_sym_index, size, alignment); |
| 2518 | | const dyld_private_sym_index = self.dyld_private_atom.?.local_sym_index; |
| 2592 | }); |
| 2593 | const atom = try MachO.createEmptyAtom(gpa, sym_index, size, alignment); |
| 2594 | const dyld_private_sym_index = self.dyld_private_atom.?.sym_index; |
| 2519 | 2595 | switch (arch) { |
| 2520 | 2596 | .x86_64 => { |
| 2521 | 2597 | try atom.relocs.ensureUnusedCapacity(self.base.allocator, 2); |
| ... | ... | @@ -2525,7 +2601,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2525 | 2601 | atom.code.items[2] = 0x1d; |
| 2526 | 2602 | atom.relocs.appendAssumeCapacity(.{ |
| 2527 | 2603 | .offset = 3, |
| 2528 | | .target = .{ .local = dyld_private_sym_index }, |
| 2604 | .target = .{ .sym_index = dyld_private_sym_index, .file = null }, |
| 2529 | 2605 | .addend = 0, |
| 2530 | 2606 | .subtractor = null, |
| 2531 | 2607 | .pcrel = true, |
| ... | ... | @@ -2540,7 +2616,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2540 | 2616 | atom.code.items[10] = 0x25; |
| 2541 | 2617 | atom.relocs.appendAssumeCapacity(.{ |
| 2542 | 2618 | .offset = 11, |
| 2543 | | .target = .{ .global = self.undefs.items[self.dyld_stub_binder_index.?].n_strx }, |
| 2619 | .target = .{ .sym_index = self.dyld_stub_binder_index.?, .file = null }, |
| 2544 | 2620 | .addend = 0, |
| 2545 | 2621 | .subtractor = null, |
| 2546 | 2622 | .pcrel = true, |
| ... | ... | @@ -2554,7 +2630,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2554 | 2630 | mem.writeIntLittle(u32, atom.code.items[0..][0..4], aarch64.Instruction.adrp(.x17, 0).toU32()); |
| 2555 | 2631 | atom.relocs.appendAssumeCapacity(.{ |
| 2556 | 2632 | .offset = 0, |
| 2557 | | .target = .{ .local = dyld_private_sym_index }, |
| 2633 | .target = .{ .sym_index = dyld_private_sym_index, .file = null }, |
| 2558 | 2634 | .addend = 0, |
| 2559 | 2635 | .subtractor = null, |
| 2560 | 2636 | .pcrel = true, |
| ... | ... | @@ -2565,7 +2641,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2565 | 2641 | mem.writeIntLittle(u32, atom.code.items[4..][0..4], aarch64.Instruction.add(.x17, .x17, 0, false).toU32()); |
| 2566 | 2642 | atom.relocs.appendAssumeCapacity(.{ |
| 2567 | 2643 | .offset = 4, |
| 2568 | | .target = .{ .local = dyld_private_sym_index }, |
| 2644 | .target = .{ .sym_index = dyld_private_sym_index, .file = null }, |
| 2569 | 2645 | .addend = 0, |
| 2570 | 2646 | .subtractor = null, |
| 2571 | 2647 | .pcrel = false, |
| ... | ... | @@ -2583,7 +2659,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2583 | 2659 | mem.writeIntLittle(u32, atom.code.items[12..][0..4], aarch64.Instruction.adrp(.x16, 0).toU32()); |
| 2584 | 2660 | atom.relocs.appendAssumeCapacity(.{ |
| 2585 | 2661 | .offset = 12, |
| 2586 | | .target = .{ .global = self.undefs.items[self.dyld_stub_binder_index.?].n_strx }, |
| 2662 | .target = .{ .sym_index = self.dyld_stub_binder_index.?, .file = null }, |
| 2587 | 2663 | .addend = 0, |
| 2588 | 2664 | .subtractor = null, |
| 2589 | 2665 | .pcrel = true, |
| ... | ... | @@ -2598,7 +2674,7 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2598 | 2674 | ).toU32()); |
| 2599 | 2675 | atom.relocs.appendAssumeCapacity(.{ |
| 2600 | 2676 | .offset = 16, |
| 2601 | | .target = .{ .global = self.undefs.items[self.dyld_stub_binder_index.?].n_strx }, |
| 2677 | .target = .{ .sym_index = self.dyld_stub_binder_index.?, .file = null }, |
| 2602 | 2678 | .addend = 0, |
| 2603 | 2679 | .subtractor = null, |
| 2604 | 2680 | .pcrel = false, |
| ... | ... | @@ -2611,22 +2687,18 @@ fn createStubHelperPreambleAtom(self: *MachO) !void { |
| 2611 | 2687 | else => unreachable, |
| 2612 | 2688 | } |
| 2613 | 2689 | self.stub_helper_preamble_atom = atom; |
| 2614 | | const match = MatchingSection{ |
| 2690 | |
| 2691 | try self.allocateAtomCommon(atom, .{ |
| 2615 | 2692 | .seg = self.text_segment_cmd_index.?, |
| 2616 | 2693 | .sect = self.stub_helper_section_index.?, |
| 2617 | | }; |
| 2618 | | |
| 2619 | | if (self.needs_prealloc) { |
| 2620 | | const alignment_pow_2 = try math.powi(u32, 2, atom.alignment); |
| 2621 | | const vaddr = try self.allocateAtom(atom, atom.size, alignment_pow_2, match); |
| 2622 | | log.debug("allocated {s} atom at 0x{x}", .{ self.getString(sym.n_strx), vaddr }); |
| 2623 | | sym.n_value = vaddr; |
| 2624 | | } else try self.addAtomToSection(atom, match); |
| 2694 | }); |
| 2625 | 2695 | |
| 2626 | | sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 2696 | try self.managed_atoms.append(gpa, atom); |
| 2697 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2627 | 2698 | } |
| 2628 | 2699 | |
| 2629 | 2700 | pub fn createStubHelperAtom(self: *MachO) !*Atom { |
| 2701 | const gpa = self.base.allocator; |
| 2630 | 2702 | const arch = self.base.options.target.cpu.arch; |
| 2631 | 2703 | const stub_size: u4 = switch (arch) { |
| 2632 | 2704 | .x86_64 => 10, |
| ... | ... | @@ -2638,16 +2710,16 @@ pub fn createStubHelperAtom(self: *MachO) !*Atom { |
| 2638 | 2710 | .aarch64 => 2, |
| 2639 | 2711 | else => unreachable, |
| 2640 | 2712 | }; |
| 2641 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2642 | | try self.locals.append(self.base.allocator, .{ |
| 2713 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2714 | try self.locals.append(gpa, .{ |
| 2643 | 2715 | .n_strx = 0, |
| 2644 | 2716 | .n_type = macho.N_SECT, |
| 2645 | 2717 | .n_sect = 0, |
| 2646 | 2718 | .n_desc = 0, |
| 2647 | 2719 | .n_value = 0, |
| 2648 | 2720 | }); |
| 2649 | | const atom = try self.createEmptyAtom(local_sym_index, stub_size, alignment); |
| 2650 | | try atom.relocs.ensureTotalCapacity(self.base.allocator, 1); |
| 2721 | const atom = try MachO.createEmptyAtom(gpa, sym_index, stub_size, alignment); |
| 2722 | try atom.relocs.ensureTotalCapacity(gpa, 1); |
| 2651 | 2723 | |
| 2652 | 2724 | switch (arch) { |
| 2653 | 2725 | .x86_64 => { |
| ... | ... | @@ -2658,7 +2730,7 @@ pub fn createStubHelperAtom(self: *MachO) !*Atom { |
| 2658 | 2730 | atom.code.items[5] = 0xe9; |
| 2659 | 2731 | atom.relocs.appendAssumeCapacity(.{ |
| 2660 | 2732 | .offset = 6, |
| 2661 | | .target = .{ .local = self.stub_helper_preamble_atom.?.local_sym_index }, |
| 2733 | .target = .{ .sym_index = self.stub_helper_preamble_atom.?.sym_index, .file = null }, |
| 2662 | 2734 | .addend = 0, |
| 2663 | 2735 | .subtractor = null, |
| 2664 | 2736 | .pcrel = true, |
| ... | ... | @@ -2680,7 +2752,7 @@ pub fn createStubHelperAtom(self: *MachO) !*Atom { |
| 2680 | 2752 | mem.writeIntLittle(u32, atom.code.items[4..8], aarch64.Instruction.b(0).toU32()); |
| 2681 | 2753 | atom.relocs.appendAssumeCapacity(.{ |
| 2682 | 2754 | .offset = 4, |
| 2683 | | .target = .{ .local = self.stub_helper_preamble_atom.?.local_sym_index }, |
| 2755 | .target = .{ .sym_index = self.stub_helper_preamble_atom.?.sym_index, .file = null }, |
| 2684 | 2756 | .addend = 0, |
| 2685 | 2757 | .subtractor = null, |
| 2686 | 2758 | .pcrel = true, |
| ... | ... | @@ -2692,22 +2764,31 @@ pub fn createStubHelperAtom(self: *MachO) !*Atom { |
| 2692 | 2764 | else => unreachable, |
| 2693 | 2765 | } |
| 2694 | 2766 | |
| 2767 | try self.managed_atoms.append(gpa, atom); |
| 2768 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2769 | |
| 2770 | try self.allocateAtomCommon(atom, .{ |
| 2771 | .seg = self.text_segment_cmd_index.?, |
| 2772 | .sect = self.stub_helper_section_index.?, |
| 2773 | }); |
| 2774 | |
| 2695 | 2775 | return atom; |
| 2696 | 2776 | } |
| 2697 | 2777 | |
| 2698 | | pub fn createLazyPointerAtom(self: *MachO, stub_sym_index: u32, n_strx: u32) !*Atom { |
| 2699 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2700 | | try self.locals.append(self.base.allocator, .{ |
| 2778 | pub fn createLazyPointerAtom(self: *MachO, stub_sym_index: u32, target: SymbolWithLoc) !*Atom { |
| 2779 | const gpa = self.base.allocator; |
| 2780 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2781 | try self.locals.append(gpa, .{ |
| 2701 | 2782 | .n_strx = 0, |
| 2702 | 2783 | .n_type = macho.N_SECT, |
| 2703 | 2784 | .n_sect = 0, |
| 2704 | 2785 | .n_desc = 0, |
| 2705 | 2786 | .n_value = 0, |
| 2706 | 2787 | }); |
| 2707 | | const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), 3); |
| 2708 | | try atom.relocs.append(self.base.allocator, .{ |
| 2788 | const atom = try MachO.createEmptyAtom(gpa, sym_index, @sizeOf(u64), 3); |
| 2789 | try atom.relocs.append(gpa, .{ |
| 2709 | 2790 | .offset = 0, |
| 2710 | | .target = .{ .local = stub_sym_index }, |
| 2791 | .target = .{ .sym_index = stub_sym_index, .file = null }, |
| 2711 | 2792 | .addend = 0, |
| 2712 | 2793 | .subtractor = null, |
| 2713 | 2794 | .pcrel = false, |
| ... | ... | @@ -2718,15 +2799,27 @@ pub fn createLazyPointerAtom(self: *MachO, stub_sym_index: u32, n_strx: u32) !*A |
| 2718 | 2799 | else => unreachable, |
| 2719 | 2800 | }, |
| 2720 | 2801 | }); |
| 2721 | | try atom.rebases.append(self.base.allocator, 0); |
| 2722 | | try atom.lazy_bindings.append(self.base.allocator, .{ |
| 2723 | | .n_strx = n_strx, |
| 2802 | try atom.rebases.append(gpa, 0); |
| 2803 | |
| 2804 | const global = self.globals.get(self.getSymbolName(target)).?; |
| 2805 | try atom.lazy_bindings.append(gpa, .{ |
| 2806 | .target = global, |
| 2724 | 2807 | .offset = 0, |
| 2725 | 2808 | }); |
| 2809 | |
| 2810 | try self.managed_atoms.append(gpa, atom); |
| 2811 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2812 | |
| 2813 | try self.allocateAtomCommon(atom, .{ |
| 2814 | .seg = self.data_segment_cmd_index.?, |
| 2815 | .sect = self.la_symbol_ptr_section_index.?, |
| 2816 | }); |
| 2817 | |
| 2726 | 2818 | return atom; |
| 2727 | 2819 | } |
| 2728 | 2820 | |
| 2729 | 2821 | pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom { |
| 2822 | const gpa = self.base.allocator; |
| 2730 | 2823 | const arch = self.base.options.target.cpu.arch; |
| 2731 | 2824 | const alignment: u2 = switch (arch) { |
| 2732 | 2825 | .x86_64 => 0, |
| ... | ... | @@ -2738,23 +2831,23 @@ pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom { |
| 2738 | 2831 | .aarch64 => 3 * @sizeOf(u32), |
| 2739 | 2832 | else => unreachable, // unhandled architecture type |
| 2740 | 2833 | }; |
| 2741 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2742 | | try self.locals.append(self.base.allocator, .{ |
| 2834 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2835 | try self.locals.append(gpa, .{ |
| 2743 | 2836 | .n_strx = 0, |
| 2744 | 2837 | .n_type = macho.N_SECT, |
| 2745 | 2838 | .n_sect = 0, |
| 2746 | 2839 | .n_desc = 0, |
| 2747 | 2840 | .n_value = 0, |
| 2748 | 2841 | }); |
| 2749 | | const atom = try self.createEmptyAtom(local_sym_index, stub_size, alignment); |
| 2842 | const atom = try MachO.createEmptyAtom(gpa, sym_index, stub_size, alignment); |
| 2750 | 2843 | switch (arch) { |
| 2751 | 2844 | .x86_64 => { |
| 2752 | 2845 | // jmp |
| 2753 | 2846 | atom.code.items[0] = 0xff; |
| 2754 | 2847 | atom.code.items[1] = 0x25; |
| 2755 | | try atom.relocs.append(self.base.allocator, .{ |
| 2848 | try atom.relocs.append(gpa, .{ |
| 2756 | 2849 | .offset = 2, |
| 2757 | | .target = .{ .local = laptr_sym_index }, |
| 2850 | .target = .{ .sym_index = laptr_sym_index, .file = null }, |
| 2758 | 2851 | .addend = 0, |
| 2759 | 2852 | .subtractor = null, |
| 2760 | 2853 | .pcrel = true, |
| ... | ... | @@ -2763,12 +2856,12 @@ pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom { |
| 2763 | 2856 | }); |
| 2764 | 2857 | }, |
| 2765 | 2858 | .aarch64 => { |
| 2766 | | try atom.relocs.ensureTotalCapacity(self.base.allocator, 2); |
| 2859 | try atom.relocs.ensureTotalCapacity(gpa, 2); |
| 2767 | 2860 | // adrp x16, pages |
| 2768 | 2861 | mem.writeIntLittle(u32, atom.code.items[0..4], aarch64.Instruction.adrp(.x16, 0).toU32()); |
| 2769 | 2862 | atom.relocs.appendAssumeCapacity(.{ |
| 2770 | 2863 | .offset = 0, |
| 2771 | | .target = .{ .local = laptr_sym_index }, |
| 2864 | .target = .{ .sym_index = laptr_sym_index, .file = null }, |
| 2772 | 2865 | .addend = 0, |
| 2773 | 2866 | .subtractor = null, |
| 2774 | 2867 | .pcrel = true, |
| ... | ... | @@ -2783,7 +2876,7 @@ pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom { |
| 2783 | 2876 | ).toU32()); |
| 2784 | 2877 | atom.relocs.appendAssumeCapacity(.{ |
| 2785 | 2878 | .offset = 4, |
| 2786 | | .target = .{ .local = laptr_sym_index }, |
| 2879 | .target = .{ .sym_index = laptr_sym_index, .file = null }, |
| 2787 | 2880 | .addend = 0, |
| 2788 | 2881 | .subtractor = null, |
| 2789 | 2882 | .pcrel = false, |
| ... | ... | @@ -2795,101 +2888,179 @@ pub fn createStubAtom(self: *MachO, laptr_sym_index: u32) !*Atom { |
| 2795 | 2888 | }, |
| 2796 | 2889 | else => unreachable, |
| 2797 | 2890 | } |
| 2891 | |
| 2892 | try self.managed_atoms.append(gpa, atom); |
| 2893 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 2894 | |
| 2895 | try self.allocateAtomCommon(atom, .{ |
| 2896 | .seg = self.text_segment_cmd_index.?, |
| 2897 | .sect = self.stubs_section_index.?, |
| 2898 | }); |
| 2899 | |
| 2798 | 2900 | return atom; |
| 2799 | 2901 | } |
| 2800 | 2902 | |
| 2801 | 2903 | fn createTentativeDefAtoms(self: *MachO) !void { |
| 2802 | | if (self.tentatives.count() == 0) return; |
| 2803 | | // Convert any tentative definition into a regular symbol and allocate |
| 2804 | | // text blocks for each tentative definition. |
| 2805 | | while (self.tentatives.popOrNull()) |entry| { |
| 2904 | const gpa = self.base.allocator; |
| 2905 | |
| 2906 | for (self.globals.values()) |global| { |
| 2907 | const sym = self.getSymbolPtr(global); |
| 2908 | if (!sym.tentative()) continue; |
| 2909 | |
| 2910 | log.debug("creating tentative definition for ATOM(%{d}, '{s}') in object({d})", .{ |
| 2911 | global.sym_index, self.getSymbolName(global), global.file, |
| 2912 | }); |
| 2913 | |
| 2914 | // Convert any tentative definition into a regular symbol and allocate |
| 2915 | // text blocks for each tentative definition. |
| 2806 | 2916 | const match = MatchingSection{ |
| 2807 | 2917 | .seg = self.data_segment_cmd_index.?, |
| 2808 | 2918 | .sect = self.bss_section_index.?, |
| 2809 | 2919 | }; |
| 2810 | | _ = try self.section_ordinals.getOrPut(self.base.allocator, match); |
| 2920 | _ = try self.section_ordinals.getOrPut(gpa, match); |
| 2811 | 2921 | |
| 2812 | | const global_sym = &self.globals.items[entry.key]; |
| 2813 | | const size = global_sym.n_value; |
| 2814 | | const alignment = (global_sym.n_desc >> 8) & 0x0f; |
| 2922 | const size = sym.n_value; |
| 2923 | const alignment = (sym.n_desc >> 8) & 0x0f; |
| 2815 | 2924 | |
| 2816 | | global_sym.n_value = 0; |
| 2817 | | global_sym.n_desc = 0; |
| 2818 | | global_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 2819 | | |
| 2820 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2821 | | const local_sym = try self.locals.addOne(self.base.allocator); |
| 2822 | | local_sym.* = .{ |
| 2823 | | .n_strx = global_sym.n_strx, |
| 2824 | | .n_type = macho.N_SECT, |
| 2825 | | .n_sect = global_sym.n_sect, |
| 2925 | sym.* = .{ |
| 2926 | .n_strx = sym.n_strx, |
| 2927 | .n_type = macho.N_SECT | macho.N_EXT, |
| 2928 | .n_sect = 0, |
| 2826 | 2929 | .n_desc = 0, |
| 2827 | 2930 | .n_value = 0, |
| 2828 | 2931 | }; |
| 2829 | 2932 | |
| 2830 | | const resolv = self.symbol_resolver.getPtr(local_sym.n_strx) orelse unreachable; |
| 2831 | | resolv.local_sym_index = local_sym_index; |
| 2933 | const atom = try MachO.createEmptyAtom(gpa, global.sym_index, size, alignment); |
| 2934 | atom.file = global.file; |
| 2832 | 2935 | |
| 2833 | | const atom = try self.createEmptyAtom(local_sym_index, size, alignment); |
| 2936 | try self.allocateAtomCommon(atom, match); |
| 2834 | 2937 | |
| 2835 | | if (self.needs_prealloc) { |
| 2836 | | const alignment_pow_2 = try math.powi(u32, 2, alignment); |
| 2837 | | const vaddr = try self.allocateAtom(atom, size, alignment_pow_2, match); |
| 2838 | | local_sym.n_value = vaddr; |
| 2839 | | global_sym.n_value = vaddr; |
| 2840 | | } else try self.addAtomToSection(atom, match); |
| 2938 | if (global.file) |file| { |
| 2939 | const object = &self.objects.items[file]; |
| 2940 | try object.managed_atoms.append(gpa, atom); |
| 2941 | try object.atom_by_index_table.putNoClobber(gpa, global.sym_index, atom); |
| 2942 | } else { |
| 2943 | try self.managed_atoms.append(gpa, atom); |
| 2944 | try self.atom_by_index_table.putNoClobber(gpa, global.sym_index, atom); |
| 2945 | } |
| 2841 | 2946 | } |
| 2842 | 2947 | } |
| 2843 | 2948 | |
| 2844 | | fn createDsoHandleSymbol(self: *MachO) !void { |
| 2845 | | if (self.dso_handle_sym_index != null) return; |
| 2846 | | |
| 2847 | | const n_strx = self.strtab_dir.getKeyAdapted(@as([]const u8, "___dso_handle"), StringIndexAdapter{ |
| 2848 | | .bytes = &self.strtab, |
| 2849 | | }) orelse return; |
| 2850 | | |
| 2851 | | const resolv = self.symbol_resolver.getPtr(n_strx) orelse return; |
| 2852 | | if (resolv.where != .undef) return; |
| 2949 | fn createMhExecuteHeaderSymbol(self: *MachO) !void { |
| 2950 | if (self.base.options.output_mode != .Exe) return; |
| 2951 | if (self.globals.get("__mh_execute_header")) |global| { |
| 2952 | const sym = self.getSymbol(global); |
| 2953 | if (!sym.undf() and !(sym.pext() or sym.weakDef())) return; |
| 2954 | } |
| 2853 | 2955 | |
| 2854 | | const undef = &self.undefs.items[resolv.where_index]; |
| 2855 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2856 | | var nlist = macho.nlist_64{ |
| 2857 | | .n_strx = undef.n_strx, |
| 2858 | | .n_type = macho.N_SECT, |
| 2956 | const gpa = self.base.allocator; |
| 2957 | const n_strx = try self.strtab.insert(gpa, "__mh_execute_header"); |
| 2958 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2959 | try self.locals.append(gpa, .{ |
| 2960 | .n_strx = n_strx, |
| 2961 | .n_type = macho.N_SECT | macho.N_EXT, |
| 2859 | 2962 | .n_sect = 0, |
| 2860 | | .n_desc = 0, |
| 2963 | .n_desc = macho.REFERENCED_DYNAMICALLY, |
| 2861 | 2964 | .n_value = 0, |
| 2862 | | }; |
| 2863 | | try self.locals.append(self.base.allocator, nlist); |
| 2864 | | const global_sym_index = @intCast(u32, self.globals.items.len); |
| 2865 | | nlist.n_type |= macho.N_EXT; |
| 2866 | | nlist.n_desc = macho.N_WEAK_DEF; |
| 2867 | | try self.globals.append(self.base.allocator, nlist); |
| 2868 | | self.dso_handle_sym_index = local_sym_index; |
| 2965 | }); |
| 2869 | 2966 | |
| 2870 | | assert(self.unresolved.swapRemove(resolv.where_index)); |
| 2967 | const name = try gpa.dupe(u8, "__mh_execute_header"); |
| 2968 | const gop = try self.globals.getOrPut(gpa, name); |
| 2969 | defer if (gop.found_existing) gpa.free(name); |
| 2970 | gop.value_ptr.* = .{ |
| 2971 | .sym_index = sym_index, |
| 2972 | .file = null, |
| 2973 | }; |
| 2974 | } |
| 2871 | 2975 | |
| 2872 | | undef.* = .{ |
| 2873 | | .n_strx = 0, |
| 2874 | | .n_type = macho.N_UNDF, |
| 2976 | fn createDsoHandleSymbol(self: *MachO) !void { |
| 2977 | const global = self.globals.getPtr("___dso_handle") orelse return; |
| 2978 | const sym = self.getSymbolPtr(global.*); |
| 2979 | if (!sym.undf()) return; |
| 2980 | |
| 2981 | const gpa = self.base.allocator; |
| 2982 | const n_strx = try self.strtab.insert(gpa, "___dso_handle"); |
| 2983 | const sym_index = @intCast(u32, self.locals.items.len); |
| 2984 | try self.locals.append(gpa, .{ |
| 2985 | .n_strx = n_strx, |
| 2986 | .n_type = macho.N_SECT | macho.N_EXT, |
| 2875 | 2987 | .n_sect = 0, |
| 2876 | | .n_desc = 0, |
| 2988 | .n_desc = macho.N_WEAK_DEF, |
| 2877 | 2989 | .n_value = 0, |
| 2990 | }); |
| 2991 | global.* = .{ |
| 2992 | .sym_index = sym_index, |
| 2993 | .file = null, |
| 2878 | 2994 | }; |
| 2879 | | resolv.* = .{ |
| 2880 | | .where = .global, |
| 2881 | | .where_index = global_sym_index, |
| 2882 | | .local_sym_index = local_sym_index, |
| 2883 | | }; |
| 2995 | _ = self.unresolved.swapRemove(@intCast(u32, self.globals.getIndex("___dso_handle").?)); |
| 2884 | 2996 | } |
| 2885 | 2997 | |
| 2886 | | fn resolveSymbolsInObject(self: *MachO, object_id: u16) !void { |
| 2887 | | const object = &self.objects.items[object_id]; |
| 2998 | fn resolveGlobalSymbol(self: *MachO, current: SymbolWithLoc) !void { |
| 2999 | const gpa = self.base.allocator; |
| 3000 | const sym = self.getSymbol(current); |
| 3001 | const sym_name = self.getSymbolName(current); |
| 3002 | |
| 3003 | const name = try gpa.dupe(u8, sym_name); |
| 3004 | const global_index = @intCast(u32, self.globals.values().len); |
| 3005 | const gop = try self.globals.getOrPut(gpa, name); |
| 3006 | defer if (gop.found_existing) gpa.free(name); |
| 3007 | |
| 3008 | if (!gop.found_existing) { |
| 3009 | gop.value_ptr.* = current; |
| 3010 | if (sym.undf() and !sym.tentative()) { |
| 3011 | try self.unresolved.putNoClobber(gpa, global_index, false); |
| 3012 | } |
| 3013 | return; |
| 3014 | } |
| 3015 | |
| 3016 | const global = gop.value_ptr.*; |
| 3017 | const global_sym = self.getSymbol(global); |
| 3018 | |
| 3019 | // Cases to consider: sym vs global_sym |
| 3020 | // 1. strong(sym) and strong(global_sym) => error |
| 3021 | // 2. strong(sym) and weak(global_sym) => sym |
| 3022 | // 3. strong(sym) and tentative(global_sym) => sym |
| 3023 | // 4. strong(sym) and undf(global_sym) => sym |
| 3024 | // 5. weak(sym) and strong(global_sym) => global_sym |
| 3025 | // 6. weak(sym) and tentative(global_sym) => sym |
| 3026 | // 7. weak(sym) and undf(global_sym) => sym |
| 3027 | // 8. tentative(sym) and strong(global_sym) => global_sym |
| 3028 | // 9. tentative(sym) and weak(global_sym) => global_sym |
| 3029 | // 10. tentative(sym) and tentative(global_sym) => pick larger |
| 3030 | // 11. tentative(sym) and undf(global_sym) => sym |
| 3031 | // 12. undf(sym) and * => global_sym |
| 3032 | // |
| 3033 | // Reduces to: |
| 3034 | // 1. strong(sym) and strong(global_sym) => error |
| 3035 | // 2. * and strong(global_sym) => global_sym |
| 3036 | // 3. weak(sym) and weak(global_sym) => global_sym |
| 3037 | // 4. tentative(sym) and tentative(global_sym) => pick larger |
| 3038 | // 5. undf(sym) and * => global_sym |
| 3039 | // 6. else => sym |
| 3040 | |
| 3041 | const sym_is_strong = sym.sect() and !(sym.weakDef() or sym.pext()); |
| 3042 | const global_is_strong = global_sym.sect() and !(global_sym.weakDef() or global_sym.pext()); |
| 3043 | const sym_is_weak = sym.sect() and (sym.weakDef() or sym.pext()); |
| 3044 | const global_is_weak = global_sym.sect() and (global_sym.weakDef() or global_sym.pext()); |
| 3045 | |
| 3046 | if (sym_is_strong and global_is_strong) return error.MultipleSymbolDefinitions; |
| 3047 | if (global_is_strong) return; |
| 3048 | if (sym_is_weak and global_is_weak) return; |
| 3049 | if (sym.tentative() and global_sym.tentative()) { |
| 3050 | if (global_sym.n_value >= sym.n_value) return; |
| 3051 | } |
| 3052 | if (sym.undf() and !sym.tentative()) return; |
| 3053 | |
| 3054 | _ = self.unresolved.swapRemove(@intCast(u32, self.globals.getIndex(name).?)); |
| 3055 | |
| 3056 | gop.value_ptr.* = current; |
| 3057 | } |
| 2888 | 3058 | |
| 3059 | fn resolveSymbolsInObject(self: *MachO, object: *Object, object_id: u16) !void { |
| 2889 | 3060 | log.debug("resolving symbols in '{s}'", .{object.name}); |
| 2890 | 3061 | |
| 2891 | | for (object.symtab.items) |sym, id| { |
| 2892 | | const sym_id = @intCast(u32, id); |
| 3062 | for (object.symtab.items) |sym, index| { |
| 3063 | const sym_index = @intCast(u32, index); |
| 2893 | 3064 | const sym_name = object.getString(sym.n_strx); |
| 2894 | 3065 | |
| 2895 | 3066 | if (sym.stab()) { |
| ... | ... | @@ -2913,170 +3084,27 @@ fn resolveSymbolsInObject(self: *MachO, object_id: u16) !void { |
| 2913 | 3084 | return error.UnhandledSymbolType; |
| 2914 | 3085 | } |
| 2915 | 3086 | |
| 2916 | | if (sym.sect()) { |
| 2917 | | // Defined symbol regardless of scope lands in the locals symbol table. |
| 2918 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 2919 | | try self.locals.append(self.base.allocator, .{ |
| 2920 | | .n_strx = if (symbolIsTemp(sym, sym_name)) 0 else try self.makeString(sym_name), |
| 2921 | | .n_type = macho.N_SECT, |
| 2922 | | .n_sect = 0, |
| 2923 | | .n_desc = 0, |
| 2924 | | .n_value = sym.n_value, |
| 2925 | | }); |
| 2926 | | try object.symbol_mapping.putNoClobber(self.base.allocator, sym_id, local_sym_index); |
| 2927 | | try object.reverse_symbol_mapping.putNoClobber(self.base.allocator, local_sym_index, sym_id); |
| 2928 | | |
| 2929 | | // If the symbol's scope is not local aka translation unit, then we need work out |
| 2930 | | // if we should save the symbol as a global, or potentially flag the error. |
| 2931 | | if (!sym.ext()) continue; |
| 2932 | | |
| 2933 | | const n_strx = try self.makeString(sym_name); |
| 2934 | | const local = self.locals.items[local_sym_index]; |
| 2935 | | const resolv = self.symbol_resolver.getPtr(n_strx) orelse { |
| 2936 | | const global_sym_index = @intCast(u32, self.globals.items.len); |
| 2937 | | try self.globals.append(self.base.allocator, .{ |
| 2938 | | .n_strx = n_strx, |
| 2939 | | .n_type = sym.n_type, |
| 2940 | | .n_sect = 0, |
| 2941 | | .n_desc = sym.n_desc, |
| 2942 | | .n_value = sym.n_value, |
| 2943 | | }); |
| 2944 | | try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{ |
| 2945 | | .where = .global, |
| 2946 | | .where_index = global_sym_index, |
| 2947 | | .local_sym_index = local_sym_index, |
| 2948 | | .file = object_id, |
| 2949 | | }); |
| 2950 | | continue; |
| 2951 | | }; |
| 2952 | | |
| 2953 | | switch (resolv.where) { |
| 2954 | | .global => { |
| 2955 | | const global = &self.globals.items[resolv.where_index]; |
| 2956 | | |
| 2957 | | if (global.tentative()) { |
| 2958 | | assert(self.tentatives.swapRemove(resolv.where_index)); |
| 2959 | | } else if (!(sym.weakDef() or sym.pext()) and !(global.weakDef() or global.pext())) { |
| 2960 | | log.err("symbol '{s}' defined multiple times", .{sym_name}); |
| 2961 | | if (resolv.file) |file| { |
| 2962 | | log.err(" first definition in '{s}'", .{self.objects.items[file].name}); |
| 2963 | | } |
| 2964 | | log.err(" next definition in '{s}'", .{object.name}); |
| 2965 | | return error.MultipleSymbolDefinitions; |
| 2966 | | } else if (sym.weakDef() or sym.pext()) continue; // Current symbol is weak, so skip it. |
| 2967 | | |
| 2968 | | // Otherwise, update the resolver and the global symbol. |
| 2969 | | global.n_type = sym.n_type; |
| 2970 | | resolv.local_sym_index = local_sym_index; |
| 2971 | | resolv.file = object_id; |
| 2972 | | |
| 2973 | | continue; |
| 2974 | | }, |
| 2975 | | .undef => { |
| 2976 | | const undef = &self.undefs.items[resolv.where_index]; |
| 2977 | | undef.* = .{ |
| 2978 | | .n_strx = 0, |
| 2979 | | .n_type = macho.N_UNDF, |
| 2980 | | .n_sect = 0, |
| 2981 | | .n_desc = 0, |
| 2982 | | .n_value = 0, |
| 2983 | | }; |
| 2984 | | assert(self.unresolved.swapRemove(resolv.where_index)); |
| 2985 | | }, |
| 2986 | | } |
| 2987 | | |
| 2988 | | const global_sym_index = @intCast(u32, self.globals.items.len); |
| 2989 | | try self.globals.append(self.base.allocator, .{ |
| 2990 | | .n_strx = local.n_strx, |
| 2991 | | .n_type = sym.n_type, |
| 2992 | | .n_sect = 0, |
| 2993 | | .n_desc = sym.n_desc, |
| 2994 | | .n_value = sym.n_value, |
| 3087 | if (sym.sect() and !sym.ext()) { |
| 3088 | log.debug("symbol '{s}' local to object {s}; skipping...", .{ |
| 3089 | sym_name, |
| 3090 | object.name, |
| 2995 | 3091 | }); |
| 2996 | | resolv.* = .{ |
| 2997 | | .where = .global, |
| 2998 | | .where_index = global_sym_index, |
| 2999 | | .local_sym_index = local_sym_index, |
| 3000 | | .file = object_id, |
| 3001 | | }; |
| 3002 | | } else if (sym.tentative()) { |
| 3003 | | // Symbol is a tentative definition. |
| 3004 | | const n_strx = try self.makeString(sym_name); |
| 3005 | | const resolv = self.symbol_resolver.getPtr(n_strx) orelse { |
| 3006 | | const global_sym_index = @intCast(u32, self.globals.items.len); |
| 3007 | | try self.globals.append(self.base.allocator, .{ |
| 3008 | | .n_strx = try self.makeString(sym_name), |
| 3009 | | .n_type = sym.n_type, |
| 3010 | | .n_sect = 0, |
| 3011 | | .n_desc = sym.n_desc, |
| 3012 | | .n_value = sym.n_value, |
| 3013 | | }); |
| 3014 | | try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{ |
| 3015 | | .where = .global, |
| 3016 | | .where_index = global_sym_index, |
| 3017 | | .file = object_id, |
| 3018 | | }); |
| 3019 | | _ = try self.tentatives.getOrPut(self.base.allocator, global_sym_index); |
| 3020 | | continue; |
| 3021 | | }; |
| 3022 | | |
| 3023 | | switch (resolv.where) { |
| 3024 | | .global => { |
| 3025 | | const global = &self.globals.items[resolv.where_index]; |
| 3026 | | if (!global.tentative()) continue; |
| 3027 | | if (global.n_value >= sym.n_value) continue; |
| 3028 | | |
| 3029 | | global.n_desc = sym.n_desc; |
| 3030 | | global.n_value = sym.n_value; |
| 3031 | | resolv.file = object_id; |
| 3032 | | }, |
| 3033 | | .undef => { |
| 3034 | | const undef = &self.undefs.items[resolv.where_index]; |
| 3035 | | const global_sym_index = @intCast(u32, self.globals.items.len); |
| 3036 | | try self.globals.append(self.base.allocator, .{ |
| 3037 | | .n_strx = undef.n_strx, |
| 3038 | | .n_type = sym.n_type, |
| 3039 | | .n_sect = 0, |
| 3040 | | .n_desc = sym.n_desc, |
| 3041 | | .n_value = sym.n_value, |
| 3042 | | }); |
| 3043 | | _ = try self.tentatives.getOrPut(self.base.allocator, global_sym_index); |
| 3044 | | assert(self.unresolved.swapRemove(resolv.where_index)); |
| 3045 | | |
| 3046 | | resolv.* = .{ |
| 3047 | | .where = .global, |
| 3048 | | .where_index = global_sym_index, |
| 3049 | | .file = object_id, |
| 3050 | | }; |
| 3051 | | undef.* = .{ |
| 3052 | | .n_strx = 0, |
| 3053 | | .n_type = macho.N_UNDF, |
| 3054 | | .n_sect = 0, |
| 3055 | | .n_desc = 0, |
| 3056 | | .n_value = 0, |
| 3057 | | }; |
| 3058 | | }, |
| 3059 | | } |
| 3060 | | } else { |
| 3061 | | // Symbol is undefined. |
| 3062 | | const n_strx = try self.makeString(sym_name); |
| 3063 | | if (self.symbol_resolver.contains(n_strx)) continue; |
| 3064 | | |
| 3065 | | const undef_sym_index = @intCast(u32, self.undefs.items.len); |
| 3066 | | try self.undefs.append(self.base.allocator, .{ |
| 3067 | | .n_strx = try self.makeString(sym_name), |
| 3068 | | .n_type = macho.N_UNDF, |
| 3069 | | .n_sect = 0, |
| 3070 | | .n_desc = sym.n_desc, |
| 3071 | | .n_value = 0, |
| 3072 | | }); |
| 3073 | | try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{ |
| 3074 | | .where = .undef, |
| 3075 | | .where_index = undef_sym_index, |
| 3076 | | .file = object_id, |
| 3077 | | }); |
| 3078 | | try self.unresolved.putNoClobber(self.base.allocator, undef_sym_index, .none); |
| 3092 | continue; |
| 3079 | 3093 | } |
| 3094 | |
| 3095 | const sym_loc = SymbolWithLoc{ .sym_index = sym_index, .file = object_id }; |
| 3096 | self.resolveGlobalSymbol(sym_loc) catch |err| switch (err) { |
| 3097 | error.MultipleSymbolDefinitions => { |
| 3098 | const global = self.globals.get(sym_name).?; |
| 3099 | log.err("symbol '{s}' defined multiple times", .{sym_name}); |
| 3100 | if (global.file) |file| { |
| 3101 | log.err(" first definition in '{s}'", .{self.objects.items[file].name}); |
| 3102 | } |
| 3103 | log.err(" next definition in '{s}'", .{self.objects.items[object_id].name}); |
| 3104 | return error.MultipleSymbolDefinitions; |
| 3105 | }, |
| 3106 | else => |e| return e, |
| 3107 | }; |
| 3080 | 3108 | } |
| 3081 | 3109 | } |
| 3082 | 3110 | |
| ... | ... | @@ -3085,8 +3113,8 @@ fn resolveSymbolsInArchives(self: *MachO) !void { |
| 3085 | 3113 | |
| 3086 | 3114 | var next_sym: usize = 0; |
| 3087 | 3115 | loop: while (next_sym < self.unresolved.count()) { |
| 3088 | | const sym = self.undefs.items[self.unresolved.keys()[next_sym]]; |
| 3089 | | const sym_name = self.getString(sym.n_strx); |
| 3116 | const global = self.globals.values()[self.unresolved.keys()[next_sym]]; |
| 3117 | const sym_name = self.getSymbolName(global); |
| 3090 | 3118 | |
| 3091 | 3119 | for (self.archives.items) |archive| { |
| 3092 | 3120 | // Check if the entry exists in a static archive. |
| ... | ... | @@ -3099,7 +3127,7 @@ fn resolveSymbolsInArchives(self: *MachO) !void { |
| 3099 | 3127 | const object_id = @intCast(u16, self.objects.items.len); |
| 3100 | 3128 | const object = try self.objects.addOne(self.base.allocator); |
| 3101 | 3129 | object.* = try archive.parseObject(self.base.allocator, self.base.options.target, offsets.items[0]); |
| 3102 | | try self.resolveSymbolsInObject(object_id); |
| 3130 | try self.resolveSymbolsInObject(object, object_id); |
| 3103 | 3131 | |
| 3104 | 3132 | continue :loop; |
| 3105 | 3133 | } |
| ... | ... | @@ -3113,8 +3141,10 @@ fn resolveSymbolsInDylibs(self: *MachO) !void { |
| 3113 | 3141 | |
| 3114 | 3142 | var next_sym: usize = 0; |
| 3115 | 3143 | loop: while (next_sym < self.unresolved.count()) { |
| 3116 | | const sym = self.undefs.items[self.unresolved.keys()[next_sym]]; |
| 3117 | | const sym_name = self.getString(sym.n_strx); |
| 3144 | const global_index = self.unresolved.keys()[next_sym]; |
| 3145 | const global = self.globals.values()[global_index]; |
| 3146 | const sym = self.getSymbolPtr(global); |
| 3147 | const sym_name = self.getSymbolName(global); |
| 3118 | 3148 | |
| 3119 | 3149 | for (self.dylibs.items) |dylib, id| { |
| 3120 | 3150 | if (!dylib.symbols.contains(sym_name)) continue; |
| ... | ... | @@ -3126,68 +3156,23 @@ fn resolveSymbolsInDylibs(self: *MachO) !void { |
| 3126 | 3156 | } |
| 3127 | 3157 | |
| 3128 | 3158 | const ordinal = self.referenced_dylibs.getIndex(dylib_id) orelse unreachable; |
| 3129 | | const resolv = self.symbol_resolver.getPtr(sym.n_strx) orelse unreachable; |
| 3130 | | const undef = &self.undefs.items[resolv.where_index]; |
| 3131 | | undef.n_type |= macho.N_EXT; |
| 3132 | | undef.n_desc = @intCast(u16, ordinal + 1) * macho.N_SYMBOL_RESOLVER; |
| 3159 | sym.n_type |= macho.N_EXT; |
| 3160 | sym.n_desc = @intCast(u16, ordinal + 1) * macho.N_SYMBOL_RESOLVER; |
| 3133 | 3161 | |
| 3134 | 3162 | if (dylib.weak) { |
| 3135 | | undef.n_desc |= macho.N_WEAK_REF; |
| 3136 | | } |
| 3137 | | |
| 3138 | | if (self.unresolved.fetchSwapRemove(resolv.where_index)) |entry| outer_blk: { |
| 3139 | | switch (entry.value) { |
| 3140 | | .none => {}, |
| 3141 | | .got => return error.TODOGotHint, |
| 3142 | | .stub => { |
| 3143 | | if (self.stubs_table.contains(sym.n_strx)) break :outer_blk; |
| 3144 | | const stub_helper_atom = blk: { |
| 3145 | | const match = MatchingSection{ |
| 3146 | | .seg = self.text_segment_cmd_index.?, |
| 3147 | | .sect = self.stub_helper_section_index.?, |
| 3148 | | }; |
| 3149 | | const atom = try self.createStubHelperAtom(); |
| 3150 | | const atom_sym = &self.locals.items[atom.local_sym_index]; |
| 3151 | | const alignment = try math.powi(u32, 2, atom.alignment); |
| 3152 | | const vaddr = try self.allocateAtom(atom, atom.size, alignment, match); |
| 3153 | | atom_sym.n_value = vaddr; |
| 3154 | | atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 3155 | | break :blk atom; |
| 3156 | | }; |
| 3157 | | const laptr_atom = blk: { |
| 3158 | | const match = MatchingSection{ |
| 3159 | | .seg = self.data_segment_cmd_index.?, |
| 3160 | | .sect = self.la_symbol_ptr_section_index.?, |
| 3161 | | }; |
| 3162 | | const atom = try self.createLazyPointerAtom( |
| 3163 | | stub_helper_atom.local_sym_index, |
| 3164 | | sym.n_strx, |
| 3165 | | ); |
| 3166 | | const atom_sym = &self.locals.items[atom.local_sym_index]; |
| 3167 | | const alignment = try math.powi(u32, 2, atom.alignment); |
| 3168 | | const vaddr = try self.allocateAtom(atom, atom.size, alignment, match); |
| 3169 | | atom_sym.n_value = vaddr; |
| 3170 | | atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 3171 | | break :blk atom; |
| 3172 | | }; |
| 3173 | | const stub_atom = blk: { |
| 3174 | | const match = MatchingSection{ |
| 3175 | | .seg = self.text_segment_cmd_index.?, |
| 3176 | | .sect = self.stubs_section_index.?, |
| 3177 | | }; |
| 3178 | | const atom = try self.createStubAtom(laptr_atom.local_sym_index); |
| 3179 | | const atom_sym = &self.locals.items[atom.local_sym_index]; |
| 3180 | | const alignment = try math.powi(u32, 2, atom.alignment); |
| 3181 | | const vaddr = try self.allocateAtom(atom, atom.size, alignment, match); |
| 3182 | | atom_sym.n_value = vaddr; |
| 3183 | | atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 3184 | | break :blk atom; |
| 3185 | | }; |
| 3186 | | const stub_index = @intCast(u32, self.stubs.items.len); |
| 3187 | | try self.stubs.append(self.base.allocator, stub_atom); |
| 3188 | | try self.stubs_table.putNoClobber(self.base.allocator, sym.n_strx, stub_index); |
| 3189 | | }, |
| 3190 | | } |
| 3163 | sym.n_desc |= macho.N_WEAK_REF; |
| 3164 | } |
| 3165 | |
| 3166 | if (self.unresolved.fetchSwapRemove(global_index)) |entry| blk: { |
| 3167 | if (!entry.value) break :blk; |
| 3168 | if (!sym.undf()) break :blk; |
| 3169 | if (self.stubs_table.contains(global)) break :blk; |
| 3170 | |
| 3171 | const stub_index = try self.allocateStubEntry(global); |
| 3172 | const stub_helper_atom = try self.createStubHelperAtom(); |
| 3173 | const laptr_atom = try self.createLazyPointerAtom(stub_helper_atom.sym_index, global); |
| 3174 | const stub_atom = try self.createStubAtom(laptr_atom.sym_index); |
| 3175 | self.stubs.items[stub_index].sym_index = stub_atom.sym_index; |
| 3191 | 3176 | } |
| 3192 | 3177 | |
| 3193 | 3178 | continue :loop; |
| ... | ... | @@ -3197,39 +3182,46 @@ fn resolveSymbolsInDylibs(self: *MachO) !void { |
| 3197 | 3182 | } |
| 3198 | 3183 | } |
| 3199 | 3184 | |
| 3200 | | fn createMhExecuteHeaderSymbol(self: *MachO) !void { |
| 3201 | | if (self.base.options.output_mode != .Exe) return; |
| 3202 | | if (self.mh_execute_header_sym_index != null) return; |
| 3185 | fn resolveSymbolsAtLoading(self: *MachO) !void { |
| 3186 | const is_lib = self.base.options.output_mode == .Lib; |
| 3187 | const is_dyn_lib = self.base.options.link_mode == .Dynamic and is_lib; |
| 3188 | const allow_undef = is_dyn_lib and (self.base.options.allow_shlib_undefined orelse false); |
| 3203 | 3189 | |
| 3204 | | const n_strx = try self.makeString("__mh_execute_header"); |
| 3205 | | const local_sym_index = @intCast(u32, self.locals.items.len); |
| 3206 | | var nlist = macho.nlist_64{ |
| 3207 | | .n_strx = n_strx, |
| 3208 | | .n_type = macho.N_SECT, |
| 3209 | | .n_sect = 0, |
| 3210 | | .n_desc = 0, |
| 3211 | | .n_value = 0, |
| 3212 | | }; |
| 3213 | | try self.locals.append(self.base.allocator, nlist); |
| 3214 | | self.mh_execute_header_sym_index = local_sym_index; |
| 3215 | | |
| 3216 | | if (self.symbol_resolver.getPtr(n_strx)) |resolv| { |
| 3217 | | const global = &self.globals.items[resolv.where_index]; |
| 3218 | | if (!(global.weakDef() or !global.pext())) { |
| 3219 | | log.err("symbol '__mh_execute_header' defined multiple times", .{}); |
| 3220 | | return error.MultipleSymbolDefinitions; |
| 3190 | var next_sym: usize = 0; |
| 3191 | while (next_sym < self.unresolved.count()) { |
| 3192 | const global_index = self.unresolved.keys()[next_sym]; |
| 3193 | const global = self.globals.values()[global_index]; |
| 3194 | const sym = self.getSymbolPtr(global); |
| 3195 | const sym_name = self.getSymbolName(global); |
| 3196 | |
| 3197 | if (sym.discarded()) { |
| 3198 | sym.* = .{ |
| 3199 | .n_strx = 0, |
| 3200 | .n_type = macho.N_UNDF, |
| 3201 | .n_sect = 0, |
| 3202 | .n_desc = 0, |
| 3203 | .n_value = 0, |
| 3204 | }; |
| 3205 | _ = self.unresolved.swapRemove(global_index); |
| 3206 | continue; |
| 3207 | } else if (allow_undef) { |
| 3208 | const n_desc = @bitCast( |
| 3209 | u16, |
| 3210 | macho.BIND_SPECIAL_DYLIB_FLAT_LOOKUP * @intCast(i16, macho.N_SYMBOL_RESOLVER), |
| 3211 | ); |
| 3212 | // TODO allow_shlib_undefined is an ELF flag so figure out macOS specific flags too. |
| 3213 | sym.n_type = macho.N_EXT; |
| 3214 | sym.n_desc = n_desc; |
| 3215 | _ = self.unresolved.swapRemove(global_index); |
| 3216 | continue; |
| 3221 | 3217 | } |
| 3222 | | resolv.local_sym_index = local_sym_index; |
| 3223 | | } else { |
| 3224 | | const global_sym_index = @intCast(u32, self.globals.items.len); |
| 3225 | | nlist.n_type |= macho.N_EXT; |
| 3226 | | try self.globals.append(self.base.allocator, nlist); |
| 3227 | | try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{ |
| 3228 | | .where = .global, |
| 3229 | | .where_index = global_sym_index, |
| 3230 | | .local_sym_index = local_sym_index, |
| 3231 | | .file = null, |
| 3232 | | }); |
| 3218 | |
| 3219 | log.err("undefined reference to symbol '{s}'", .{sym_name}); |
| 3220 | if (global.file) |file| { |
| 3221 | log.err(" first referenced in '{s}'", .{self.objects.items[file].name}); |
| 3222 | } |
| 3223 | |
| 3224 | next_sym += 1; |
| 3233 | 3225 | } |
| 3234 | 3226 | } |
| 3235 | 3227 | |
| ... | ... | @@ -3237,21 +3229,20 @@ fn resolveDyldStubBinder(self: *MachO) !void { |
| 3237 | 3229 | if (self.dyld_stub_binder_index != null) return; |
| 3238 | 3230 | if (self.unresolved.count() == 0) return; // no need for a stub binder if we don't have any imports |
| 3239 | 3231 | |
| 3240 | | const n_strx = try self.makeString("dyld_stub_binder"); |
| 3241 | | const sym_index = @intCast(u32, self.undefs.items.len); |
| 3242 | | try self.undefs.append(self.base.allocator, .{ |
| 3232 | const gpa = self.base.allocator; |
| 3233 | const n_strx = try self.strtab.insert(gpa, "dyld_stub_binder"); |
| 3234 | const sym_index = @intCast(u32, self.locals.items.len); |
| 3235 | try self.locals.append(gpa, .{ |
| 3243 | 3236 | .n_strx = n_strx, |
| 3244 | 3237 | .n_type = macho.N_UNDF, |
| 3245 | 3238 | .n_sect = 0, |
| 3246 | 3239 | .n_desc = 0, |
| 3247 | 3240 | .n_value = 0, |
| 3248 | 3241 | }); |
| 3249 | | try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{ |
| 3250 | | .where = .undef, |
| 3251 | | .where_index = sym_index, |
| 3252 | | }); |
| 3253 | | const sym = &self.undefs.items[sym_index]; |
| 3254 | | const sym_name = self.getString(n_strx); |
| 3242 | const sym_name = try gpa.dupe(u8, "dyld_stub_binder"); |
| 3243 | const global = SymbolWithLoc{ .sym_index = sym_index, .file = null }; |
| 3244 | try self.globals.putNoClobber(gpa, sym_name, global); |
| 3245 | const sym = &self.locals.items[sym_index]; |
| 3255 | 3246 | |
| 3256 | 3247 | for (self.dylibs.items) |dylib, id| { |
| 3257 | 3248 | if (!dylib.symbols.contains(sym_name)) continue; |
| ... | ... | @@ -3276,205 +3267,9 @@ fn resolveDyldStubBinder(self: *MachO) !void { |
| 3276 | 3267 | } |
| 3277 | 3268 | |
| 3278 | 3269 | // Add dyld_stub_binder as the final GOT entry. |
| 3279 | | const target = Atom.Relocation.Target{ .global = n_strx }; |
| 3280 | | const atom = try self.createGotAtom(target); |
| 3281 | | const got_index = @intCast(u32, self.got_entries.items.len); |
| 3282 | | try self.got_entries.append(self.base.allocator, .{ .target = target, .atom = atom }); |
| 3283 | | try self.got_entries_table.putNoClobber(self.base.allocator, target, got_index); |
| 3284 | | const match = MatchingSection{ |
| 3285 | | .seg = self.data_const_segment_cmd_index.?, |
| 3286 | | .sect = self.got_section_index.?, |
| 3287 | | }; |
| 3288 | | const atom_sym = &self.locals.items[atom.local_sym_index]; |
| 3289 | | |
| 3290 | | if (self.needs_prealloc) { |
| 3291 | | const vaddr = try self.allocateAtom(atom, @sizeOf(u64), 8, match); |
| 3292 | | log.debug("allocated {s} atom at 0x{x}", .{ self.getString(sym.n_strx), vaddr }); |
| 3293 | | atom_sym.n_value = vaddr; |
| 3294 | | } else { |
| 3295 | | const seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].segment; |
| 3296 | | const sect = &seg.sections.items[self.got_section_index.?]; |
| 3297 | | sect.size += atom.size; |
| 3298 | | try self.addAtomToSection(atom, match); |
| 3299 | | } |
| 3300 | | |
| 3301 | | atom_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 3302 | | } |
| 3303 | | |
| 3304 | | fn parseObjectsIntoAtoms(self: *MachO) !void { |
| 3305 | | // TODO I need to see if I can simplify this logic, or perhaps split it into two functions: |
| 3306 | | // one for non-prealloc traditional path, and one for incremental prealloc path. |
| 3307 | | const tracy = trace(@src()); |
| 3308 | | defer tracy.end(); |
| 3309 | | |
| 3310 | | var parsed_atoms = std.AutoArrayHashMap(MatchingSection, *Atom).init(self.base.allocator); |
| 3311 | | defer parsed_atoms.deinit(); |
| 3312 | | |
| 3313 | | var first_atoms = std.AutoArrayHashMap(MatchingSection, *Atom).init(self.base.allocator); |
| 3314 | | defer first_atoms.deinit(); |
| 3315 | | |
| 3316 | | var section_metadata = std.AutoHashMap(MatchingSection, struct { |
| 3317 | | size: u64, |
| 3318 | | alignment: u32, |
| 3319 | | }).init(self.base.allocator); |
| 3320 | | defer section_metadata.deinit(); |
| 3321 | | |
| 3322 | | for (self.objects.items) |*object| { |
| 3323 | | if (object.analyzed) continue; |
| 3324 | | |
| 3325 | | try object.parseIntoAtoms(self.base.allocator, self); |
| 3326 | | |
| 3327 | | var it = object.end_atoms.iterator(); |
| 3328 | | while (it.next()) |entry| { |
| 3329 | | const match = entry.key_ptr.*; |
| 3330 | | var atom = entry.value_ptr.*; |
| 3331 | | |
| 3332 | | while (atom.prev) |prev| { |
| 3333 | | atom = prev; |
| 3334 | | } |
| 3335 | | |
| 3336 | | const first_atom = atom; |
| 3337 | | |
| 3338 | | const seg = self.load_commands.items[match.seg].segment; |
| 3339 | | const sect = seg.sections.items[match.sect]; |
| 3340 | | const metadata = try section_metadata.getOrPut(match); |
| 3341 | | if (!metadata.found_existing) { |
| 3342 | | metadata.value_ptr.* = .{ |
| 3343 | | .size = sect.size, |
| 3344 | | .alignment = sect.@"align", |
| 3345 | | }; |
| 3346 | | } |
| 3347 | | |
| 3348 | | log.debug("{s},{s}", .{ sect.segName(), sect.sectName() }); |
| 3349 | | |
| 3350 | | while (true) { |
| 3351 | | const alignment = try math.powi(u32, 2, atom.alignment); |
| 3352 | | const curr_size = metadata.value_ptr.size; |
| 3353 | | const curr_size_aligned = mem.alignForwardGeneric(u64, curr_size, alignment); |
| 3354 | | metadata.value_ptr.size = curr_size_aligned + atom.size; |
| 3355 | | metadata.value_ptr.alignment = math.max(metadata.value_ptr.alignment, atom.alignment); |
| 3356 | | |
| 3357 | | const sym = self.locals.items[atom.local_sym_index]; |
| 3358 | | log.debug(" {s}: n_value=0x{x}, size=0x{x}, alignment=0x{x}", .{ |
| 3359 | | self.getString(sym.n_strx), |
| 3360 | | sym.n_value, |
| 3361 | | atom.size, |
| 3362 | | atom.alignment, |
| 3363 | | }); |
| 3364 | | |
| 3365 | | if (atom.next) |next| { |
| 3366 | | atom = next; |
| 3367 | | } else break; |
| 3368 | | } |
| 3369 | | |
| 3370 | | if (parsed_atoms.getPtr(match)) |last| { |
| 3371 | | last.*.next = first_atom; |
| 3372 | | first_atom.prev = last.*; |
| 3373 | | last.* = first_atom; |
| 3374 | | } |
| 3375 | | _ = try parsed_atoms.put(match, atom); |
| 3376 | | |
| 3377 | | if (!first_atoms.contains(match)) { |
| 3378 | | try first_atoms.putNoClobber(match, first_atom); |
| 3379 | | } |
| 3380 | | } |
| 3381 | | |
| 3382 | | object.analyzed = true; |
| 3383 | | } |
| 3384 | | |
| 3385 | | var it = section_metadata.iterator(); |
| 3386 | | while (it.next()) |entry| { |
| 3387 | | const match = entry.key_ptr.*; |
| 3388 | | const metadata = entry.value_ptr.*; |
| 3389 | | const seg = &self.load_commands.items[match.seg].segment; |
| 3390 | | const sect = &seg.sections.items[match.sect]; |
| 3391 | | log.debug("{s},{s} => size: 0x{x}, alignment: 0x{x}", .{ |
| 3392 | | sect.segName(), |
| 3393 | | sect.sectName(), |
| 3394 | | metadata.size, |
| 3395 | | metadata.alignment, |
| 3396 | | }); |
| 3397 | | |
| 3398 | | sect.@"align" = math.max(sect.@"align", metadata.alignment); |
| 3399 | | const needed_size = @intCast(u32, metadata.size); |
| 3400 | | |
| 3401 | | if (self.needs_prealloc) { |
| 3402 | | try self.growSection(match, needed_size); |
| 3403 | | } |
| 3404 | | sect.size = needed_size; |
| 3405 | | } |
| 3406 | | |
| 3407 | | for (&[_]?u16{ |
| 3408 | | self.text_segment_cmd_index, |
| 3409 | | self.data_const_segment_cmd_index, |
| 3410 | | self.data_segment_cmd_index, |
| 3411 | | }) |maybe_seg_id| { |
| 3412 | | const seg_id = maybe_seg_id orelse continue; |
| 3413 | | const seg = self.load_commands.items[seg_id].segment; |
| 3414 | | |
| 3415 | | for (seg.sections.items) |sect, sect_id| { |
| 3416 | | const match = MatchingSection{ |
| 3417 | | .seg = seg_id, |
| 3418 | | .sect = @intCast(u16, sect_id), |
| 3419 | | }; |
| 3420 | | if (!section_metadata.contains(match)) continue; |
| 3421 | | |
| 3422 | | var base_vaddr = if (self.atoms.get(match)) |last| blk: { |
| 3423 | | const last_atom_sym = self.locals.items[last.local_sym_index]; |
| 3424 | | break :blk last_atom_sym.n_value + last.size; |
| 3425 | | } else sect.addr; |
| 3426 | | |
| 3427 | | if (self.atoms.getPtr(match)) |last| { |
| 3428 | | const first_atom = first_atoms.get(match).?; |
| 3429 | | last.*.next = first_atom; |
| 3430 | | first_atom.prev = last.*; |
| 3431 | | last.* = first_atom; |
| 3432 | | } |
| 3433 | | _ = try self.atoms.put(self.base.allocator, match, parsed_atoms.get(match).?); |
| 3434 | | |
| 3435 | | if (!self.needs_prealloc) continue; |
| 3436 | | |
| 3437 | | const n_sect = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 3438 | | |
| 3439 | | var atom = first_atoms.get(match).?; |
| 3440 | | while (true) { |
| 3441 | | const alignment = try math.powi(u32, 2, atom.alignment); |
| 3442 | | base_vaddr = mem.alignForwardGeneric(u64, base_vaddr, alignment); |
| 3443 | | |
| 3444 | | const sym = &self.locals.items[atom.local_sym_index]; |
| 3445 | | sym.n_value = base_vaddr; |
| 3446 | | sym.n_sect = n_sect; |
| 3447 | | |
| 3448 | | log.debug(" {s}: start=0x{x}, end=0x{x}, size=0x{x}, alignment=0x{x}", .{ |
| 3449 | | self.getString(sym.n_strx), |
| 3450 | | base_vaddr, |
| 3451 | | base_vaddr + atom.size, |
| 3452 | | atom.size, |
| 3453 | | atom.alignment, |
| 3454 | | }); |
| 3455 | | |
| 3456 | | // Update each alias (if any) |
| 3457 | | for (atom.aliases.items) |index| { |
| 3458 | | const alias_sym = &self.locals.items[index]; |
| 3459 | | alias_sym.n_value = base_vaddr; |
| 3460 | | alias_sym.n_sect = n_sect; |
| 3461 | | } |
| 3462 | | |
| 3463 | | // Update each symbol contained within the atom |
| 3464 | | for (atom.contained.items) |sym_at_off| { |
| 3465 | | const contained_sym = &self.locals.items[sym_at_off.local_sym_index]; |
| 3466 | | contained_sym.n_value = base_vaddr + sym_at_off.offset; |
| 3467 | | contained_sym.n_sect = n_sect; |
| 3468 | | } |
| 3469 | | |
| 3470 | | base_vaddr += atom.size; |
| 3471 | | |
| 3472 | | if (atom.next) |next| { |
| 3473 | | atom = next; |
| 3474 | | } else break; |
| 3475 | | } |
| 3476 | | } |
| 3477 | | } |
| 3270 | const got_index = try self.allocateGotEntry(global); |
| 3271 | const got_atom = try self.createGotAtom(global); |
| 3272 | self.got_entries.items[got_index].sym_index = got_atom.sym_index; |
| 3478 | 3273 | } |
| 3479 | 3274 | |
| 3480 | 3275 | fn addLoadDylibLC(self: *MachO, id: u16) !void { |
| ... | ... | @@ -3511,16 +3306,8 @@ fn setEntryPoint(self: *MachO) !void { |
| 3511 | 3306 | if (self.base.options.output_mode != .Exe) return; |
| 3512 | 3307 | |
| 3513 | 3308 | const seg = self.load_commands.items[self.text_segment_cmd_index.?].segment; |
| 3514 | | const entry_name = self.base.options.entry orelse "_main"; |
| 3515 | | const n_strx = self.strtab_dir.getKeyAdapted(entry_name, StringIndexAdapter{ |
| 3516 | | .bytes = &self.strtab, |
| 3517 | | }) orelse { |
| 3518 | | log.err("entrypoint '{s}' not found", .{entry_name}); |
| 3519 | | return error.MissingMainEntrypoint; |
| 3520 | | }; |
| 3521 | | const resolv = self.symbol_resolver.get(n_strx) orelse unreachable; |
| 3522 | | assert(resolv.where == .global); |
| 3523 | | const sym = self.globals.items[resolv.where_index]; |
| 3309 | const global = try self.getEntryPoint(); |
| 3310 | const sym = self.getSymbol(global); |
| 3524 | 3311 | const ec = &self.load_commands.items[self.main_cmd_index.?].main; |
| 3525 | 3312 | ec.entryoff = @intCast(u32, sym.n_value - seg.inner.vmaddr); |
| 3526 | 3313 | ec.stacksize = self.base.options.stack_size_override orelse 0; |
| ... | ... | @@ -3529,76 +3316,77 @@ fn setEntryPoint(self: *MachO) !void { |
| 3529 | 3316 | } |
| 3530 | 3317 | |
| 3531 | 3318 | pub fn deinit(self: *MachO) void { |
| 3319 | const gpa = self.base.allocator; |
| 3320 | |
| 3532 | 3321 | if (build_options.have_llvm) { |
| 3533 | | if (self.llvm_object) |llvm_object| llvm_object.destroy(self.base.allocator); |
| 3322 | if (self.llvm_object) |llvm_object| llvm_object.destroy(gpa); |
| 3534 | 3323 | } |
| 3535 | 3324 | |
| 3536 | 3325 | if (self.d_sym) |*d_sym| { |
| 3537 | | d_sym.deinit(self.base.allocator); |
| 3538 | | } |
| 3539 | | |
| 3540 | | self.section_ordinals.deinit(self.base.allocator); |
| 3541 | | self.tlv_ptr_entries.deinit(self.base.allocator); |
| 3542 | | self.tlv_ptr_entries_free_list.deinit(self.base.allocator); |
| 3543 | | self.tlv_ptr_entries_table.deinit(self.base.allocator); |
| 3544 | | self.got_entries.deinit(self.base.allocator); |
| 3545 | | self.got_entries_free_list.deinit(self.base.allocator); |
| 3546 | | self.got_entries_table.deinit(self.base.allocator); |
| 3547 | | self.stubs.deinit(self.base.allocator); |
| 3548 | | self.stubs_free_list.deinit(self.base.allocator); |
| 3549 | | self.stubs_table.deinit(self.base.allocator); |
| 3550 | | self.strtab_dir.deinit(self.base.allocator); |
| 3551 | | self.strtab.deinit(self.base.allocator); |
| 3552 | | self.undefs.deinit(self.base.allocator); |
| 3553 | | self.globals.deinit(self.base.allocator); |
| 3554 | | self.globals_free_list.deinit(self.base.allocator); |
| 3555 | | self.locals.deinit(self.base.allocator); |
| 3556 | | self.locals_free_list.deinit(self.base.allocator); |
| 3557 | | self.symbol_resolver.deinit(self.base.allocator); |
| 3558 | | self.unresolved.deinit(self.base.allocator); |
| 3559 | | self.tentatives.deinit(self.base.allocator); |
| 3326 | d_sym.deinit(gpa); |
| 3327 | } |
| 3328 | |
| 3329 | self.section_ordinals.deinit(gpa); |
| 3330 | self.tlv_ptr_entries.deinit(gpa); |
| 3331 | self.tlv_ptr_entries_free_list.deinit(gpa); |
| 3332 | self.tlv_ptr_entries_table.deinit(gpa); |
| 3333 | self.got_entries.deinit(gpa); |
| 3334 | self.got_entries_free_list.deinit(gpa); |
| 3335 | self.got_entries_table.deinit(gpa); |
| 3336 | self.stubs.deinit(gpa); |
| 3337 | self.stubs_free_list.deinit(gpa); |
| 3338 | self.stubs_table.deinit(gpa); |
| 3339 | self.strtab.deinit(gpa); |
| 3340 | self.locals.deinit(gpa); |
| 3341 | self.locals_free_list.deinit(gpa); |
| 3342 | self.unresolved.deinit(gpa); |
| 3343 | |
| 3344 | for (self.globals.keys()) |key| { |
| 3345 | gpa.free(key); |
| 3346 | } |
| 3347 | self.globals.deinit(gpa); |
| 3560 | 3348 | |
| 3561 | 3349 | for (self.objects.items) |*object| { |
| 3562 | | object.deinit(self.base.allocator); |
| 3350 | object.deinit(gpa); |
| 3563 | 3351 | } |
| 3564 | | self.objects.deinit(self.base.allocator); |
| 3352 | self.objects.deinit(gpa); |
| 3565 | 3353 | |
| 3566 | 3354 | for (self.archives.items) |*archive| { |
| 3567 | | archive.deinit(self.base.allocator); |
| 3355 | archive.deinit(gpa); |
| 3568 | 3356 | } |
| 3569 | | self.archives.deinit(self.base.allocator); |
| 3357 | self.archives.deinit(gpa); |
| 3570 | 3358 | |
| 3571 | 3359 | for (self.dylibs.items) |*dylib| { |
| 3572 | | dylib.deinit(self.base.allocator); |
| 3360 | dylib.deinit(gpa); |
| 3573 | 3361 | } |
| 3574 | | self.dylibs.deinit(self.base.allocator); |
| 3575 | | self.dylibs_map.deinit(self.base.allocator); |
| 3576 | | self.referenced_dylibs.deinit(self.base.allocator); |
| 3362 | self.dylibs.deinit(gpa); |
| 3363 | self.dylibs_map.deinit(gpa); |
| 3364 | self.referenced_dylibs.deinit(gpa); |
| 3577 | 3365 | |
| 3578 | 3366 | for (self.load_commands.items) |*lc| { |
| 3579 | | lc.deinit(self.base.allocator); |
| 3367 | lc.deinit(gpa); |
| 3580 | 3368 | } |
| 3581 | | self.load_commands.deinit(self.base.allocator); |
| 3369 | self.load_commands.deinit(gpa); |
| 3582 | 3370 | |
| 3583 | 3371 | for (self.managed_atoms.items) |atom| { |
| 3584 | | atom.deinit(self.base.allocator); |
| 3585 | | self.base.allocator.destroy(atom); |
| 3372 | atom.deinit(gpa); |
| 3373 | gpa.destroy(atom); |
| 3586 | 3374 | } |
| 3587 | | self.managed_atoms.deinit(self.base.allocator); |
| 3588 | | self.atoms.deinit(self.base.allocator); |
| 3375 | self.managed_atoms.deinit(gpa); |
| 3376 | self.atoms.deinit(gpa); |
| 3589 | 3377 | { |
| 3590 | 3378 | var it = self.atom_free_lists.valueIterator(); |
| 3591 | 3379 | while (it.next()) |free_list| { |
| 3592 | | free_list.deinit(self.base.allocator); |
| 3380 | free_list.deinit(gpa); |
| 3593 | 3381 | } |
| 3594 | | self.atom_free_lists.deinit(self.base.allocator); |
| 3382 | self.atom_free_lists.deinit(gpa); |
| 3595 | 3383 | } |
| 3596 | 3384 | if (self.base.options.module) |mod| { |
| 3597 | 3385 | for (self.decls.keys()) |decl_index| { |
| 3598 | 3386 | const decl = mod.declPtr(decl_index); |
| 3599 | | decl.link.macho.deinit(self.base.allocator); |
| 3387 | decl.link.macho.deinit(gpa); |
| 3600 | 3388 | } |
| 3601 | | self.decls.deinit(self.base.allocator); |
| 3389 | self.decls.deinit(gpa); |
| 3602 | 3390 | } else { |
| 3603 | 3391 | assert(self.decls.count() == 0); |
| 3604 | 3392 | } |
| ... | ... | @@ -3606,15 +3394,15 @@ pub fn deinit(self: *MachO) void { |
| 3606 | 3394 | { |
| 3607 | 3395 | var it = self.unnamed_const_atoms.valueIterator(); |
| 3608 | 3396 | while (it.next()) |atoms| { |
| 3609 | | atoms.deinit(self.base.allocator); |
| 3397 | atoms.deinit(gpa); |
| 3610 | 3398 | } |
| 3611 | | self.unnamed_const_atoms.deinit(self.base.allocator); |
| 3399 | self.unnamed_const_atoms.deinit(gpa); |
| 3612 | 3400 | } |
| 3613 | 3401 | |
| 3614 | | self.atom_by_index_table.deinit(self.base.allocator); |
| 3402 | self.atom_by_index_table.deinit(gpa); |
| 3615 | 3403 | |
| 3616 | 3404 | if (self.code_signature) |*csig| { |
| 3617 | | csig.deinit(self.base.allocator); |
| 3405 | csig.deinit(gpa); |
| 3618 | 3406 | } |
| 3619 | 3407 | } |
| 3620 | 3408 | |
| ... | ... | @@ -3670,7 +3458,7 @@ fn freeAtom(self: *MachO, atom: *Atom, match: MatchingSection, owns_atom: bool) |
| 3670 | 3458 | if (atom.prev) |prev| { |
| 3671 | 3459 | prev.next = atom.next; |
| 3672 | 3460 | |
| 3673 | | if (!already_have_free_list_node and prev.freeListEligible(self.*)) { |
| 3461 | if (!already_have_free_list_node and prev.freeListEligible(self)) { |
| 3674 | 3462 | // The free list is heuristics, it doesn't have to be perfect, so we can ignore |
| 3675 | 3463 | // the OOM here. |
| 3676 | 3464 | free_list.append(self.base.allocator, prev) catch {}; |
| ... | ... | @@ -3700,14 +3488,14 @@ fn shrinkAtom(self: *MachO, atom: *Atom, new_block_size: u64, match: MatchingSec |
| 3700 | 3488 | } |
| 3701 | 3489 | |
| 3702 | 3490 | fn growAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, match: MatchingSection) !u64 { |
| 3703 | | const sym = self.locals.items[atom.local_sym_index]; |
| 3491 | const sym = atom.getSymbol(self); |
| 3704 | 3492 | const align_ok = mem.alignBackwardGeneric(u64, sym.n_value, alignment) == sym.n_value; |
| 3705 | | 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); |
| 3706 | 3494 | if (!need_realloc) return sym.n_value; |
| 3707 | 3495 | return self.allocateAtom(atom, new_atom_size, alignment, match); |
| 3708 | 3496 | } |
| 3709 | 3497 | |
| 3710 | | fn allocateLocalSymbol(self: *MachO) !u32 { |
| 3498 | fn allocateSymbol(self: *MachO) !u32 { |
| 3711 | 3499 | try self.locals.ensureUnusedCapacity(self.base.allocator, 1); |
| 3712 | 3500 | |
| 3713 | 3501 | const index = blk: { |
| ... | ... | @@ -3733,8 +3521,9 @@ fn allocateLocalSymbol(self: *MachO) !u32 { |
| 3733 | 3521 | return index; |
| 3734 | 3522 | } |
| 3735 | 3523 | |
| 3736 | | pub fn allocateGotEntry(self: *MachO, target: Atom.Relocation.Target) !u32 { |
| 3737 | | try self.got_entries.ensureUnusedCapacity(self.base.allocator, 1); |
| 3524 | pub fn allocateGotEntry(self: *MachO, target: SymbolWithLoc) !u32 { |
| 3525 | const gpa = self.base.allocator; |
| 3526 | try self.got_entries.ensureUnusedCapacity(gpa, 1); |
| 3738 | 3527 | |
| 3739 | 3528 | const index = blk: { |
| 3740 | 3529 | if (self.got_entries_free_list.popOrNull()) |index| { |
| ... | ... | @@ -3748,16 +3537,13 @@ pub fn allocateGotEntry(self: *MachO, target: Atom.Relocation.Target) !u32 { |
| 3748 | 3537 | } |
| 3749 | 3538 | }; |
| 3750 | 3539 | |
| 3751 | | self.got_entries.items[index] = .{ |
| 3752 | | .target = target, |
| 3753 | | .atom = undefined, |
| 3754 | | }; |
| 3755 | | try self.got_entries_table.putNoClobber(self.base.allocator, target, index); |
| 3540 | self.got_entries.items[index] = .{ .target = target, .sym_index = 0 }; |
| 3541 | try self.got_entries_table.putNoClobber(gpa, target, index); |
| 3756 | 3542 | |
| 3757 | 3543 | return index; |
| 3758 | 3544 | } |
| 3759 | 3545 | |
| 3760 | | pub fn allocateStubEntry(self: *MachO, n_strx: u32) !u32 { |
| 3546 | pub fn allocateStubEntry(self: *MachO, target: SymbolWithLoc) !u32 { |
| 3761 | 3547 | try self.stubs.ensureUnusedCapacity(self.base.allocator, 1); |
| 3762 | 3548 | |
| 3763 | 3549 | const index = blk: { |
| ... | ... | @@ -3772,13 +3558,13 @@ pub fn allocateStubEntry(self: *MachO, n_strx: u32) !u32 { |
| 3772 | 3558 | } |
| 3773 | 3559 | }; |
| 3774 | 3560 | |
| 3775 | | self.stubs.items[index] = undefined; |
| 3776 | | try self.stubs_table.putNoClobber(self.base.allocator, n_strx, index); |
| 3561 | self.stubs.items[index] = .{ .target = target, .sym_index = 0 }; |
| 3562 | try self.stubs_table.putNoClobber(self.base.allocator, target, index); |
| 3777 | 3563 | |
| 3778 | 3564 | return index; |
| 3779 | 3565 | } |
| 3780 | 3566 | |
| 3781 | | pub fn allocateTlvPtrEntry(self: *MachO, target: Atom.Relocation.Target) !u32 { |
| 3567 | pub fn allocateTlvPtrEntry(self: *MachO, target: SymbolWithLoc) !u32 { |
| 3782 | 3568 | try self.tlv_ptr_entries.ensureUnusedCapacity(self.base.allocator, 1); |
| 3783 | 3569 | |
| 3784 | 3570 | const index = blk: { |
| ... | ... | @@ -3793,7 +3579,7 @@ pub fn allocateTlvPtrEntry(self: *MachO, target: Atom.Relocation.Target) !u32 { |
| 3793 | 3579 | } |
| 3794 | 3580 | }; |
| 3795 | 3581 | |
| 3796 | | self.tlv_ptr_entries.items[index] = .{ .target = target, .atom = undefined }; |
| 3582 | self.tlv_ptr_entries.items[index] = .{ .target = target, .sym_index = 0 }; |
| 3797 | 3583 | try self.tlv_ptr_entries_table.putNoClobber(self.base.allocator, target, index); |
| 3798 | 3584 | |
| 3799 | 3585 | return index; |
| ... | ... | @@ -3802,16 +3588,11 @@ pub fn allocateTlvPtrEntry(self: *MachO, target: Atom.Relocation.Target) !u32 { |
| 3802 | 3588 | pub fn allocateDeclIndexes(self: *MachO, decl_index: Module.Decl.Index) !void { |
| 3803 | 3589 | if (self.llvm_object) |_| return; |
| 3804 | 3590 | const decl = self.base.options.module.?.declPtr(decl_index); |
| 3805 | | if (decl.link.macho.local_sym_index != 0) return; |
| 3591 | if (decl.link.macho.sym_index != 0) return; |
| 3806 | 3592 | |
| 3807 | | decl.link.macho.local_sym_index = try self.allocateLocalSymbol(); |
| 3808 | | try self.atom_by_index_table.putNoClobber(self.base.allocator, decl.link.macho.local_sym_index, &decl.link.macho); |
| 3593 | decl.link.macho.sym_index = try self.allocateSymbol(); |
| 3594 | try self.atom_by_index_table.putNoClobber(self.base.allocator, decl.link.macho.sym_index, &decl.link.macho); |
| 3809 | 3595 | try self.decls.putNoClobber(self.base.allocator, decl_index, null); |
| 3810 | | |
| 3811 | | const got_target = .{ .local = decl.link.macho.local_sym_index }; |
| 3812 | | const got_index = try self.allocateGotEntry(got_target); |
| 3813 | | const got_atom = try self.createGotAtom(got_target); |
| 3814 | | self.got_entries.items[got_index].atom = got_atom; |
| 3815 | 3596 | } |
| 3816 | 3597 | |
| 3817 | 3598 | pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liveness: Liveness) !void { |
| ... | ... | @@ -3862,14 +3643,14 @@ pub fn updateFunc(self: *MachO, module: *Module, func: *Module.Fn, air: Air, liv |
| 3862 | 3643 | }, |
| 3863 | 3644 | } |
| 3864 | 3645 | |
| 3865 | | const symbol = try self.placeDecl(decl_index, decl.link.macho.code.items.len); |
| 3646 | const addr = try self.placeDecl(decl_index, decl.link.macho.code.items.len); |
| 3866 | 3647 | |
| 3867 | 3648 | if (decl_state) |*ds| { |
| 3868 | 3649 | try self.d_sym.?.dwarf.commitDeclState( |
| 3869 | 3650 | &self.base, |
| 3870 | 3651 | module, |
| 3871 | 3652 | decl, |
| 3872 | | symbol.n_value, |
| 3653 | addr, |
| 3873 | 3654 | decl.link.macho.size, |
| 3874 | 3655 | ds, |
| 3875 | 3656 | ); |
| ... | ... | @@ -3885,8 +3666,9 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Modu |
| 3885 | 3666 | var code_buffer = std.ArrayList(u8).init(self.base.allocator); |
| 3886 | 3667 | defer code_buffer.deinit(); |
| 3887 | 3668 | |
| 3669 | const gpa = self.base.allocator; |
| 3888 | 3670 | const module = self.base.options.module.?; |
| 3889 | | const gop = try self.unnamed_const_atoms.getOrPut(self.base.allocator, decl_index); |
| 3671 | const gop = try self.unnamed_const_atoms.getOrPut(gpa, decl_index); |
| 3890 | 3672 | if (!gop.found_existing) { |
| 3891 | 3673 | gop.value_ptr.* = .{}; |
| 3892 | 3674 | } |
| ... | ... | @@ -3894,25 +3676,32 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Modu |
| 3894 | 3676 | |
| 3895 | 3677 | const decl = module.declPtr(decl_index); |
| 3896 | 3678 | const decl_name = try decl.getFullyQualifiedName(module); |
| 3897 | | defer self.base.allocator.free(decl_name); |
| 3679 | defer gpa.free(decl_name); |
| 3898 | 3680 | |
| 3899 | 3681 | const name_str_index = blk: { |
| 3900 | 3682 | const index = unnamed_consts.items.len; |
| 3901 | | const name = try std.fmt.allocPrint(self.base.allocator, "__unnamed_{s}_{d}", .{ decl_name, index }); |
| 3902 | | defer self.base.allocator.free(name); |
| 3903 | | break :blk try self.makeString(name); |
| 3683 | const name = try std.fmt.allocPrint(gpa, "__unnamed_{s}_{d}", .{ decl_name, index }); |
| 3684 | defer gpa.free(name); |
| 3685 | break :blk try self.strtab.insert(gpa, name); |
| 3904 | 3686 | }; |
| 3905 | | const name = self.getString(name_str_index); |
| 3687 | const name = self.strtab.get(name_str_index); |
| 3906 | 3688 | |
| 3907 | 3689 | log.debug("allocating symbol indexes for {s}", .{name}); |
| 3908 | 3690 | |
| 3909 | 3691 | const required_alignment = typed_value.ty.abiAlignment(self.base.options.target); |
| 3910 | | const local_sym_index = try self.allocateLocalSymbol(); |
| 3911 | | const atom = try self.createEmptyAtom(local_sym_index, @sizeOf(u64), math.log2(required_alignment)); |
| 3912 | | try self.atom_by_index_table.putNoClobber(self.base.allocator, local_sym_index, atom); |
| 3692 | const sym_index = try self.allocateSymbol(); |
| 3693 | const atom = try MachO.createEmptyAtom( |
| 3694 | gpa, |
| 3695 | sym_index, |
| 3696 | @sizeOf(u64), |
| 3697 | math.log2(required_alignment), |
| 3698 | ); |
| 3699 | |
| 3700 | try self.managed_atoms.append(gpa, atom); |
| 3701 | try self.atom_by_index_table.putNoClobber(gpa, sym_index, atom); |
| 3913 | 3702 | |
| 3914 | 3703 | const res = try codegen.generateSymbol(&self.base, decl.srcLoc(), typed_value, &code_buffer, .none, .{ |
| 3915 | | .parent_atom_index = local_sym_index, |
| 3704 | .parent_atom_index = sym_index, |
| 3916 | 3705 | }); |
| 3917 | 3706 | const code = switch (res) { |
| 3918 | 3707 | .externally_managed => |x| x, |
| ... | ... | @@ -3926,7 +3715,7 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Modu |
| 3926 | 3715 | }; |
| 3927 | 3716 | |
| 3928 | 3717 | atom.code.clearRetainingCapacity(); |
| 3929 | | try atom.code.appendSlice(self.base.allocator, code); |
| 3718 | try atom.code.appendSlice(gpa, code); |
| 3930 | 3719 | |
| 3931 | 3720 | const match = try self.getMatchingSectionAtom( |
| 3932 | 3721 | atom, |
| ... | ... | @@ -3942,18 +3731,18 @@ pub fn lowerUnnamedConst(self: *MachO, typed_value: TypedValue, decl_index: Modu |
| 3942 | 3731 | |
| 3943 | 3732 | errdefer self.freeAtom(atom, match, true); |
| 3944 | 3733 | |
| 3945 | | const symbol = &self.locals.items[atom.local_sym_index]; |
| 3734 | const symbol = atom.getSymbolPtr(self); |
| 3946 | 3735 | symbol.* = .{ |
| 3947 | 3736 | .n_strx = name_str_index, |
| 3948 | 3737 | .n_type = macho.N_SECT, |
| 3949 | | .n_sect = @intCast(u8, self.section_ordinals.getIndex(match).?) + 1, |
| 3738 | .n_sect = self.getSectionOrdinal(match), |
| 3950 | 3739 | .n_desc = 0, |
| 3951 | 3740 | .n_value = addr, |
| 3952 | 3741 | }; |
| 3953 | 3742 | |
| 3954 | | try unnamed_consts.append(self.base.allocator, atom); |
| 3743 | try unnamed_consts.append(gpa, atom); |
| 3955 | 3744 | |
| 3956 | | return atom.local_sym_index; |
| 3745 | return atom.sym_index; |
| 3957 | 3746 | } |
| 3958 | 3747 | |
| 3959 | 3748 | pub fn updateDecl(self: *MachO, module: *Module, decl_index: Module.Decl.Index) !void { |
| ... | ... | @@ -3995,14 +3784,14 @@ pub fn updateDecl(self: *MachO, module: *Module, decl_index: Module.Decl.Index) |
| 3995 | 3784 | }, &code_buffer, .{ |
| 3996 | 3785 | .dwarf = ds, |
| 3997 | 3786 | }, .{ |
| 3998 | | .parent_atom_index = decl.link.macho.local_sym_index, |
| 3787 | .parent_atom_index = decl.link.macho.sym_index, |
| 3999 | 3788 | }) |
| 4000 | 3789 | else |
| 4001 | 3790 | try codegen.generateSymbol(&self.base, decl.srcLoc(), .{ |
| 4002 | 3791 | .ty = decl.ty, |
| 4003 | 3792 | .val = decl_val, |
| 4004 | 3793 | }, &code_buffer, .none, .{ |
| 4005 | | .parent_atom_index = decl.link.macho.local_sym_index, |
| 3794 | .parent_atom_index = decl.link.macho.sym_index, |
| 4006 | 3795 | }); |
| 4007 | 3796 | |
| 4008 | 3797 | const code = blk: { |
| ... | ... | @@ -4025,14 +3814,14 @@ pub fn updateDecl(self: *MachO, module: *Module, decl_index: Module.Decl.Index) |
| 4025 | 3814 | }, |
| 4026 | 3815 | } |
| 4027 | 3816 | }; |
| 4028 | | const symbol = try self.placeDecl(decl_index, code.len); |
| 3817 | const addr = try self.placeDecl(decl_index, code.len); |
| 4029 | 3818 | |
| 4030 | 3819 | if (decl_state) |*ds| { |
| 4031 | 3820 | try self.d_sym.?.dwarf.commitDeclState( |
| 4032 | 3821 | &self.base, |
| 4033 | 3822 | module, |
| 4034 | 3823 | decl, |
| 4035 | | symbol.n_value, |
| 3824 | addr, |
| 4036 | 3825 | decl.link.macho.size, |
| 4037 | 3826 | ds, |
| 4038 | 3827 | ); |
| ... | ... | @@ -4177,8 +3966,7 @@ fn getMatchingSectionAtom( |
| 4177 | 3966 | .@"align" = align_log_2, |
| 4178 | 3967 | })).?; |
| 4179 | 3968 | }; |
| 4180 | | const seg = self.load_commands.items[match.seg].segment; |
| 4181 | | const sect = seg.sections.items[match.sect]; |
| 3969 | const sect = self.getSection(match); |
| 4182 | 3970 | log.debug(" allocating atom '{s}' in '{s},{s}' ({d},{d})", .{ |
| 4183 | 3971 | name, |
| 4184 | 3972 | sect.segName(), |
| ... | ... | @@ -4189,12 +3977,11 @@ fn getMatchingSectionAtom( |
| 4189 | 3977 | return match; |
| 4190 | 3978 | } |
| 4191 | 3979 | |
| 4192 | | fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !*macho.nlist_64 { |
| 3980 | fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !u64 { |
| 4193 | 3981 | const module = self.base.options.module.?; |
| 4194 | 3982 | const decl = module.declPtr(decl_index); |
| 4195 | 3983 | const required_alignment = decl.getAlignment(self.base.options.target); |
| 4196 | | assert(decl.link.macho.local_sym_index != 0); // Caller forgot to call allocateDeclIndexes() |
| 4197 | | const symbol = &self.locals.items[decl.link.macho.local_sym_index]; |
| 3984 | assert(decl.link.macho.sym_index != 0); // Caller forgot to call allocateDeclIndexes() |
| 4198 | 3985 | |
| 4199 | 3986 | const sym_name = try decl.getFullyQualifiedName(module); |
| 4200 | 3987 | defer self.base.allocator.free(sym_name); |
| ... | ... | @@ -4212,7 +3999,8 @@ fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !*mac |
| 4212 | 3999 | const match = decl_ptr.*.?; |
| 4213 | 4000 | |
| 4214 | 4001 | if (decl.link.macho.size != 0) { |
| 4215 | | const capacity = decl.link.macho.capacity(self.*); |
| 4002 | const symbol = decl.link.macho.getSymbolPtr(self); |
| 4003 | const capacity = decl.link.macho.capacity(self); |
| 4216 | 4004 | const need_realloc = code_len > capacity or !mem.isAlignedGeneric(u64, symbol.n_value, required_alignment); |
| 4217 | 4005 | |
| 4218 | 4006 | if (need_realloc) { |
| ... | ... | @@ -4220,18 +4008,24 @@ fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !*mac |
| 4220 | 4008 | log.debug("growing {s} and moving from 0x{x} to 0x{x}", .{ sym_name, symbol.n_value, vaddr }); |
| 4221 | 4009 | log.debug(" (required alignment 0x{x})", .{required_alignment}); |
| 4222 | 4010 | symbol.n_value = vaddr; |
| 4011 | |
| 4012 | const got_atom = self.getGotAtomForSymbol(.{ |
| 4013 | .sym_index = decl.link.macho.sym_index, |
| 4014 | .file = null, |
| 4015 | }).?; |
| 4016 | got_atom.dirty = true; |
| 4223 | 4017 | } else if (code_len < decl.link.macho.size) { |
| 4224 | 4018 | self.shrinkAtom(&decl.link.macho, code_len, match); |
| 4225 | 4019 | } |
| 4226 | 4020 | decl.link.macho.size = code_len; |
| 4227 | 4021 | decl.link.macho.dirty = true; |
| 4228 | 4022 | |
| 4229 | | symbol.n_strx = try self.makeString(sym_name); |
| 4023 | symbol.n_strx = try self.strtab.insert(self.base.allocator, sym_name); |
| 4230 | 4024 | symbol.n_type = macho.N_SECT; |
| 4231 | 4025 | symbol.n_sect = @intCast(u8, self.text_section_index.?) + 1; |
| 4232 | 4026 | symbol.n_desc = 0; |
| 4233 | 4027 | } else { |
| 4234 | | const name_str_index = try self.makeString(sym_name); |
| 4028 | const name_str_index = try self.strtab.insert(self.base.allocator, sym_name); |
| 4235 | 4029 | const addr = try self.allocateAtom(&decl.link.macho, code_len, required_alignment, match); |
| 4236 | 4030 | |
| 4237 | 4031 | log.debug("allocated atom for {s} at 0x{x}", .{ sym_name, addr }); |
| ... | ... | @@ -4239,28 +4033,22 @@ fn placeDecl(self: *MachO, decl_index: Module.Decl.Index, code_len: usize) !*mac |
| 4239 | 4033 | |
| 4240 | 4034 | errdefer self.freeAtom(&decl.link.macho, match, false); |
| 4241 | 4035 | |
| 4036 | const symbol = decl.link.macho.getSymbolPtr(self); |
| 4242 | 4037 | symbol.* = .{ |
| 4243 | 4038 | .n_strx = name_str_index, |
| 4244 | 4039 | .n_type = macho.N_SECT, |
| 4245 | | .n_sect = @intCast(u8, self.section_ordinals.getIndex(match).?) + 1, |
| 4040 | .n_sect = self.getSectionOrdinal(match), |
| 4246 | 4041 | .n_desc = 0, |
| 4247 | 4042 | .n_value = addr, |
| 4248 | 4043 | }; |
| 4249 | | const got_index = self.got_entries_table.get(.{ .local = decl.link.macho.local_sym_index }).?; |
| 4250 | | const got_atom = self.got_entries.items[got_index].atom; |
| 4251 | | const got_sym = &self.locals.items[got_atom.local_sym_index]; |
| 4252 | | const vaddr = try self.allocateAtom(got_atom, @sizeOf(u64), 8, .{ |
| 4253 | | .seg = self.data_const_segment_cmd_index.?, |
| 4254 | | .sect = self.got_section_index.?, |
| 4255 | | }); |
| 4256 | | got_sym.n_value = vaddr; |
| 4257 | | got_sym.n_sect = @intCast(u8, self.section_ordinals.getIndex(.{ |
| 4258 | | .seg = self.data_const_segment_cmd_index.?, |
| 4259 | | .sect = self.got_section_index.?, |
| 4260 | | }).? + 1); |
| 4044 | |
| 4045 | const got_target = SymbolWithLoc{ .sym_index = decl.link.macho.sym_index, .file = null }; |
| 4046 | const got_index = try self.allocateGotEntry(got_target); |
| 4047 | const got_atom = try self.createGotAtom(got_target); |
| 4048 | self.got_entries.items[got_index].sym_index = got_atom.sym_index; |
| 4261 | 4049 | } |
| 4262 | 4050 | |
| 4263 | | return symbol; |
| 4051 | return decl.link.macho.getSymbol(self).n_value; |
| 4264 | 4052 | } |
| 4265 | 4053 | |
| 4266 | 4054 | pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl: *const Module.Decl) !void { |
| ... | ... | @@ -4280,19 +4068,23 @@ pub fn updateDeclExports( |
| 4280 | 4068 | @panic("Attempted to compile for object format that was disabled by build configuration"); |
| 4281 | 4069 | } |
| 4282 | 4070 | if (build_options.have_llvm) { |
| 4283 | | if (self.llvm_object) |llvm_object| return llvm_object.updateDeclExports(module, decl_index, exports); |
| 4071 | if (self.llvm_object) |llvm_object| |
| 4072 | return llvm_object.updateDeclExports(module, decl_index, exports); |
| 4284 | 4073 | } |
| 4285 | 4074 | const tracy = trace(@src()); |
| 4286 | 4075 | defer tracy.end(); |
| 4287 | 4076 | |
| 4288 | | try self.globals.ensureUnusedCapacity(self.base.allocator, exports.len); |
| 4077 | const gpa = self.base.allocator; |
| 4078 | |
| 4289 | 4079 | const decl = module.declPtr(decl_index); |
| 4290 | | if (decl.link.macho.local_sym_index == 0) return; |
| 4291 | | const decl_sym = &self.locals.items[decl.link.macho.local_sym_index]; |
| 4080 | if (decl.link.macho.sym_index == 0) return; |
| 4081 | const decl_sym = decl.link.macho.getSymbol(self); |
| 4292 | 4082 | |
| 4293 | 4083 | for (exports) |exp| { |
| 4294 | | const exp_name = try std.fmt.allocPrint(self.base.allocator, "_{s}", .{exp.options.name}); |
| 4295 | | defer self.base.allocator.free(exp_name); |
| 4084 | const exp_name = try std.fmt.allocPrint(gpa, "_{s}", .{exp.options.name}); |
| 4085 | defer gpa.free(exp_name); |
| 4086 | |
| 4087 | log.debug("adding new export '{s}'", .{exp_name}); |
| 4296 | 4088 | |
| 4297 | 4089 | if (exp.options.section) |section_name| { |
| 4298 | 4090 | if (!mem.eql(u8, section_name, "__text")) { |
| ... | ... | @@ -4300,7 +4092,7 @@ pub fn updateDeclExports( |
| 4300 | 4092 | module.gpa, |
| 4301 | 4093 | exp, |
| 4302 | 4094 | try Module.ErrorMsg.create( |
| 4303 | | self.base.allocator, |
| 4095 | gpa, |
| 4304 | 4096 | decl.srcLoc(), |
| 4305 | 4097 | "Unimplemented: ExportOptions.section", |
| 4306 | 4098 | .{}, |
| ... | ... | @@ -4315,7 +4107,7 @@ pub fn updateDeclExports( |
| 4315 | 4107 | module.gpa, |
| 4316 | 4108 | exp, |
| 4317 | 4109 | try Module.ErrorMsg.create( |
| 4318 | | self.base.allocator, |
| 4110 | gpa, |
| 4319 | 4111 | decl.srcLoc(), |
| 4320 | 4112 | "Unimplemented: GlobalLinkage.LinkOnce", |
| 4321 | 4113 | .{}, |
| ... | ... | @@ -4324,103 +4116,85 @@ pub fn updateDeclExports( |
| 4324 | 4116 | continue; |
| 4325 | 4117 | } |
| 4326 | 4118 | |
| 4327 | | const is_weak = exp.options.linkage == .Internal or exp.options.linkage == .Weak; |
| 4328 | | const n_strx = try self.makeString(exp_name); |
| 4329 | | if (self.symbol_resolver.getPtr(n_strx)) |resolv| { |
| 4330 | | switch (resolv.where) { |
| 4331 | | .global => { |
| 4332 | | if (resolv.local_sym_index == decl.link.macho.local_sym_index) continue; |
| 4333 | | |
| 4334 | | const sym = &self.globals.items[resolv.where_index]; |
| 4335 | | |
| 4336 | | if (sym.tentative()) { |
| 4337 | | assert(self.tentatives.swapRemove(resolv.where_index)); |
| 4338 | | } else if (!is_weak and !(sym.weakDef() or sym.pext())) { |
| 4339 | | _ = try module.failed_exports.put( |
| 4340 | | module.gpa, |
| 4341 | | exp, |
| 4342 | | try Module.ErrorMsg.create( |
| 4343 | | self.base.allocator, |
| 4344 | | decl.srcLoc(), |
| 4345 | | \\LinkError: symbol '{s}' defined multiple times |
| 4346 | | \\ first definition in '{s}' |
| 4347 | | , |
| 4348 | | .{ exp_name, self.objects.items[resolv.file.?].name }, |
| 4349 | | ), |
| 4350 | | ); |
| 4351 | | continue; |
| 4352 | | } else if (is_weak) continue; // Current symbol is weak, so skip it. |
| 4353 | | |
| 4354 | | // Otherwise, update the resolver and the global symbol. |
| 4355 | | sym.n_type = macho.N_SECT | macho.N_EXT; |
| 4356 | | resolv.local_sym_index = decl.link.macho.local_sym_index; |
| 4357 | | resolv.file = null; |
| 4358 | | exp.link.macho.sym_index = resolv.where_index; |
| 4359 | | |
| 4360 | | continue; |
| 4361 | | }, |
| 4362 | | .undef => { |
| 4363 | | assert(self.unresolved.swapRemove(resolv.where_index)); |
| 4364 | | _ = self.symbol_resolver.remove(n_strx); |
| 4365 | | }, |
| 4366 | | } |
| 4367 | | } |
| 4368 | | |
| 4369 | | var n_type: u8 = macho.N_SECT | macho.N_EXT; |
| 4370 | | var n_desc: u16 = 0; |
| 4119 | const sym_index = exp.link.macho.sym_index orelse blk: { |
| 4120 | const sym_index = try self.allocateSymbol(); |
| 4121 | exp.link.macho.sym_index = sym_index; |
| 4122 | break :blk sym_index; |
| 4123 | }; |
| 4124 | const sym_loc = SymbolWithLoc{ .sym_index = sym_index, .file = null }; |
| 4125 | const sym = self.getSymbolPtr(sym_loc); |
| 4126 | sym.* = .{ |
| 4127 | .n_strx = try self.strtab.insert(gpa, exp_name), |
| 4128 | .n_type = macho.N_SECT | macho.N_EXT, |
| 4129 | .n_sect = self.getSectionOrdinal(.{ |
| 4130 | .seg = self.text_segment_cmd_index.?, |
| 4131 | .sect = self.text_section_index.?, // TODO what if we export a variable? |
| 4132 | }), |
| 4133 | .n_desc = 0, |
| 4134 | .n_value = decl_sym.n_value, |
| 4135 | }; |
| 4371 | 4136 | |
| 4372 | 4137 | switch (exp.options.linkage) { |
| 4373 | 4138 | .Internal => { |
| 4374 | 4139 | // Symbol should be hidden, or in MachO lingo, private extern. |
| 4375 | 4140 | // We should also mark the symbol as Weak: n_desc == N_WEAK_DEF. |
| 4376 | | // TODO work out when to add N_WEAK_REF. |
| 4377 | | n_type |= macho.N_PEXT; |
| 4378 | | n_desc |= macho.N_WEAK_DEF; |
| 4141 | sym.n_type |= macho.N_PEXT; |
| 4142 | sym.n_desc |= macho.N_WEAK_DEF; |
| 4379 | 4143 | }, |
| 4380 | 4144 | .Strong => {}, |
| 4381 | 4145 | .Weak => { |
| 4382 | 4146 | // Weak linkage is specified as part of n_desc field. |
| 4383 | 4147 | // Symbol's n_type is like for a symbol with strong linkage. |
| 4384 | | n_desc |= macho.N_WEAK_DEF; |
| 4148 | sym.n_desc |= macho.N_WEAK_DEF; |
| 4385 | 4149 | }, |
| 4386 | 4150 | else => unreachable, |
| 4387 | 4151 | } |
| 4388 | 4152 | |
| 4389 | | const global_sym_index = if (exp.link.macho.sym_index) |i| i else blk: { |
| 4390 | | const i = if (self.globals_free_list.popOrNull()) |i| i else inner: { |
| 4391 | | _ = self.globals.addOneAssumeCapacity(); |
| 4392 | | break :inner @intCast(u32, self.globals.items.len - 1); |
| 4393 | | }; |
| 4394 | | break :blk i; |
| 4395 | | }; |
| 4396 | | const sym = &self.globals.items[global_sym_index]; |
| 4397 | | sym.* = .{ |
| 4398 | | .n_strx = try self.makeString(exp_name), |
| 4399 | | .n_type = n_type, |
| 4400 | | .n_sect = @intCast(u8, self.text_section_index.?) + 1, |
| 4401 | | .n_desc = n_desc, |
| 4402 | | .n_value = decl_sym.n_value, |
| 4153 | self.resolveGlobalSymbol(sym_loc) catch |err| switch (err) { |
| 4154 | error.MultipleSymbolDefinitions => { |
| 4155 | const global = self.globals.get(exp_name).?; |
| 4156 | if (sym_loc.sym_index != global.sym_index and global.file != null) { |
| 4157 | _ = try module.failed_exports.put(module.gpa, exp, try Module.ErrorMsg.create( |
| 4158 | gpa, |
| 4159 | decl.srcLoc(), |
| 4160 | \\LinkError: symbol '{s}' defined multiple times |
| 4161 | \\ first definition in '{s}' |
| 4162 | , |
| 4163 | .{ exp_name, self.objects.items[global.file.?].name }, |
| 4164 | )); |
| 4165 | } |
| 4166 | }, |
| 4167 | else => |e| return e, |
| 4403 | 4168 | }; |
| 4404 | | exp.link.macho.sym_index = global_sym_index; |
| 4405 | | |
| 4406 | | try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{ |
| 4407 | | .where = .global, |
| 4408 | | .where_index = global_sym_index, |
| 4409 | | .local_sym_index = decl.link.macho.local_sym_index, |
| 4410 | | }); |
| 4411 | 4169 | } |
| 4412 | 4170 | } |
| 4413 | 4171 | |
| 4414 | 4172 | pub fn deleteExport(self: *MachO, exp: Export) void { |
| 4415 | 4173 | if (self.llvm_object) |_| return; |
| 4416 | 4174 | const sym_index = exp.sym_index orelse return; |
| 4417 | | self.globals_free_list.append(self.base.allocator, sym_index) catch {}; |
| 4418 | | const global = &self.globals.items[sym_index]; |
| 4419 | | log.debug("deleting export '{s}': {}", .{ self.getString(global.n_strx), global }); |
| 4420 | | assert(self.symbol_resolver.remove(global.n_strx)); |
| 4421 | | global.n_type = 0; |
| 4422 | | global.n_strx = 0; |
| 4423 | | global.n_value = 0; |
| 4175 | |
| 4176 | const gpa = self.base.allocator; |
| 4177 | |
| 4178 | const sym_loc = SymbolWithLoc{ .sym_index = sym_index, .file = null }; |
| 4179 | const sym = self.getSymbolPtr(sym_loc); |
| 4180 | const sym_name = self.getSymbolName(sym_loc); |
| 4181 | log.debug("deleting export '{s}'", .{sym_name}); |
| 4182 | assert(sym.sect() and sym.ext()); |
| 4183 | sym.* = .{ |
| 4184 | .n_strx = 0, |
| 4185 | .n_type = 0, |
| 4186 | .n_sect = 0, |
| 4187 | .n_desc = 0, |
| 4188 | .n_value = 0, |
| 4189 | }; |
| 4190 | self.locals_free_list.append(gpa, sym_index) catch {}; |
| 4191 | |
| 4192 | if (self.globals.get(sym_name)) |global| blk: { |
| 4193 | if (global.sym_index != sym_index) break :blk; |
| 4194 | if (global.file != null) break :blk; |
| 4195 | const kv = self.globals.fetchSwapRemove(sym_name); |
| 4196 | gpa.free(kv.?.key); |
| 4197 | } |
| 4424 | 4198 | } |
| 4425 | 4199 | |
| 4426 | 4200 | fn freeUnnamedConsts(self: *MachO, decl_index: Module.Decl.Index) void { |
| ... | ... | @@ -4430,11 +4204,11 @@ fn freeUnnamedConsts(self: *MachO, decl_index: Module.Decl.Index) void { |
| 4430 | 4204 | .seg = self.text_segment_cmd_index.?, |
| 4431 | 4205 | .sect = self.text_const_section_index.?, |
| 4432 | 4206 | }, true); |
| 4433 | | self.locals_free_list.append(self.base.allocator, atom.local_sym_index) catch {}; |
| 4434 | | self.locals.items[atom.local_sym_index].n_type = 0; |
| 4435 | | _ = self.atom_by_index_table.remove(atom.local_sym_index); |
| 4436 | | log.debug(" adding local symbol index {d} to free list", .{atom.local_sym_index}); |
| 4437 | | atom.local_sym_index = 0; |
| 4207 | self.locals_free_list.append(self.base.allocator, atom.sym_index) catch {}; |
| 4208 | self.locals.items[atom.sym_index].n_type = 0; |
| 4209 | _ = self.atom_by_index_table.remove(atom.sym_index); |
| 4210 | log.debug(" adding local symbol index {d} to free list", .{atom.sym_index}); |
| 4211 | atom.sym_index = 0; |
| 4438 | 4212 | } |
| 4439 | 4213 | unnamed_consts.clearAndFree(self.base.allocator); |
| 4440 | 4214 | } |
| ... | ... | @@ -4452,29 +4226,33 @@ pub fn freeDecl(self: *MachO, decl_index: Module.Decl.Index) void { |
| 4452 | 4226 | self.freeUnnamedConsts(decl_index); |
| 4453 | 4227 | } |
| 4454 | 4228 | // Appending to free lists is allowed to fail because the free lists are heuristics based anyway. |
| 4455 | | if (decl.link.macho.local_sym_index != 0) { |
| 4456 | | self.locals_free_list.append(self.base.allocator, decl.link.macho.local_sym_index) catch {}; |
| 4229 | if (decl.link.macho.sym_index != 0) { |
| 4230 | self.locals_free_list.append(self.base.allocator, decl.link.macho.sym_index) catch {}; |
| 4457 | 4231 | |
| 4458 | 4232 | // Try freeing GOT atom if this decl had one |
| 4459 | | if (self.got_entries_table.get(.{ .local = decl.link.macho.local_sym_index })) |got_index| { |
| 4233 | const got_target = SymbolWithLoc{ .sym_index = decl.link.macho.sym_index, .file = null }; |
| 4234 | if (self.got_entries_table.get(got_target)) |got_index| { |
| 4460 | 4235 | self.got_entries_free_list.append(self.base.allocator, @intCast(u32, got_index)) catch {}; |
| 4461 | | self.got_entries.items[got_index] = .{ .target = .{ .local = 0 }, .atom = undefined }; |
| 4462 | | _ = self.got_entries_table.swapRemove(.{ .local = decl.link.macho.local_sym_index }); |
| 4236 | self.got_entries.items[got_index] = .{ |
| 4237 | .target = .{ .sym_index = 0, .file = null }, |
| 4238 | .sym_index = 0, |
| 4239 | }; |
| 4240 | _ = self.got_entries_table.remove(got_target); |
| 4463 | 4241 | |
| 4464 | 4242 | if (self.d_sym) |*d_sym| { |
| 4465 | | d_sym.swapRemoveRelocs(decl.link.macho.local_sym_index); |
| 4243 | d_sym.swapRemoveRelocs(decl.link.macho.sym_index); |
| 4466 | 4244 | } |
| 4467 | 4245 | |
| 4468 | 4246 | log.debug(" adding GOT index {d} to free list (target local@{d})", .{ |
| 4469 | 4247 | got_index, |
| 4470 | | decl.link.macho.local_sym_index, |
| 4248 | decl.link.macho.sym_index, |
| 4471 | 4249 | }); |
| 4472 | 4250 | } |
| 4473 | 4251 | |
| 4474 | | self.locals.items[decl.link.macho.local_sym_index].n_type = 0; |
| 4475 | | _ = self.atom_by_index_table.remove(decl.link.macho.local_sym_index); |
| 4476 | | log.debug(" adding local symbol index {d} to free list", .{decl.link.macho.local_sym_index}); |
| 4477 | | decl.link.macho.local_sym_index = 0; |
| 4252 | self.locals.items[decl.link.macho.sym_index].n_type = 0; |
| 4253 | _ = self.atom_by_index_table.remove(decl.link.macho.sym_index); |
| 4254 | log.debug(" adding local symbol index {d} to free list", .{decl.link.macho.sym_index}); |
| 4255 | decl.link.macho.sym_index = 0; |
| 4478 | 4256 | } |
| 4479 | 4257 | if (self.d_sym) |*d_sym| { |
| 4480 | 4258 | d_sym.dwarf.freeDecl(decl); |
| ... | ... | @@ -4486,12 +4264,12 @@ pub fn getDeclVAddr(self: *MachO, decl_index: Module.Decl.Index, reloc_info: Fil |
| 4486 | 4264 | const decl = mod.declPtr(decl_index); |
| 4487 | 4265 | |
| 4488 | 4266 | assert(self.llvm_object == null); |
| 4489 | | assert(decl.link.macho.local_sym_index != 0); |
| 4267 | assert(decl.link.macho.sym_index != 0); |
| 4490 | 4268 | |
| 4491 | 4269 | const atom = self.atom_by_index_table.get(reloc_info.parent_atom_index).?; |
| 4492 | 4270 | try atom.relocs.append(self.base.allocator, .{ |
| 4493 | 4271 | .offset = @intCast(u32, reloc_info.offset), |
| 4494 | | .target = .{ .local = decl.link.macho.local_sym_index }, |
| 4272 | .target = .{ .sym_index = decl.link.macho.sym_index, .file = null }, |
| 4495 | 4273 | .addend = reloc_info.addend, |
| 4496 | 4274 | .subtractor = null, |
| 4497 | 4275 | .pcrel = false, |
| ... | ... | @@ -4534,7 +4312,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4534 | 4312 | |
| 4535 | 4313 | if (self.text_segment_cmd_index == null) { |
| 4536 | 4314 | self.text_segment_cmd_index = @intCast(u16, self.load_commands.items.len); |
| 4537 | | const needed_size = if (self.needs_prealloc) blk: { |
| 4315 | const needed_size = if (self.mode == .incremental) blk: { |
| 4538 | 4316 | const headerpad_size = @maximum(self.base.options.headerpad_size orelse 0, default_headerpad_size); |
| 4539 | 4317 | const program_code_size_hint = self.base.options.program_code_size_hint; |
| 4540 | 4318 | const got_size_hint = @sizeOf(u64) * self.base.options.symbol_count_hint; |
| ... | ... | @@ -4565,7 +4343,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4565 | 4343 | .aarch64 => 2, |
| 4566 | 4344 | else => unreachable, // unhandled architecture type |
| 4567 | 4345 | }; |
| 4568 | | const needed_size = if (self.needs_prealloc) self.base.options.program_code_size_hint else 0; |
| 4346 | const needed_size = if (self.mode == .incremental) self.base.options.program_code_size_hint else 0; |
| 4569 | 4347 | self.text_section_index = try self.initSection( |
| 4570 | 4348 | self.text_segment_cmd_index.?, |
| 4571 | 4349 | "__text", |
| ... | ... | @@ -4588,7 +4366,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4588 | 4366 | .aarch64 => 3 * @sizeOf(u32), |
| 4589 | 4367 | else => unreachable, // unhandled architecture type |
| 4590 | 4368 | }; |
| 4591 | | const needed_size = if (self.needs_prealloc) stub_size * self.base.options.symbol_count_hint else 0; |
| 4369 | const needed_size = if (self.mode == .incremental) stub_size * self.base.options.symbol_count_hint else 0; |
| 4592 | 4370 | self.stubs_section_index = try self.initSection( |
| 4593 | 4371 | self.text_segment_cmd_index.?, |
| 4594 | 4372 | "__stubs", |
| ... | ... | @@ -4617,7 +4395,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4617 | 4395 | .aarch64 => 3 * @sizeOf(u32), |
| 4618 | 4396 | else => unreachable, |
| 4619 | 4397 | }; |
| 4620 | | const needed_size = if (self.needs_prealloc) |
| 4398 | const needed_size = if (self.mode == .incremental) |
| 4621 | 4399 | stub_size * self.base.options.symbol_count_hint + preamble_size |
| 4622 | 4400 | else |
| 4623 | 4401 | 0; |
| ... | ... | @@ -4637,7 +4415,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4637 | 4415 | var vmaddr: u64 = 0; |
| 4638 | 4416 | var fileoff: u64 = 0; |
| 4639 | 4417 | var needed_size: u64 = 0; |
| 4640 | | if (self.needs_prealloc) { |
| 4418 | if (self.mode == .incremental) { |
| 4641 | 4419 | const base = self.getSegmentAllocBase(&.{self.text_segment_cmd_index.?}); |
| 4642 | 4420 | vmaddr = base.vmaddr; |
| 4643 | 4421 | fileoff = base.fileoff; |
| ... | ... | @@ -4666,7 +4444,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4666 | 4444 | } |
| 4667 | 4445 | |
| 4668 | 4446 | if (self.got_section_index == null) { |
| 4669 | | const needed_size = if (self.needs_prealloc) |
| 4447 | const needed_size = if (self.mode == .incremental) |
| 4670 | 4448 | @sizeOf(u64) * self.base.options.symbol_count_hint |
| 4671 | 4449 | else |
| 4672 | 4450 | 0; |
| ... | ... | @@ -4687,7 +4465,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4687 | 4465 | var vmaddr: u64 = 0; |
| 4688 | 4466 | var fileoff: u64 = 0; |
| 4689 | 4467 | var needed_size: u64 = 0; |
| 4690 | | if (self.needs_prealloc) { |
| 4468 | if (self.mode == .incremental) { |
| 4691 | 4469 | const base = self.getSegmentAllocBase(&.{self.data_const_segment_cmd_index.?}); |
| 4692 | 4470 | vmaddr = base.vmaddr; |
| 4693 | 4471 | fileoff = base.fileoff; |
| ... | ... | @@ -4716,7 +4494,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4716 | 4494 | } |
| 4717 | 4495 | |
| 4718 | 4496 | if (self.la_symbol_ptr_section_index == null) { |
| 4719 | | const needed_size = if (self.needs_prealloc) |
| 4497 | const needed_size = if (self.mode == .incremental) |
| 4720 | 4498 | @sizeOf(u64) * self.base.options.symbol_count_hint |
| 4721 | 4499 | else |
| 4722 | 4500 | 0; |
| ... | ... | @@ -4733,7 +4511,10 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4733 | 4511 | } |
| 4734 | 4512 | |
| 4735 | 4513 | if (self.data_section_index == null) { |
| 4736 | | const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0; |
| 4514 | const needed_size = if (self.mode == .incremental) |
| 4515 | @sizeOf(u64) * self.base.options.symbol_count_hint |
| 4516 | else |
| 4517 | 0; |
| 4737 | 4518 | const alignment: u16 = 3; // 2^3 = @sizeOf(u64) |
| 4738 | 4519 | self.data_section_index = try self.initSection( |
| 4739 | 4520 | self.data_segment_cmd_index.?, |
| ... | ... | @@ -4745,7 +4526,10 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4745 | 4526 | } |
| 4746 | 4527 | |
| 4747 | 4528 | if (self.tlv_section_index == null) { |
| 4748 | | const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0; |
| 4529 | const needed_size = if (self.mode == .incremental) |
| 4530 | @sizeOf(u64) * self.base.options.symbol_count_hint |
| 4531 | else |
| 4532 | 0; |
| 4749 | 4533 | const alignment: u16 = 3; // 2^3 = @sizeOf(u64) |
| 4750 | 4534 | self.tlv_section_index = try self.initSection( |
| 4751 | 4535 | self.data_segment_cmd_index.?, |
| ... | ... | @@ -4759,7 +4543,10 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4759 | 4543 | } |
| 4760 | 4544 | |
| 4761 | 4545 | if (self.tlv_data_section_index == null) { |
| 4762 | | const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0; |
| 4546 | const needed_size = if (self.mode == .incremental) |
| 4547 | @sizeOf(u64) * self.base.options.symbol_count_hint |
| 4548 | else |
| 4549 | 0; |
| 4763 | 4550 | const alignment: u16 = 3; // 2^3 = @sizeOf(u64) |
| 4764 | 4551 | self.tlv_data_section_index = try self.initSection( |
| 4765 | 4552 | self.data_segment_cmd_index.?, |
| ... | ... | @@ -4773,7 +4560,10 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4773 | 4560 | } |
| 4774 | 4561 | |
| 4775 | 4562 | if (self.tlv_bss_section_index == null) { |
| 4776 | | const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0; |
| 4563 | const needed_size = if (self.mode == .incremental) |
| 4564 | @sizeOf(u64) * self.base.options.symbol_count_hint |
| 4565 | else |
| 4566 | 0; |
| 4777 | 4567 | const alignment: u16 = 3; // 2^3 = @sizeOf(u64) |
| 4778 | 4568 | self.tlv_bss_section_index = try self.initSection( |
| 4779 | 4569 | self.data_segment_cmd_index.?, |
| ... | ... | @@ -4787,7 +4577,10 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4787 | 4577 | } |
| 4788 | 4578 | |
| 4789 | 4579 | if (self.bss_section_index == null) { |
| 4790 | | const needed_size = if (self.needs_prealloc) @sizeOf(u64) * self.base.options.symbol_count_hint else 0; |
| 4580 | const needed_size = if (self.mode == .incremental) |
| 4581 | @sizeOf(u64) * self.base.options.symbol_count_hint |
| 4582 | else |
| 4583 | 0; |
| 4791 | 4584 | const alignment: u16 = 3; // 2^3 = @sizeOf(u64) |
| 4792 | 4585 | self.bss_section_index = try self.initSection( |
| 4793 | 4586 | self.data_segment_cmd_index.?, |
| ... | ... | @@ -4804,7 +4597,7 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 4804 | 4597 | self.linkedit_segment_cmd_index = @intCast(u16, self.load_commands.items.len); |
| 4805 | 4598 | var vmaddr: u64 = 0; |
| 4806 | 4599 | var fileoff: u64 = 0; |
| 4807 | | if (self.needs_prealloc) { |
| 4600 | if (self.mode == .incremental) { |
| 4808 | 4601 | const base = self.getSegmentAllocBase(&.{self.data_segment_cmd_index.?}); |
| 4809 | 4602 | vmaddr = base.vmaddr; |
| 4810 | 4603 | fileoff = base.fileoff; |
| ... | ... | @@ -5028,8 +4821,6 @@ fn populateMissingMetadata(self: *MachO) !void { |
| 5028 | 4821 | }); |
| 5029 | 4822 | self.load_commands_dirty = true; |
| 5030 | 4823 | } |
| 5031 | | |
| 5032 | | self.cold_start = true; |
| 5033 | 4824 | } |
| 5034 | 4825 | |
| 5035 | 4826 | fn calcMinHeaderpad(self: *MachO) u64 { |
| ... | ... | @@ -5130,7 +4921,7 @@ fn allocateSegment(self: *MachO, maybe_index: ?u16, indices: []const ?u16, init_ |
| 5130 | 4921 | |
| 5131 | 4922 | // Allocate the sections according to their alignment at the beginning of the segment. |
| 5132 | 4923 | var start = init_size; |
| 5133 | | for (seg.sections.items) |*sect, sect_id| { |
| 4924 | for (seg.sections.items) |*sect| { |
| 5134 | 4925 | const is_zerofill = sect.flags == macho.S_ZEROFILL or sect.flags == macho.S_THREAD_LOCAL_ZEROFILL; |
| 5135 | 4926 | const use_llvm = build_options.have_llvm and self.base.options.use_llvm; |
| 5136 | 4927 | const use_stage1 = build_options.is_stage1 and self.base.options.use_stage1; |
| ... | ... | @@ -5138,32 +4929,12 @@ fn allocateSegment(self: *MachO, maybe_index: ?u16, indices: []const ?u16, init_ |
| 5138 | 4929 | const start_aligned = mem.alignForwardGeneric(u64, start, alignment); |
| 5139 | 4930 | |
| 5140 | 4931 | // TODO handle zerofill sections in stage2 |
| 5141 | | sect.offset = if (is_zerofill and (use_stage1 or use_llvm)) 0 else @intCast(u32, seg.inner.fileoff + start_aligned); |
| 4932 | sect.offset = if (is_zerofill and (use_stage1 or use_llvm)) |
| 4933 | 0 |
| 4934 | else |
| 4935 | @intCast(u32, seg.inner.fileoff + start_aligned); |
| 5142 | 4936 | sect.addr = seg.inner.vmaddr + start_aligned; |
| 5143 | 4937 | |
| 5144 | | // Recalculate section size given the allocated start address |
| 5145 | | sect.size = if (self.atoms.get(.{ |
| 5146 | | .seg = index, |
| 5147 | | .sect = @intCast(u16, sect_id), |
| 5148 | | })) |last_atom| blk: { |
| 5149 | | var atom = last_atom; |
| 5150 | | while (atom.prev) |prev| { |
| 5151 | | atom = prev; |
| 5152 | | } |
| 5153 | | |
| 5154 | | var base_addr = sect.addr; |
| 5155 | | |
| 5156 | | while (true) { |
| 5157 | | const atom_alignment = try math.powi(u32, 2, atom.alignment); |
| 5158 | | base_addr = mem.alignForwardGeneric(u64, base_addr, atom_alignment) + atom.size; |
| 5159 | | if (atom.next) |next| { |
| 5160 | | atom = next; |
| 5161 | | } else break; |
| 5162 | | } |
| 5163 | | |
| 5164 | | break :blk base_addr - sect.addr; |
| 5165 | | } else 0; |
| 5166 | | |
| 5167 | 4938 | start = start_aligned + sect.size; |
| 5168 | 4939 | |
| 5169 | 4940 | if (!(is_zerofill and (use_stage1 or use_llvm))) { |
| ... | ... | @@ -5194,14 +4965,14 @@ fn initSection( |
| 5194 | 4965 | var sect = macho.section_64{ |
| 5195 | 4966 | .sectname = makeStaticString(sectname), |
| 5196 | 4967 | .segname = seg.inner.segname, |
| 5197 | | .size = if (self.needs_prealloc) @intCast(u32, size) else 0, |
| 4968 | .size = if (self.mode == .incremental) @intCast(u32, size) else 0, |
| 5198 | 4969 | .@"align" = alignment, |
| 5199 | 4970 | .flags = opts.flags, |
| 5200 | 4971 | .reserved1 = opts.reserved1, |
| 5201 | 4972 | .reserved2 = opts.reserved2, |
| 5202 | 4973 | }; |
| 5203 | 4974 | |
| 5204 | | if (self.needs_prealloc) { |
| 4975 | if (self.mode == .incremental) { |
| 5205 | 4976 | const alignment_pow_2 = try math.powi(u32, 2, alignment); |
| 5206 | 4977 | const padding: ?u32 = if (segment_id == self.text_segment_cmd_index.?) |
| 5207 | 4978 | @maximum(self.base.options.headerpad_size orelse 0, default_headerpad_size) |
| ... | ... | @@ -5419,12 +5190,30 @@ fn getSectionMaxAlignment(self: *MachO, segment_id: u16, start_sect_id: u16) !u3 |
| 5419 | 5190 | return max_alignment; |
| 5420 | 5191 | } |
| 5421 | 5192 | |
| 5422 | | fn allocateAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, match: MatchingSection) !u64 { |
| 5193 | fn allocateAtomCommon(self: *MachO, atom: *Atom, match: MatchingSection) !void { |
| 5194 | const sym = atom.getSymbolPtr(self); |
| 5195 | if (self.mode == .incremental) { |
| 5196 | const size = atom.size; |
| 5197 | const alignment = try math.powi(u32, 2, atom.alignment); |
| 5198 | const vaddr = try self.allocateAtom(atom, size, alignment, match); |
| 5199 | const sym_name = atom.getName(self); |
| 5200 | log.debug("allocated {s} atom at 0x{x}", .{ sym_name, vaddr }); |
| 5201 | sym.n_value = vaddr; |
| 5202 | } else try self.addAtomToSection(atom, match); |
| 5203 | sym.n_sect = self.getSectionOrdinal(match); |
| 5204 | } |
| 5205 | |
| 5206 | fn allocateAtom( |
| 5207 | self: *MachO, |
| 5208 | atom: *Atom, |
| 5209 | new_atom_size: u64, |
| 5210 | alignment: u64, |
| 5211 | match: MatchingSection, |
| 5212 | ) !u64 { |
| 5423 | 5213 | const tracy = trace(@src()); |
| 5424 | 5214 | defer tracy.end(); |
| 5425 | 5215 | |
| 5426 | | const seg = &self.load_commands.items[match.seg].segment; |
| 5427 | | const sect = &seg.sections.items[match.sect]; |
| 5216 | const sect = self.getSectionPtr(match); |
| 5428 | 5217 | var free_list = self.atom_free_lists.get(match).?; |
| 5429 | 5218 | const needs_padding = match.seg == self.text_segment_cmd_index.? and match.sect == self.text_section_index.?; |
| 5430 | 5219 | const new_atom_ideal_capacity = if (needs_padding) padToIdeal(new_atom_size) else new_atom_size; |
| ... | ... | @@ -5445,8 +5234,8 @@ fn allocateAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, m |
| 5445 | 5234 | const big_atom = free_list.items[i]; |
| 5446 | 5235 | // We now have a pointer to a live atom that has too much capacity. |
| 5447 | 5236 | // Is it enough that we could fit this new atom? |
| 5448 | | const sym = self.locals.items[big_atom.local_sym_index]; |
| 5449 | | const capacity = big_atom.capacity(self.*); |
| 5237 | const sym = big_atom.getSymbol(self); |
| 5238 | const capacity = big_atom.capacity(self); |
| 5450 | 5239 | const ideal_capacity = if (needs_padding) padToIdeal(capacity) else capacity; |
| 5451 | 5240 | const ideal_capacity_end_vaddr = math.add(u64, sym.n_value, ideal_capacity) catch ideal_capacity; |
| 5452 | 5241 | const capacity_end_vaddr = sym.n_value + capacity; |
| ... | ... | @@ -5456,7 +5245,7 @@ fn allocateAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, m |
| 5456 | 5245 | // Additional bookkeeping here to notice if this free list node |
| 5457 | 5246 | // should be deleted because the atom that it points to has grown to take up |
| 5458 | 5247 | // more of the extra capacity. |
| 5459 | | if (!big_atom.freeListEligible(self.*)) { |
| 5248 | if (!big_atom.freeListEligible(self)) { |
| 5460 | 5249 | _ = free_list.swapRemove(i); |
| 5461 | 5250 | } else { |
| 5462 | 5251 | i += 1; |
| ... | ... | @@ -5476,7 +5265,7 @@ fn allocateAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, m |
| 5476 | 5265 | } |
| 5477 | 5266 | break :blk new_start_vaddr; |
| 5478 | 5267 | } else if (self.atoms.get(match)) |last| { |
| 5479 | | const last_symbol = self.locals.items[last.local_sym_index]; |
| 5268 | const last_symbol = last.getSymbol(self); |
| 5480 | 5269 | const ideal_capacity = if (needs_padding) padToIdeal(last.size) else last.size; |
| 5481 | 5270 | const ideal_capacity_end_vaddr = last_symbol.n_value + ideal_capacity; |
| 5482 | 5271 | const new_start_vaddr = mem.alignForwardGeneric(u64, ideal_capacity_end_vaddr, alignment); |
| ... | ... | @@ -5525,7 +5314,7 @@ fn allocateAtom(self: *MachO, atom: *Atom, new_atom_size: u64, alignment: u64, m |
| 5525 | 5314 | return vaddr; |
| 5526 | 5315 | } |
| 5527 | 5316 | |
| 5528 | | fn addAtomToSection(self: *MachO, atom: *Atom, match: MatchingSection) !void { |
| 5317 | pub fn addAtomToSection(self: *MachO, atom: *Atom, match: MatchingSection) !void { |
| 5529 | 5318 | if (self.atoms.getPtr(match)) |last| { |
| 5530 | 5319 | last.*.next = atom; |
| 5531 | 5320 | atom.prev = last.*; |
| ... | ... | @@ -5533,34 +5322,42 @@ fn addAtomToSection(self: *MachO, atom: *Atom, match: MatchingSection) !void { |
| 5533 | 5322 | } else { |
| 5534 | 5323 | try self.atoms.putNoClobber(self.base.allocator, match, atom); |
| 5535 | 5324 | } |
| 5536 | | const seg = &self.load_commands.items[match.seg].segment; |
| 5537 | | const sect = &seg.sections.items[match.sect]; |
| 5538 | | sect.size += atom.size; |
| 5325 | const sect = self.getSectionPtr(match); |
| 5326 | const atom_alignment = try math.powi(u32, 2, atom.alignment); |
| 5327 | const aligned_end_addr = mem.alignForwardGeneric(u64, sect.size, atom_alignment); |
| 5328 | const padding = aligned_end_addr - sect.size; |
| 5329 | sect.size += padding + atom.size; |
| 5330 | sect.@"align" = @maximum(sect.@"align", atom.alignment); |
| 5539 | 5331 | } |
| 5540 | 5332 | |
| 5541 | 5333 | pub fn getGlobalSymbol(self: *MachO, name: []const u8) !u32 { |
| 5542 | | const sym_name = try std.fmt.allocPrint(self.base.allocator, "_{s}", .{name}); |
| 5543 | | defer self.base.allocator.free(sym_name); |
| 5544 | | const n_strx = try self.makeString(sym_name); |
| 5545 | | |
| 5546 | | if (!self.symbol_resolver.contains(n_strx)) { |
| 5547 | | log.debug("adding new extern function '{s}'", .{sym_name}); |
| 5548 | | const sym_index = @intCast(u32, self.undefs.items.len); |
| 5549 | | try self.undefs.append(self.base.allocator, .{ |
| 5550 | | .n_strx = n_strx, |
| 5551 | | .n_type = macho.N_UNDF, |
| 5552 | | .n_sect = 0, |
| 5553 | | .n_desc = 0, |
| 5554 | | .n_value = 0, |
| 5555 | | }); |
| 5556 | | try self.symbol_resolver.putNoClobber(self.base.allocator, n_strx, .{ |
| 5557 | | .where = .undef, |
| 5558 | | .where_index = sym_index, |
| 5559 | | }); |
| 5560 | | try self.unresolved.putNoClobber(self.base.allocator, sym_index, .stub); |
| 5334 | const gpa = self.base.allocator; |
| 5335 | const sym_name = try std.fmt.allocPrint(gpa, "_{s}", .{name}); |
| 5336 | const global_index = @intCast(u32, self.globals.values().len); |
| 5337 | const gop = try self.globals.getOrPut(gpa, sym_name); |
| 5338 | defer if (gop.found_existing) gpa.free(sym_name); |
| 5339 | |
| 5340 | if (gop.found_existing) { |
| 5341 | // TODO audit this: can we ever reference anything from outside the Zig module? |
| 5342 | assert(gop.value_ptr.file == null); |
| 5343 | return gop.value_ptr.sym_index; |
| 5561 | 5344 | } |
| 5562 | 5345 | |
| 5563 | | return n_strx; |
| 5346 | const sym_index = @intCast(u32, self.locals.items.len); |
| 5347 | try self.locals.append(gpa, .{ |
| 5348 | .n_strx = try self.strtab.insert(gpa, sym_name), |
| 5349 | .n_type = macho.N_UNDF, |
| 5350 | .n_sect = 0, |
| 5351 | .n_desc = 0, |
| 5352 | .n_value = 0, |
| 5353 | }); |
| 5354 | gop.value_ptr.* = .{ |
| 5355 | .sym_index = sym_index, |
| 5356 | .file = null, |
| 5357 | }; |
| 5358 | try self.unresolved.putNoClobber(gpa, global_index, true); |
| 5359 | |
| 5360 | return sym_index; |
| 5564 | 5361 | } |
| 5565 | 5362 | |
| 5566 | 5363 | fn getSegmentAllocBase(self: MachO, indices: []const ?u16) struct { vmaddr: u64, fileoff: u64 } { |
| ... | ... | @@ -5588,7 +5385,7 @@ fn pruneAndSortSectionsInSegment(self: *MachO, maybe_seg_id: *?u16, indices: []* |
| 5588 | 5385 | |
| 5589 | 5386 | for (indices) |maybe_index| { |
| 5590 | 5387 | const old_idx = maybe_index.* orelse continue; |
| 5591 | | const sect = sections[old_idx]; |
| 5388 | const sect = &sections[old_idx]; |
| 5592 | 5389 | if (sect.size == 0) { |
| 5593 | 5390 | log.debug("pruning section {s},{s}", .{ sect.segName(), sect.sectName() }); |
| 5594 | 5391 | maybe_index.* = null; |
| ... | ... | @@ -5596,7 +5393,7 @@ fn pruneAndSortSectionsInSegment(self: *MachO, maybe_seg_id: *?u16, indices: []* |
| 5596 | 5393 | seg.inner.nsects -= 1; |
| 5597 | 5394 | } else { |
| 5598 | 5395 | maybe_index.* = @intCast(u16, seg.sections.items.len); |
| 5599 | | seg.sections.appendAssumeCapacity(sect); |
| 5396 | seg.sections.appendAssumeCapacity(sect.*); |
| 5600 | 5397 | } |
| 5601 | 5398 | try mapping.putNoClobber(old_idx, maybe_index.*); |
| 5602 | 5399 | } |
| ... | ... | @@ -5711,7 +5508,11 @@ fn updateSectionOrdinals(self: *MachO) !void { |
| 5711 | 5508 | const tracy = trace(@src()); |
| 5712 | 5509 | defer tracy.end(); |
| 5713 | 5510 | |
| 5714 | | var ordinal_remap = std.AutoHashMap(u8, u8).init(self.base.allocator); |
| 5511 | log.debug("updating section ordinals", .{}); |
| 5512 | |
| 5513 | const gpa = self.base.allocator; |
| 5514 | |
| 5515 | var ordinal_remap = std.AutoHashMap(u8, u8).init(gpa); |
| 5715 | 5516 | defer ordinal_remap.deinit(); |
| 5716 | 5517 | var ordinals: std.AutoArrayHashMapUnmanaged(MatchingSection, void) = .{}; |
| 5717 | 5518 | |
| ... | ... | @@ -5723,27 +5524,40 @@ fn updateSectionOrdinals(self: *MachO) !void { |
| 5723 | 5524 | }) |maybe_index| { |
| 5724 | 5525 | const index = maybe_index orelse continue; |
| 5725 | 5526 | const seg = self.load_commands.items[index].segment; |
| 5726 | | for (seg.sections.items) |_, sect_id| { |
| 5527 | for (seg.sections.items) |sect, sect_id| { |
| 5727 | 5528 | const match = MatchingSection{ |
| 5728 | 5529 | .seg = @intCast(u16, index), |
| 5729 | 5530 | .sect = @intCast(u16, sect_id), |
| 5730 | 5531 | }; |
| 5731 | | const old_ordinal = @intCast(u8, self.section_ordinals.getIndex(match).? + 1); |
| 5532 | const old_ordinal = self.getSectionOrdinal(match); |
| 5732 | 5533 | new_ordinal += 1; |
| 5534 | log.debug("'{s},{s}': sect({d}, '_,_') => sect({d}, '_,_')", .{ |
| 5535 | sect.segName(), |
| 5536 | sect.sectName(), |
| 5537 | old_ordinal, |
| 5538 | new_ordinal, |
| 5539 | }); |
| 5733 | 5540 | try ordinal_remap.putNoClobber(old_ordinal, new_ordinal); |
| 5734 | | try ordinals.putNoClobber(self.base.allocator, match, {}); |
| 5541 | try ordinals.putNoClobber(gpa, match, {}); |
| 5735 | 5542 | } |
| 5736 | 5543 | } |
| 5737 | 5544 | |
| 5545 | // FIXME Jakub |
| 5546 | // TODO no need for duping work here; simply walk the atom graph |
| 5738 | 5547 | for (self.locals.items) |*sym| { |
| 5548 | if (sym.undf()) continue; |
| 5739 | 5549 | if (sym.n_sect == 0) continue; |
| 5740 | 5550 | sym.n_sect = ordinal_remap.get(sym.n_sect).?; |
| 5741 | 5551 | } |
| 5742 | | for (self.globals.items) |*sym| { |
| 5743 | | sym.n_sect = ordinal_remap.get(sym.n_sect).?; |
| 5552 | for (self.objects.items) |*object| { |
| 5553 | for (object.symtab.items) |*sym| { |
| 5554 | if (sym.undf()) continue; |
| 5555 | if (sym.n_sect == 0) continue; |
| 5556 | sym.n_sect = ordinal_remap.get(sym.n_sect).?; |
| 5557 | } |
| 5744 | 5558 | } |
| 5745 | 5559 | |
| 5746 | | self.section_ordinals.deinit(self.base.allocator); |
| 5560 | self.section_ordinals.deinit(gpa); |
| 5747 | 5561 | self.section_ordinals = ordinals; |
| 5748 | 5562 | } |
| 5749 | 5563 | |
| ... | ... | @@ -5751,11 +5565,13 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5751 | 5565 | const tracy = trace(@src()); |
| 5752 | 5566 | defer tracy.end(); |
| 5753 | 5567 | |
| 5754 | | var rebase_pointers = std.ArrayList(bind.Pointer).init(self.base.allocator); |
| 5568 | const gpa = self.base.allocator; |
| 5569 | |
| 5570 | var rebase_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 5755 | 5571 | defer rebase_pointers.deinit(); |
| 5756 | | var bind_pointers = std.ArrayList(bind.Pointer).init(self.base.allocator); |
| 5572 | var bind_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 5757 | 5573 | defer bind_pointers.deinit(); |
| 5758 | | var lazy_bind_pointers = std.ArrayList(bind.Pointer).init(self.base.allocator); |
| 5574 | var lazy_bind_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 5759 | 5575 | defer lazy_bind_pointers.deinit(); |
| 5760 | 5576 | |
| 5761 | 5577 | { |
| ... | ... | @@ -5768,13 +5584,17 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5768 | 5584 | if (match.seg == seg) continue; // __TEXT is non-writable |
| 5769 | 5585 | } |
| 5770 | 5586 | |
| 5771 | | const seg = self.load_commands.items[match.seg].segment; |
| 5587 | const seg = self.getSegment(match); |
| 5588 | const sect = self.getSection(match); |
| 5589 | log.debug("dyld info for {s},{s}", .{ sect.segName(), sect.sectName() }); |
| 5772 | 5590 | |
| 5773 | 5591 | while (true) { |
| 5774 | | const sym = self.locals.items[atom.local_sym_index]; |
| 5592 | log.debug(" ATOM(%{d}, '{s}')", .{ atom.sym_index, atom.getName(self) }); |
| 5593 | const sym = atom.getSymbol(self); |
| 5775 | 5594 | const base_offset = sym.n_value - seg.inner.vmaddr; |
| 5776 | 5595 | |
| 5777 | 5596 | for (atom.rebases.items) |offset| { |
| 5597 | log.debug(" | rebase at {x}", .{base_offset + offset}); |
| 5778 | 5598 | try rebase_pointers.append(.{ |
| 5779 | 5599 | .offset = base_offset + offset, |
| 5780 | 5600 | .segment_id = match.seg, |
| ... | ... | @@ -5782,57 +5602,55 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5782 | 5602 | } |
| 5783 | 5603 | |
| 5784 | 5604 | for (atom.bindings.items) |binding| { |
| 5785 | | const resolv = self.symbol_resolver.get(binding.n_strx).?; |
| 5786 | | switch (resolv.where) { |
| 5787 | | .global => { |
| 5788 | | // Turn into a rebase. |
| 5789 | | try rebase_pointers.append(.{ |
| 5790 | | .offset = base_offset + binding.offset, |
| 5791 | | .segment_id = match.seg, |
| 5792 | | }); |
| 5793 | | }, |
| 5794 | | .undef => { |
| 5795 | | const bind_sym = self.undefs.items[resolv.where_index]; |
| 5796 | | var flags: u4 = 0; |
| 5797 | | if (bind_sym.weakRef()) { |
| 5798 | | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 5799 | | } |
| 5800 | | try bind_pointers.append(.{ |
| 5801 | | .offset = binding.offset + base_offset, |
| 5802 | | .segment_id = match.seg, |
| 5803 | | .dylib_ordinal = @divTrunc(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER), |
| 5804 | | .name = self.getString(bind_sym.n_strx), |
| 5805 | | .bind_flags = flags, |
| 5806 | | }); |
| 5807 | | }, |
| 5605 | const bind_sym = self.getSymbol(binding.target); |
| 5606 | const bind_sym_name = self.getSymbolName(binding.target); |
| 5607 | const dylib_ordinal = @divTrunc( |
| 5608 | @bitCast(i16, bind_sym.n_desc), |
| 5609 | macho.N_SYMBOL_RESOLVER, |
| 5610 | ); |
| 5611 | var flags: u4 = 0; |
| 5612 | log.debug(" | bind at {x}, import('{s}') in dylib({d})", .{ |
| 5613 | binding.offset + base_offset, |
| 5614 | bind_sym_name, |
| 5615 | dylib_ordinal, |
| 5616 | }); |
| 5617 | if (bind_sym.weakRef()) { |
| 5618 | log.debug(" | marking as weak ref ", .{}); |
| 5619 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 5808 | 5620 | } |
| 5621 | try bind_pointers.append(.{ |
| 5622 | .offset = binding.offset + base_offset, |
| 5623 | .segment_id = match.seg, |
| 5624 | .dylib_ordinal = dylib_ordinal, |
| 5625 | .name = bind_sym_name, |
| 5626 | .bind_flags = flags, |
| 5627 | }); |
| 5809 | 5628 | } |
| 5810 | 5629 | |
| 5811 | 5630 | for (atom.lazy_bindings.items) |binding| { |
| 5812 | | const resolv = self.symbol_resolver.get(binding.n_strx).?; |
| 5813 | | switch (resolv.where) { |
| 5814 | | .global => { |
| 5815 | | // Turn into a rebase. |
| 5816 | | try rebase_pointers.append(.{ |
| 5817 | | .offset = base_offset + binding.offset, |
| 5818 | | .segment_id = match.seg, |
| 5819 | | }); |
| 5820 | | }, |
| 5821 | | .undef => { |
| 5822 | | const bind_sym = self.undefs.items[resolv.where_index]; |
| 5823 | | var flags: u4 = 0; |
| 5824 | | if (bind_sym.weakRef()) { |
| 5825 | | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 5826 | | } |
| 5827 | | try lazy_bind_pointers.append(.{ |
| 5828 | | .offset = binding.offset + base_offset, |
| 5829 | | .segment_id = match.seg, |
| 5830 | | .dylib_ordinal = @divTrunc(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER), |
| 5831 | | .name = self.getString(bind_sym.n_strx), |
| 5832 | | .bind_flags = flags, |
| 5833 | | }); |
| 5834 | | }, |
| 5631 | const bind_sym = self.getSymbol(binding.target); |
| 5632 | const bind_sym_name = self.getSymbolName(binding.target); |
| 5633 | const dylib_ordinal = @divTrunc( |
| 5634 | @bitCast(i16, bind_sym.n_desc), |
| 5635 | macho.N_SYMBOL_RESOLVER, |
| 5636 | ); |
| 5637 | var flags: u4 = 0; |
| 5638 | log.debug(" | lazy bind at {x} import('{s}') ord({d})", .{ |
| 5639 | binding.offset + base_offset, |
| 5640 | bind_sym_name, |
| 5641 | dylib_ordinal, |
| 5642 | }); |
| 5643 | if (bind_sym.weakRef()) { |
| 5644 | log.debug(" | marking as weak ref ", .{}); |
| 5645 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 5835 | 5646 | } |
| 5647 | try lazy_bind_pointers.append(.{ |
| 5648 | .offset = binding.offset + base_offset, |
| 5649 | .segment_id = match.seg, |
| 5650 | .dylib_ordinal = dylib_ordinal, |
| 5651 | .name = bind_sym_name, |
| 5652 | .bind_flags = flags, |
| 5653 | }); |
| 5836 | 5654 | } |
| 5837 | 5655 | |
| 5838 | 5656 | if (atom.prev) |prev| { |
| ... | ... | @@ -5843,7 +5661,7 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5843 | 5661 | } |
| 5844 | 5662 | |
| 5845 | 5663 | var trie: Trie = .{}; |
| 5846 | | defer trie.deinit(self.base.allocator); |
| 5664 | defer trie.deinit(gpa); |
| 5847 | 5665 | |
| 5848 | 5666 | { |
| 5849 | 5667 | // TODO handle macho.EXPORT_SYMBOL_FLAGS_REEXPORT and macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER. |
| ... | ... | @@ -5852,19 +5670,40 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5852 | 5670 | const text_segment = self.load_commands.items[self.text_segment_cmd_index.?].segment; |
| 5853 | 5671 | const base_address = text_segment.inner.vmaddr; |
| 5854 | 5672 | |
| 5855 | | for (self.globals.items) |sym| { |
| 5856 | | if (sym.n_type == 0) continue; |
| 5857 | | const sym_name = self.getString(sym.n_strx); |
| 5858 | | log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value }); |
| 5859 | | |
| 5860 | | try trie.put(self.base.allocator, .{ |
| 5861 | | .name = sym_name, |
| 5862 | | .vmaddr_offset = sym.n_value - base_address, |
| 5863 | | .export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR, |
| 5864 | | }); |
| 5673 | if (self.base.options.output_mode == .Exe) { |
| 5674 | for (&[_]SymbolWithLoc{ |
| 5675 | try self.getEntryPoint(), |
| 5676 | self.globals.get("__mh_execute_header").?, |
| 5677 | }) |global| { |
| 5678 | const sym = self.getSymbol(global); |
| 5679 | const sym_name = self.getSymbolName(global); |
| 5680 | log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value }); |
| 5681 | try trie.put(gpa, .{ |
| 5682 | .name = sym_name, |
| 5683 | .vmaddr_offset = sym.n_value - base_address, |
| 5684 | .export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR, |
| 5685 | }); |
| 5686 | } |
| 5687 | } else { |
| 5688 | assert(self.base.options.output_mode == .Lib); |
| 5689 | for (self.globals.values()) |global| { |
| 5690 | const sym = self.getSymbol(global); |
| 5691 | |
| 5692 | if (sym.undf()) continue; |
| 5693 | if (!sym.ext()) continue; |
| 5694 | if (sym.n_desc == N_DESC_GCED) continue; |
| 5695 | |
| 5696 | const sym_name = self.getSymbolName(global); |
| 5697 | log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value }); |
| 5698 | try trie.put(gpa, .{ |
| 5699 | .name = sym_name, |
| 5700 | .vmaddr_offset = sym.n_value - base_address, |
| 5701 | .export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR, |
| 5702 | }); |
| 5703 | } |
| 5865 | 5704 | } |
| 5866 | 5705 | |
| 5867 | | try trie.finalize(self.base.allocator); |
| 5706 | try trie.finalize(gpa); |
| 5868 | 5707 | } |
| 5869 | 5708 | |
| 5870 | 5709 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; |
| ... | ... | @@ -5909,8 +5748,8 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5909 | 5748 | seg.inner.filesize = dyld_info.export_off + dyld_info.export_size - seg.inner.fileoff; |
| 5910 | 5749 | |
| 5911 | 5750 | const needed_size = dyld_info.export_off + dyld_info.export_size - dyld_info.rebase_off; |
| 5912 | | var buffer = try self.base.allocator.alloc(u8, needed_size); |
| 5913 | | defer self.base.allocator.free(buffer); |
| 5751 | var buffer = try gpa.alloc(u8, needed_size); |
| 5752 | defer gpa.free(buffer); |
| 5914 | 5753 | mem.set(u8, buffer, 0); |
| 5915 | 5754 | |
| 5916 | 5755 | var stream = std.io.fixedBufferStream(buffer); |
| ... | ... | @@ -5937,10 +5776,12 @@ fn writeDyldInfoData(self: *MachO) !void { |
| 5937 | 5776 | try self.populateLazyBindOffsetsInStubHelper( |
| 5938 | 5777 | buffer[dyld_info.lazy_bind_off - base_off ..][0..dyld_info.lazy_bind_size], |
| 5939 | 5778 | ); |
| 5779 | |
| 5940 | 5780 | self.load_commands_dirty = true; |
| 5941 | 5781 | } |
| 5942 | 5782 | |
| 5943 | 5783 | fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5784 | const gpa = self.base.allocator; |
| 5944 | 5785 | const text_segment_cmd_index = self.text_segment_cmd_index orelse return; |
| 5945 | 5786 | const stub_helper_section_index = self.stub_helper_section_index orelse return; |
| 5946 | 5787 | const last_atom = self.atoms.get(.{ |
| ... | ... | @@ -5950,7 +5791,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5950 | 5791 | if (self.stub_helper_preamble_atom == null) return; |
| 5951 | 5792 | if (last_atom == self.stub_helper_preamble_atom.?) return; |
| 5952 | 5793 | |
| 5953 | | var table = std.AutoHashMap(i64, *Atom).init(self.base.allocator); |
| 5794 | var table = std.AutoHashMap(i64, *Atom).init(gpa); |
| 5954 | 5795 | defer table.deinit(); |
| 5955 | 5796 | |
| 5956 | 5797 | { |
| ... | ... | @@ -5966,7 +5807,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5966 | 5807 | |
| 5967 | 5808 | while (true) { |
| 5968 | 5809 | const laptr_off = blk: { |
| 5969 | | const sym = self.locals.items[laptr_atom.local_sym_index]; |
| 5810 | const sym = laptr_atom.getSymbol(self); |
| 5970 | 5811 | break :blk @intCast(i64, sym.n_value - base_addr); |
| 5971 | 5812 | }; |
| 5972 | 5813 | try table.putNoClobber(laptr_off, stub_atom); |
| ... | ... | @@ -5979,7 +5820,7 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 5979 | 5820 | |
| 5980 | 5821 | var stream = std.io.fixedBufferStream(buffer); |
| 5981 | 5822 | var reader = stream.reader(); |
| 5982 | | var offsets = std.ArrayList(struct { sym_offset: i64, offset: u32 }).init(self.base.allocator); |
| 5823 | var offsets = std.ArrayList(struct { sym_offset: i64, offset: u32 }).init(gpa); |
| 5983 | 5824 | try offsets.append(.{ .sym_offset = undefined, .offset = 0 }); |
| 5984 | 5825 | defer offsets.deinit(); |
| 5985 | 5826 | var valid_block = false; |
| ... | ... | @@ -6022,10 +5863,10 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 6022 | 5863 | } |
| 6023 | 5864 | } |
| 6024 | 5865 | |
| 6025 | | const sect = blk: { |
| 6026 | | const seg = self.load_commands.items[text_segment_cmd_index].segment; |
| 6027 | | break :blk seg.sections.items[stub_helper_section_index]; |
| 6028 | | }; |
| 5866 | const sect = self.getSection(.{ |
| 5867 | .seg = text_segment_cmd_index, |
| 5868 | .sect = stub_helper_section_index, |
| 5869 | }); |
| 6029 | 5870 | const stub_offset: u4 = switch (self.base.options.target.cpu.arch) { |
| 6030 | 5871 | .x86_64 => 1, |
| 6031 | 5872 | .aarch64 => 2 * @sizeOf(u32), |
| ... | ... | @@ -6036,79 +5877,63 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { |
| 6036 | 5877 | |
| 6037 | 5878 | while (offsets.popOrNull()) |bind_offset| { |
| 6038 | 5879 | const atom = table.get(bind_offset.sym_offset).?; |
| 6039 | | const sym = self.locals.items[atom.local_sym_index]; |
| 5880 | const sym = atom.getSymbol(self); |
| 6040 | 5881 | const file_offset = sect.offset + sym.n_value - sect.addr + stub_offset; |
| 6041 | 5882 | mem.writeIntLittle(u32, &buf, bind_offset.offset); |
| 6042 | 5883 | log.debug("writing lazy bind offset in stub helper of 0x{x} for symbol {s} at offset 0x{x}", .{ |
| 6043 | 5884 | bind_offset.offset, |
| 6044 | | self.getString(sym.n_strx), |
| 5885 | atom.getName(self), |
| 6045 | 5886 | file_offset, |
| 6046 | 5887 | }); |
| 6047 | 5888 | try self.base.file.?.pwriteAll(&buf, file_offset); |
| 6048 | 5889 | } |
| 6049 | 5890 | } |
| 6050 | 5891 | |
| 5892 | const asc_u64 = std.sort.asc(u64); |
| 5893 | |
| 6051 | 5894 | fn writeFunctionStarts(self: *MachO) !void { |
| 6052 | | var atom = self.atoms.get(.{ |
| 6053 | | .seg = self.text_segment_cmd_index orelse return, |
| 6054 | | .sect = self.text_section_index orelse return, |
| 6055 | | }) orelse return; |
| 5895 | const text_seg_index = self.text_segment_cmd_index orelse return; |
| 5896 | const text_sect_index = self.text_section_index orelse return; |
| 5897 | const text_seg = self.load_commands.items[text_seg_index].segment; |
| 6056 | 5898 | |
| 6057 | 5899 | const tracy = trace(@src()); |
| 6058 | 5900 | defer tracy.end(); |
| 6059 | 5901 | |
| 6060 | | while (atom.prev) |prev| { |
| 6061 | | atom = prev; |
| 6062 | | } |
| 6063 | | |
| 6064 | | var offsets = std.ArrayList(u32).init(self.base.allocator); |
| 6065 | | defer offsets.deinit(); |
| 6066 | | |
| 6067 | | const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].segment; |
| 6068 | | var last_off: u32 = 0; |
| 6069 | | |
| 6070 | | while (true) { |
| 6071 | | const atom_sym = self.locals.items[atom.local_sym_index]; |
| 6072 | | |
| 6073 | | if (atom_sym.n_strx != 0) blk: { |
| 6074 | | if (self.symbol_resolver.get(atom_sym.n_strx)) |resolv| { |
| 6075 | | assert(resolv.where == .global); |
| 6076 | | if (resolv.local_sym_index != atom.local_sym_index) break :blk; |
| 6077 | | } |
| 6078 | | |
| 6079 | | const offset = @intCast(u32, atom_sym.n_value - text_seg.inner.vmaddr); |
| 6080 | | const diff = offset - last_off; |
| 5902 | const gpa = self.base.allocator; |
| 6081 | 5903 | |
| 6082 | | if (diff == 0) break :blk; |
| 5904 | // We need to sort by address first |
| 5905 | var addresses = std.ArrayList(u64).init(gpa); |
| 5906 | defer addresses.deinit(); |
| 5907 | try addresses.ensureTotalCapacityPrecise(self.globals.count()); |
| 6083 | 5908 | |
| 6084 | | try offsets.append(diff); |
| 6085 | | last_off = offset; |
| 6086 | | } |
| 5909 | for (self.globals.values()) |global| { |
| 5910 | const sym = self.getSymbol(global); |
| 5911 | if (sym.undf()) continue; |
| 5912 | if (sym.n_desc == N_DESC_GCED) continue; |
| 5913 | const match = self.getMatchingSectionFromOrdinal(sym.n_sect); |
| 5914 | if (match.seg != text_seg_index or match.sect != text_sect_index) continue; |
| 6087 | 5915 | |
| 6088 | | for (atom.contained.items) |cont| { |
| 6089 | | const cont_sym = self.locals.items[cont.local_sym_index]; |
| 5916 | addresses.appendAssumeCapacity(sym.n_value); |
| 5917 | } |
| 6090 | 5918 | |
| 6091 | | if (cont_sym.n_strx == 0) continue; |
| 6092 | | if (self.symbol_resolver.get(cont_sym.n_strx)) |resolv| { |
| 6093 | | assert(resolv.where == .global); |
| 6094 | | if (resolv.local_sym_index != cont.local_sym_index) continue; |
| 6095 | | } |
| 5919 | std.sort.sort(u64, addresses.items, {}, asc_u64); |
| 6096 | 5920 | |
| 6097 | | const offset = @intCast(u32, cont_sym.n_value - text_seg.inner.vmaddr); |
| 6098 | | const diff = offset - last_off; |
| 5921 | var offsets = std.ArrayList(u32).init(gpa); |
| 5922 | defer offsets.deinit(); |
| 5923 | try offsets.ensureTotalCapacityPrecise(addresses.items.len); |
| 6099 | 5924 | |
| 6100 | | if (diff == 0) continue; |
| 5925 | var last_off: u32 = 0; |
| 5926 | for (addresses.items) |addr| { |
| 5927 | const offset = @intCast(u32, addr - text_seg.inner.vmaddr); |
| 5928 | const diff = offset - last_off; |
| 6101 | 5929 | |
| 6102 | | try offsets.append(diff); |
| 6103 | | last_off = offset; |
| 6104 | | } |
| 5930 | if (diff == 0) continue; |
| 6105 | 5931 | |
| 6106 | | if (atom.next) |next| { |
| 6107 | | atom = next; |
| 6108 | | } else break; |
| 5932 | offsets.appendAssumeCapacity(diff); |
| 5933 | last_off = offset; |
| 6109 | 5934 | } |
| 6110 | 5935 | |
| 6111 | | var buffer = std.ArrayList(u8).init(self.base.allocator); |
| 5936 | var buffer = std.ArrayList(u8).init(gpa); |
| 6112 | 5937 | defer buffer.deinit(); |
| 6113 | 5938 | |
| 6114 | 5939 | const max_size = @intCast(usize, offsets.items.len * @sizeOf(u64)); |
| ... | ... | @@ -6136,53 +5961,72 @@ fn writeFunctionStarts(self: *MachO) !void { |
| 6136 | 5961 | self.load_commands_dirty = true; |
| 6137 | 5962 | } |
| 6138 | 5963 | |
| 6139 | | fn writeDices(self: *MachO) !void { |
| 6140 | | if (!self.has_dices) return; |
| 5964 | fn filterDataInCode( |
| 5965 | dices: []const macho.data_in_code_entry, |
| 5966 | start_addr: u64, |
| 5967 | end_addr: u64, |
| 5968 | ) []const macho.data_in_code_entry { |
| 5969 | const Predicate = struct { |
| 5970 | addr: u64, |
| 5971 | |
| 5972 | pub fn predicate(self: @This(), dice: macho.data_in_code_entry) bool { |
| 5973 | return dice.offset >= self.addr; |
| 5974 | } |
| 5975 | }; |
| 5976 | |
| 5977 | const start = MachO.findFirst(macho.data_in_code_entry, dices, 0, Predicate{ .addr = start_addr }); |
| 5978 | const end = MachO.findFirst(macho.data_in_code_entry, dices, start, Predicate{ .addr = end_addr }); |
| 5979 | |
| 5980 | return dices[start..end]; |
| 5981 | } |
| 6141 | 5982 | |
| 5983 | fn writeDataInCode(self: *MachO) !void { |
| 6142 | 5984 | const tracy = trace(@src()); |
| 6143 | 5985 | defer tracy.end(); |
| 6144 | 5986 | |
| 6145 | | var buf = std.ArrayList(u8).init(self.base.allocator); |
| 6146 | | defer buf.deinit(); |
| 5987 | var out_dice = std.ArrayList(macho.data_in_code_entry).init(self.base.allocator); |
| 5988 | defer out_dice.deinit(); |
| 6147 | 5989 | |
| 6148 | | var atom: *Atom = self.atoms.get(.{ |
| 5990 | const text_sect = self.getSection(.{ |
| 6149 | 5991 | .seg = self.text_segment_cmd_index orelse return, |
| 6150 | 5992 | .sect = self.text_section_index orelse return, |
| 6151 | | }) orelse return; |
| 5993 | }); |
| 6152 | 5994 | |
| 6153 | | while (atom.prev) |prev| { |
| 6154 | | atom = prev; |
| 6155 | | } |
| 5995 | for (self.objects.items) |object| { |
| 5996 | const dice = object.parseDataInCode() orelse continue; |
| 5997 | try out_dice.ensureUnusedCapacity(dice.len); |
| 6156 | 5998 | |
| 6157 | | const text_seg = self.load_commands.items[self.text_segment_cmd_index.?].segment; |
| 6158 | | const text_sect = text_seg.sections.items[self.text_section_index.?]; |
| 5999 | for (object.managed_atoms.items) |atom| { |
| 6000 | const sym = atom.getSymbol(self); |
| 6001 | if (sym.n_desc == N_DESC_GCED) continue; |
| 6159 | 6002 | |
| 6160 | | while (true) { |
| 6161 | | if (atom.dices.items.len > 0) { |
| 6162 | | const sym = self.locals.items[atom.local_sym_index]; |
| 6163 | | const base_off = math.cast(u32, sym.n_value - text_sect.addr + text_sect.offset) orelse return error.Overflow; |
| 6164 | | |
| 6165 | | try buf.ensureUnusedCapacity(atom.dices.items.len * @sizeOf(macho.data_in_code_entry)); |
| 6166 | | for (atom.dices.items) |dice| { |
| 6167 | | const rebased_dice = macho.data_in_code_entry{ |
| 6168 | | .offset = base_off + dice.offset, |
| 6169 | | .length = dice.length, |
| 6170 | | .kind = dice.kind, |
| 6171 | | }; |
| 6172 | | buf.appendSliceAssumeCapacity(mem.asBytes(&rebased_dice)); |
| 6003 | const match = self.getMatchingSectionFromOrdinal(sym.n_sect); |
| 6004 | if (match.seg != self.text_segment_cmd_index.? and match.sect != self.text_section_index.?) { |
| 6005 | continue; |
| 6173 | 6006 | } |
| 6174 | | } |
| 6175 | 6007 | |
| 6176 | | if (atom.next) |next| { |
| 6177 | | atom = next; |
| 6178 | | } else break; |
| 6008 | const source_sym = object.getSourceSymbol(atom.sym_index) orelse continue; |
| 6009 | const source_addr = math.cast(u32, source_sym.n_value) orelse return error.Overflow; |
| 6010 | const filtered_dice = filterDataInCode(dice, source_addr, source_addr + atom.size); |
| 6011 | const base = math.cast(u32, sym.n_value - text_sect.addr + text_sect.offset) orelse |
| 6012 | return error.Overflow; |
| 6013 | |
| 6014 | for (filtered_dice) |single| { |
| 6015 | const offset = single.offset - source_addr + base; |
| 6016 | out_dice.appendAssumeCapacity(.{ |
| 6017 | .offset = offset, |
| 6018 | .length = single.length, |
| 6019 | .kind = single.kind, |
| 6020 | }); |
| 6021 | } |
| 6022 | } |
| 6179 | 6023 | } |
| 6180 | 6024 | |
| 6181 | 6025 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; |
| 6182 | 6026 | const dice_cmd = &self.load_commands.items[self.data_in_code_cmd_index.?].linkedit_data; |
| 6183 | 6027 | |
| 6184 | 6028 | const dataoff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(u64)); |
| 6185 | | const datasize = buf.items.len; |
| 6029 | const datasize = out_dice.items.len * @sizeOf(macho.data_in_code_entry); |
| 6186 | 6030 | dice_cmd.dataoff = @intCast(u32, dataoff); |
| 6187 | 6031 | dice_cmd.datasize = @intCast(u32, datasize); |
| 6188 | 6032 | seg.inner.filesize = dice_cmd.dataoff + dice_cmd.datasize - seg.inner.fileoff; |
| ... | ... | @@ -6192,118 +6036,93 @@ fn writeDices(self: *MachO) !void { |
| 6192 | 6036 | dice_cmd.dataoff + dice_cmd.datasize, |
| 6193 | 6037 | }); |
| 6194 | 6038 | |
| 6195 | | try self.base.file.?.pwriteAll(buf.items, dice_cmd.dataoff); |
| 6039 | try self.base.file.?.pwriteAll(mem.sliceAsBytes(out_dice.items), dice_cmd.dataoff); |
| 6196 | 6040 | self.load_commands_dirty = true; |
| 6197 | 6041 | } |
| 6198 | 6042 | |
| 6199 | | fn writeSymbolTable(self: *MachO) !void { |
| 6043 | fn writeSymtab(self: *MachO) !void { |
| 6200 | 6044 | const tracy = trace(@src()); |
| 6201 | 6045 | defer tracy.end(); |
| 6202 | 6046 | |
| 6047 | const gpa = self.base.allocator; |
| 6203 | 6048 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; |
| 6204 | 6049 | const symtab = &self.load_commands.items[self.symtab_cmd_index.?].symtab; |
| 6205 | 6050 | const symoff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(macho.nlist_64)); |
| 6206 | 6051 | symtab.symoff = @intCast(u32, symoff); |
| 6207 | 6052 | |
| 6208 | | var locals = std.ArrayList(macho.nlist_64).init(self.base.allocator); |
| 6053 | var locals = std.ArrayList(macho.nlist_64).init(gpa); |
| 6209 | 6054 | defer locals.deinit(); |
| 6210 | 6055 | |
| 6211 | | for (self.locals.items) |sym| { |
| 6212 | | if (sym.n_strx == 0) continue; |
| 6213 | | if (self.symbol_resolver.get(sym.n_strx)) |_| continue; |
| 6056 | for (self.locals.items) |sym, sym_id| { |
| 6057 | if (sym.n_strx == 0) continue; // no name, skip |
| 6058 | if (sym.n_desc == N_DESC_GCED) continue; // GCed, skip |
| 6059 | const sym_loc = SymbolWithLoc{ .sym_index = @intCast(u32, sym_id), .file = null }; |
| 6060 | if (self.symbolIsTemp(sym_loc)) continue; // local temp symbol, skip |
| 6061 | if (self.globals.contains(self.getSymbolName(sym_loc))) continue; // global symbol is either an export or import, skip |
| 6214 | 6062 | try locals.append(sym); |
| 6215 | 6063 | } |
| 6216 | 6064 | |
| 6217 | | // TODO How do we handle null global symbols in incremental context? |
| 6218 | | var undefs = std.ArrayList(macho.nlist_64).init(self.base.allocator); |
| 6219 | | defer undefs.deinit(); |
| 6220 | | var undefs_table = std.AutoHashMap(u32, u32).init(self.base.allocator); |
| 6221 | | defer undefs_table.deinit(); |
| 6222 | | try undefs.ensureTotalCapacity(self.undefs.items.len); |
| 6223 | | try undefs_table.ensureTotalCapacity(@intCast(u32, self.undefs.items.len)); |
| 6065 | for (self.objects.items) |object, object_id| { |
| 6066 | for (object.symtab.items) |sym, sym_id| { |
| 6067 | if (sym.n_strx == 0) continue; // no name, skip |
| 6068 | if (sym.n_desc == N_DESC_GCED) continue; // GCed, skip |
| 6069 | const sym_loc = SymbolWithLoc{ .sym_index = @intCast(u32, sym_id), .file = @intCast(u32, object_id) }; |
| 6070 | if (self.symbolIsTemp(sym_loc)) continue; // local temp symbol, skip |
| 6071 | if (self.globals.contains(self.getSymbolName(sym_loc))) continue; // global symbol is either an export or import, skip |
| 6072 | var out_sym = sym; |
| 6073 | out_sym.n_strx = try self.strtab.insert(gpa, self.getSymbolName(sym_loc)); |
| 6074 | try locals.append(out_sym); |
| 6075 | } |
| 6224 | 6076 | |
| 6225 | | for (self.undefs.items) |sym, i| { |
| 6226 | | if (sym.n_strx == 0) continue; |
| 6227 | | const new_index = @intCast(u32, undefs.items.len); |
| 6228 | | undefs.appendAssumeCapacity(sym); |
| 6229 | | undefs_table.putAssumeCapacityNoClobber(@intCast(u32, i), new_index); |
| 6077 | if (!self.base.options.strip) { |
| 6078 | try self.generateSymbolStabs(object, &locals); |
| 6079 | } |
| 6230 | 6080 | } |
| 6231 | 6081 | |
| 6232 | | if (self.has_stabs) { |
| 6233 | | for (self.objects.items) |object| { |
| 6234 | | if (object.debug_info == null) continue; |
| 6082 | var exports = std.ArrayList(macho.nlist_64).init(gpa); |
| 6083 | defer exports.deinit(); |
| 6235 | 6084 | |
| 6236 | | // Open scope |
| 6237 | | try locals.ensureUnusedCapacity(3); |
| 6238 | | locals.appendAssumeCapacity(.{ |
| 6239 | | .n_strx = try self.makeString(object.tu_comp_dir.?), |
| 6240 | | .n_type = macho.N_SO, |
| 6241 | | .n_sect = 0, |
| 6242 | | .n_desc = 0, |
| 6243 | | .n_value = 0, |
| 6244 | | }); |
| 6245 | | locals.appendAssumeCapacity(.{ |
| 6246 | | .n_strx = try self.makeString(object.tu_name.?), |
| 6247 | | .n_type = macho.N_SO, |
| 6248 | | .n_sect = 0, |
| 6249 | | .n_desc = 0, |
| 6250 | | .n_value = 0, |
| 6251 | | }); |
| 6252 | | locals.appendAssumeCapacity(.{ |
| 6253 | | .n_strx = try self.makeString(object.name), |
| 6254 | | .n_type = macho.N_OSO, |
| 6255 | | .n_sect = 0, |
| 6256 | | .n_desc = 1, |
| 6257 | | .n_value = object.mtime orelse 0, |
| 6258 | | }); |
| 6085 | for (self.globals.values()) |global| { |
| 6086 | const sym = self.getSymbol(global); |
| 6087 | if (sym.undf()) continue; // import, skip |
| 6088 | if (sym.n_desc == N_DESC_GCED) continue; // GCed, skip |
| 6089 | var out_sym = sym; |
| 6090 | out_sym.n_strx = try self.strtab.insert(gpa, self.getSymbolName(global)); |
| 6091 | try exports.append(out_sym); |
| 6092 | } |
| 6259 | 6093 | |
| 6260 | | for (object.contained_atoms.items) |atom| { |
| 6261 | | if (atom.stab) |stab| { |
| 6262 | | const nlists = try stab.asNlists(atom.local_sym_index, self); |
| 6263 | | defer self.base.allocator.free(nlists); |
| 6264 | | try locals.appendSlice(nlists); |
| 6265 | | } else { |
| 6266 | | for (atom.contained.items) |sym_at_off| { |
| 6267 | | const stab = sym_at_off.stab orelse continue; |
| 6268 | | const nlists = try stab.asNlists(sym_at_off.local_sym_index, self); |
| 6269 | | defer self.base.allocator.free(nlists); |
| 6270 | | try locals.appendSlice(nlists); |
| 6271 | | } |
| 6272 | | } |
| 6273 | | } |
| 6094 | var imports = std.ArrayList(macho.nlist_64).init(gpa); |
| 6095 | defer imports.deinit(); |
| 6096 | var imports_table = std.AutoHashMap(SymbolWithLoc, u32).init(gpa); |
| 6097 | defer imports_table.deinit(); |
| 6274 | 6098 | |
| 6275 | | // Close scope |
| 6276 | | try locals.append(.{ |
| 6277 | | .n_strx = 0, |
| 6278 | | .n_type = macho.N_SO, |
| 6279 | | .n_sect = 0, |
| 6280 | | .n_desc = 0, |
| 6281 | | .n_value = 0, |
| 6282 | | }); |
| 6283 | | } |
| 6099 | for (self.globals.values()) |global| { |
| 6100 | const sym = self.getSymbol(global); |
| 6101 | if (sym.n_strx == 0) continue; // no name, skip |
| 6102 | if (!sym.undf()) continue; // not an import, skip |
| 6103 | const new_index = @intCast(u32, imports.items.len); |
| 6104 | var out_sym = sym; |
| 6105 | out_sym.n_strx = try self.strtab.insert(gpa, self.getSymbolName(global)); |
| 6106 | try imports.append(out_sym); |
| 6107 | try imports_table.putNoClobber(global, new_index); |
| 6284 | 6108 | } |
| 6285 | 6109 | |
| 6286 | 6110 | const nlocals = locals.items.len; |
| 6287 | | const nexports = self.globals.items.len; |
| 6288 | | const nundefs = undefs.items.len; |
| 6289 | | |
| 6290 | | const locals_off = symtab.symoff; |
| 6291 | | const locals_size = nlocals * @sizeOf(macho.nlist_64); |
| 6292 | | log.debug("writing local symbols from 0x{x} to 0x{x}", .{ locals_off, locals_size + locals_off }); |
| 6293 | | try self.base.file.?.pwriteAll(mem.sliceAsBytes(locals.items), locals_off); |
| 6111 | const nexports = exports.items.len; |
| 6112 | const nimports = imports.items.len; |
| 6113 | symtab.nsyms = @intCast(u32, nlocals + nexports + nimports); |
| 6294 | 6114 | |
| 6295 | | const exports_off = locals_off + locals_size; |
| 6296 | | const exports_size = nexports * @sizeOf(macho.nlist_64); |
| 6297 | | log.debug("writing exported symbols from 0x{x} to 0x{x}", .{ exports_off, exports_size + exports_off }); |
| 6298 | | try self.base.file.?.pwriteAll(mem.sliceAsBytes(self.globals.items), exports_off); |
| 6115 | var buffer = std.ArrayList(u8).init(gpa); |
| 6116 | defer buffer.deinit(); |
| 6117 | try buffer.ensureTotalCapacityPrecise(symtab.nsyms * @sizeOf(macho.nlist_64)); |
| 6118 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(locals.items)); |
| 6119 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(exports.items)); |
| 6120 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(imports.items)); |
| 6299 | 6121 | |
| 6300 | | const undefs_off = exports_off + exports_size; |
| 6301 | | const undefs_size = nundefs * @sizeOf(macho.nlist_64); |
| 6302 | | log.debug("writing undefined symbols from 0x{x} to 0x{x}", .{ undefs_off, undefs_size + undefs_off }); |
| 6303 | | try self.base.file.?.pwriteAll(mem.sliceAsBytes(undefs.items), undefs_off); |
| 6122 | log.debug("writing symtab from 0x{x} to 0x{x}", .{ symtab.symoff, symtab.symoff + buffer.items.len }); |
| 6123 | try self.base.file.?.pwriteAll(buffer.items, symtab.symoff); |
| 6304 | 6124 | |
| 6305 | | symtab.nsyms = @intCast(u32, nlocals + nexports + nundefs); |
| 6306 | | seg.inner.filesize = symtab.symoff + symtab.nsyms * @sizeOf(macho.nlist_64) - seg.inner.fileoff; |
| 6125 | seg.inner.filesize = symtab.symoff + buffer.items.len - seg.inner.fileoff; |
| 6307 | 6126 | |
| 6308 | 6127 | // Update dynamic symbol table. |
| 6309 | 6128 | const dysymtab = &self.load_commands.items[self.dysymtab_cmd_index.?].dysymtab; |
| ... | ... | @@ -6311,7 +6130,7 @@ fn writeSymbolTable(self: *MachO) !void { |
| 6311 | 6130 | dysymtab.iextdefsym = dysymtab.nlocalsym; |
| 6312 | 6131 | dysymtab.nextdefsym = @intCast(u32, nexports); |
| 6313 | 6132 | dysymtab.iundefsym = dysymtab.nlocalsym + dysymtab.nextdefsym; |
| 6314 | | dysymtab.nundefsym = @intCast(u32, nundefs); |
| 6133 | dysymtab.nundefsym = @intCast(u32, nimports); |
| 6315 | 6134 | |
| 6316 | 6135 | const nstubs = @intCast(u32, self.stubs_table.count()); |
| 6317 | 6136 | const ngot_entries = @intCast(u32, self.got_entries_table.count()); |
| ... | ... | @@ -6327,55 +6146,62 @@ fn writeSymbolTable(self: *MachO) !void { |
| 6327 | 6146 | dysymtab.indirectsymoff + dysymtab.nindirectsyms * @sizeOf(u32), |
| 6328 | 6147 | }); |
| 6329 | 6148 | |
| 6330 | | var buf = std.ArrayList(u8).init(self.base.allocator); |
| 6149 | var buf = std.ArrayList(u8).init(gpa); |
| 6331 | 6150 | defer buf.deinit(); |
| 6332 | 6151 | try buf.ensureTotalCapacity(dysymtab.nindirectsyms * @sizeOf(u32)); |
| 6333 | 6152 | const writer = buf.writer(); |
| 6334 | 6153 | |
| 6335 | 6154 | if (self.text_segment_cmd_index) |text_segment_cmd_index| blk: { |
| 6336 | 6155 | const stubs_section_index = self.stubs_section_index orelse break :blk; |
| 6337 | | const text_segment = &self.load_commands.items[text_segment_cmd_index].segment; |
| 6338 | | const stubs = &text_segment.sections.items[stubs_section_index]; |
| 6156 | const stubs = self.getSectionPtr(.{ |
| 6157 | .seg = text_segment_cmd_index, |
| 6158 | .sect = stubs_section_index, |
| 6159 | }); |
| 6339 | 6160 | stubs.reserved1 = 0; |
| 6340 | | for (self.stubs_table.keys()) |key| { |
| 6341 | | const resolv = self.symbol_resolver.get(key).?; |
| 6342 | | switch (resolv.where) { |
| 6343 | | .global => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL), |
| 6344 | | .undef => try writer.writeIntLittle(u32, dysymtab.iundefsym + undefs_table.get(resolv.where_index).?), |
| 6345 | | } |
| 6161 | for (self.stubs.items) |entry| { |
| 6162 | if (entry.sym_index == 0) continue; |
| 6163 | const atom_sym = entry.getSymbol(self); |
| 6164 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 6165 | const target_sym = self.getSymbol(entry.target); |
| 6166 | assert(target_sym.undf()); |
| 6167 | try writer.writeIntLittle(u32, dysymtab.iundefsym + imports_table.get(entry.target).?); |
| 6346 | 6168 | } |
| 6347 | 6169 | } |
| 6348 | 6170 | |
| 6349 | 6171 | if (self.data_const_segment_cmd_index) |data_const_segment_cmd_index| blk: { |
| 6350 | 6172 | const got_section_index = self.got_section_index orelse break :blk; |
| 6351 | | const data_const_segment = &self.load_commands.items[data_const_segment_cmd_index].segment; |
| 6352 | | const got = &data_const_segment.sections.items[got_section_index]; |
| 6173 | const got = self.getSectionPtr(.{ |
| 6174 | .seg = data_const_segment_cmd_index, |
| 6175 | .sect = got_section_index, |
| 6176 | }); |
| 6353 | 6177 | got.reserved1 = nstubs; |
| 6354 | | for (self.got_entries_table.keys()) |key| { |
| 6355 | | switch (key) { |
| 6356 | | .local => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL), |
| 6357 | | .global => |n_strx| { |
| 6358 | | const resolv = self.symbol_resolver.get(n_strx).?; |
| 6359 | | switch (resolv.where) { |
| 6360 | | .global => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL), |
| 6361 | | .undef => try writer.writeIntLittle(u32, dysymtab.iundefsym + undefs_table.get(resolv.where_index).?), |
| 6362 | | } |
| 6363 | | }, |
| 6178 | for (self.got_entries.items) |entry| { |
| 6179 | if (entry.sym_index == 0) continue; |
| 6180 | const atom_sym = entry.getSymbol(self); |
| 6181 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 6182 | const target_sym = self.getSymbol(entry.target); |
| 6183 | if (target_sym.undf()) { |
| 6184 | try writer.writeIntLittle(u32, dysymtab.iundefsym + imports_table.get(entry.target).?); |
| 6185 | } else { |
| 6186 | try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL); |
| 6364 | 6187 | } |
| 6365 | 6188 | } |
| 6366 | 6189 | } |
| 6367 | 6190 | |
| 6368 | 6191 | if (self.data_segment_cmd_index) |data_segment_cmd_index| blk: { |
| 6369 | 6192 | const la_symbol_ptr_section_index = self.la_symbol_ptr_section_index orelse break :blk; |
| 6370 | | const data_segment = &self.load_commands.items[data_segment_cmd_index].segment; |
| 6371 | | const la_symbol_ptr = &data_segment.sections.items[la_symbol_ptr_section_index]; |
| 6193 | const la_symbol_ptr = self.getSectionPtr(.{ |
| 6194 | .seg = data_segment_cmd_index, |
| 6195 | .sect = la_symbol_ptr_section_index, |
| 6196 | }); |
| 6372 | 6197 | la_symbol_ptr.reserved1 = nstubs + ngot_entries; |
| 6373 | | for (self.stubs_table.keys()) |key| { |
| 6374 | | const resolv = self.symbol_resolver.get(key).?; |
| 6375 | | switch (resolv.where) { |
| 6376 | | .global => try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL), |
| 6377 | | .undef => try writer.writeIntLittle(u32, dysymtab.iundefsym + undefs_table.get(resolv.where_index).?), |
| 6378 | | } |
| 6198 | for (self.stubs.items) |entry| { |
| 6199 | if (entry.sym_index == 0) continue; |
| 6200 | const atom_sym = entry.getSymbol(self); |
| 6201 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 6202 | const target_sym = self.getSymbol(entry.target); |
| 6203 | assert(target_sym.undf()); |
| 6204 | try writer.writeIntLittle(u32, dysymtab.iundefsym + imports_table.get(entry.target).?); |
| 6379 | 6205 | } |
| 6380 | 6206 | } |
| 6381 | 6207 | |
| ... | ... | @@ -6385,21 +6211,22 @@ fn writeSymbolTable(self: *MachO) !void { |
| 6385 | 6211 | self.load_commands_dirty = true; |
| 6386 | 6212 | } |
| 6387 | 6213 | |
| 6388 | | fn writeStringTable(self: *MachO) !void { |
| 6214 | fn writeStrtab(self: *MachO) !void { |
| 6389 | 6215 | const tracy = trace(@src()); |
| 6390 | 6216 | defer tracy.end(); |
| 6391 | 6217 | |
| 6392 | 6218 | const seg = &self.load_commands.items[self.linkedit_segment_cmd_index.?].segment; |
| 6393 | 6219 | const symtab = &self.load_commands.items[self.symtab_cmd_index.?].symtab; |
| 6394 | 6220 | const stroff = mem.alignForwardGeneric(u64, seg.inner.fileoff + seg.inner.filesize, @alignOf(u64)); |
| 6395 | | const strsize = self.strtab.items.len; |
| 6221 | |
| 6222 | const strsize = self.strtab.buffer.items.len; |
| 6396 | 6223 | symtab.stroff = @intCast(u32, stroff); |
| 6397 | 6224 | symtab.strsize = @intCast(u32, strsize); |
| 6398 | 6225 | seg.inner.filesize = symtab.stroff + symtab.strsize - seg.inner.fileoff; |
| 6399 | 6226 | |
| 6400 | 6227 | log.debug("writing string table from 0x{x} to 0x{x}", .{ symtab.stroff, symtab.stroff + symtab.strsize }); |
| 6401 | 6228 | |
| 6402 | | try self.base.file.?.pwriteAll(self.strtab.items, symtab.stroff); |
| 6229 | try self.base.file.?.pwriteAll(self.strtab.buffer.items, symtab.stroff); |
| 6403 | 6230 | |
| 6404 | 6231 | self.load_commands_dirty = true; |
| 6405 | 6232 | } |
| ... | ... | @@ -6413,9 +6240,9 @@ fn writeLinkeditSegment(self: *MachO) !void { |
| 6413 | 6240 | |
| 6414 | 6241 | try self.writeDyldInfoData(); |
| 6415 | 6242 | try self.writeFunctionStarts(); |
| 6416 | | try self.writeDices(); |
| 6417 | | try self.writeSymbolTable(); |
| 6418 | | try self.writeStringTable(); |
| 6243 | try self.writeDataInCode(); |
| 6244 | try self.writeSymtab(); |
| 6245 | try self.writeStrtab(); |
| 6419 | 6246 | |
| 6420 | 6247 | seg.inner.vmsize = mem.alignForwardGeneric(u64, seg.inner.filesize, self.page_size); |
| 6421 | 6248 | } |
| ... | ... | @@ -6557,43 +6384,114 @@ pub fn makeStaticString(bytes: []const u8) [16]u8 { |
| 6557 | 6384 | return buf; |
| 6558 | 6385 | } |
| 6559 | 6386 | |
| 6560 | | pub fn makeString(self: *MachO, string: []const u8) !u32 { |
| 6561 | | const gop = try self.strtab_dir.getOrPutContextAdapted(self.base.allocator, @as([]const u8, string), StringIndexAdapter{ |
| 6562 | | .bytes = &self.strtab, |
| 6563 | | }, StringIndexContext{ |
| 6564 | | .bytes = &self.strtab, |
| 6565 | | }); |
| 6566 | | if (gop.found_existing) { |
| 6567 | | const off = gop.key_ptr.*; |
| 6568 | | log.debug("reusing string '{s}' at offset 0x{x}", .{ string, off }); |
| 6569 | | return off; |
| 6570 | | } |
| 6571 | | |
| 6572 | | try self.strtab.ensureUnusedCapacity(self.base.allocator, string.len + 1); |
| 6573 | | const new_off = @intCast(u32, self.strtab.items.len); |
| 6387 | pub fn getSectionOrdinal(self: *MachO, match: MatchingSection) u8 { |
| 6388 | return @intCast(u8, self.section_ordinals.getIndex(match).?) + 1; |
| 6389 | } |
| 6574 | 6390 | |
| 6575 | | log.debug("writing new string '{s}' at offset 0x{x}", .{ string, new_off }); |
| 6391 | pub fn getMatchingSectionFromOrdinal(self: *MachO, ord: u8) MatchingSection { |
| 6392 | const index = ord - 1; |
| 6393 | assert(index < self.section_ordinals.count()); |
| 6394 | return self.section_ordinals.keys()[index]; |
| 6395 | } |
| 6576 | 6396 | |
| 6577 | | self.strtab.appendSliceAssumeCapacity(string); |
| 6578 | | self.strtab.appendAssumeCapacity(0); |
| 6397 | pub fn getSegmentPtr(self: *MachO, match: MatchingSection) *macho.SegmentCommand { |
| 6398 | assert(match.seg < self.load_commands.items.len); |
| 6399 | return &self.load_commands.items[match.seg].segment; |
| 6400 | } |
| 6579 | 6401 | |
| 6580 | | gop.key_ptr.* = new_off; |
| 6402 | pub fn getSegment(self: *MachO, match: MatchingSection) macho.SegmentCommand { |
| 6403 | return self.getSegmentPtr(match).*; |
| 6404 | } |
| 6581 | 6405 | |
| 6582 | | return new_off; |
| 6406 | pub fn getSectionPtr(self: *MachO, match: MatchingSection) *macho.section_64 { |
| 6407 | const seg = self.getSegmentPtr(match); |
| 6408 | assert(match.sect < seg.sections.items.len); |
| 6409 | return &seg.sections.items[match.sect]; |
| 6583 | 6410 | } |
| 6584 | 6411 | |
| 6585 | | pub fn getString(self: MachO, off: u32) []const u8 { |
| 6586 | | assert(off < self.strtab.items.len); |
| 6587 | | return mem.sliceTo(@ptrCast([*:0]const u8, self.strtab.items.ptr + off), 0); |
| 6412 | pub fn getSection(self: *MachO, match: MatchingSection) macho.section_64 { |
| 6413 | return self.getSectionPtr(match).*; |
| 6588 | 6414 | } |
| 6589 | 6415 | |
| 6590 | | pub fn symbolIsTemp(sym: macho.nlist_64, sym_name: []const u8) bool { |
| 6416 | pub fn symbolIsTemp(self: *MachO, sym_with_loc: SymbolWithLoc) bool { |
| 6417 | const sym = self.getSymbol(sym_with_loc); |
| 6591 | 6418 | if (!sym.sect()) return false; |
| 6592 | 6419 | if (sym.ext()) return false; |
| 6420 | const sym_name = self.getSymbolName(sym_with_loc); |
| 6593 | 6421 | return mem.startsWith(u8, sym_name, "l") or mem.startsWith(u8, sym_name, "L"); |
| 6594 | 6422 | } |
| 6595 | 6423 | |
| 6596 | | pub fn findFirst(comptime T: type, haystack: []T, start: usize, predicate: anytype) usize { |
| 6424 | /// Returns pointer-to-symbol described by `sym_with_loc` descriptor. |
| 6425 | pub fn getSymbolPtr(self: *MachO, sym_with_loc: SymbolWithLoc) *macho.nlist_64 { |
| 6426 | if (sym_with_loc.file) |file| { |
| 6427 | const object = &self.objects.items[file]; |
| 6428 | return &object.symtab.items[sym_with_loc.sym_index]; |
| 6429 | } else { |
| 6430 | return &self.locals.items[sym_with_loc.sym_index]; |
| 6431 | } |
| 6432 | } |
| 6433 | |
| 6434 | /// Returns symbol described by `sym_with_loc` descriptor. |
| 6435 | pub fn getSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) macho.nlist_64 { |
| 6436 | return self.getSymbolPtr(sym_with_loc).*; |
| 6437 | } |
| 6438 | |
| 6439 | /// Returns name of the symbol described by `sym_with_loc` descriptor. |
| 6440 | pub fn getSymbolName(self: *MachO, sym_with_loc: SymbolWithLoc) []const u8 { |
| 6441 | if (sym_with_loc.file) |file| { |
| 6442 | const object = self.objects.items[file]; |
| 6443 | const sym = object.symtab.items[sym_with_loc.sym_index]; |
| 6444 | return object.getString(sym.n_strx); |
| 6445 | } else { |
| 6446 | const sym = self.locals.items[sym_with_loc.sym_index]; |
| 6447 | return self.strtab.get(sym.n_strx).?; |
| 6448 | } |
| 6449 | } |
| 6450 | |
| 6451 | /// Returns atom if there is an atom referenced by the symbol described by `sym_with_loc` descriptor. |
| 6452 | /// Returns null on failure. |
| 6453 | pub fn getAtomForSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) ?*Atom { |
| 6454 | if (sym_with_loc.file) |file| { |
| 6455 | const object = self.objects.items[file]; |
| 6456 | return object.getAtomForSymbol(sym_with_loc.sym_index); |
| 6457 | } else { |
| 6458 | return self.atom_by_index_table.get(sym_with_loc.sym_index); |
| 6459 | } |
| 6460 | } |
| 6461 | |
| 6462 | /// Returns GOT atom that references `sym_with_loc` if one exists. |
| 6463 | /// Returns null otherwise. |
| 6464 | pub fn getGotAtomForSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) ?*Atom { |
| 6465 | const got_index = self.got_entries_table.get(sym_with_loc) orelse return null; |
| 6466 | return self.got_entries.items[got_index].getAtom(self); |
| 6467 | } |
| 6468 | |
| 6469 | /// Returns stubs atom that references `sym_with_loc` if one exists. |
| 6470 | /// Returns null otherwise. |
| 6471 | pub fn getStubsAtomForSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) ?*Atom { |
| 6472 | const stubs_index = self.stubs_table.get(sym_with_loc) orelse return null; |
| 6473 | return self.stubs.items[stubs_index].getAtom(self); |
| 6474 | } |
| 6475 | |
| 6476 | /// Returns TLV pointer atom that references `sym_with_loc` if one exists. |
| 6477 | /// Returns null otherwise. |
| 6478 | pub fn getTlvPtrAtomForSymbol(self: *MachO, sym_with_loc: SymbolWithLoc) ?*Atom { |
| 6479 | const tlv_ptr_index = self.tlv_ptr_entries_table.get(sym_with_loc) orelse return null; |
| 6480 | return self.tlv_ptr_entries.items[tlv_ptr_index].getAtom(self); |
| 6481 | } |
| 6482 | |
| 6483 | /// Returns symbol location corresponding to the set entrypoint. |
| 6484 | /// Asserts output mode is executable. |
| 6485 | pub fn getEntryPoint(self: MachO) error{MissingMainEntrypoint}!SymbolWithLoc { |
| 6486 | const entry_name = self.base.options.entry orelse "_main"; |
| 6487 | const global = self.globals.get(entry_name) orelse { |
| 6488 | log.err("entrypoint '{s}' not found", .{entry_name}); |
| 6489 | return error.MissingMainEntrypoint; |
| 6490 | }; |
| 6491 | return global; |
| 6492 | } |
| 6493 | |
| 6494 | pub fn findFirst(comptime T: type, haystack: []const T, start: usize, predicate: anytype) usize { |
| 6597 | 6495 | if (!@hasDecl(@TypeOf(predicate), "predicate")) |
| 6598 | 6496 | @compileError("Predicate is required to define fn predicate(@This(), T) bool"); |
| 6599 | 6497 | |
| ... | ... | @@ -6606,6 +6504,225 @@ pub fn findFirst(comptime T: type, haystack: []T, start: usize, predicate: anyty |
| 6606 | 6504 | return i; |
| 6607 | 6505 | } |
| 6608 | 6506 | |
| 6507 | const DebugInfo = struct { |
| 6508 | inner: dwarf.DwarfInfo, |
| 6509 | debug_info: []const u8, |
| 6510 | debug_abbrev: []const u8, |
| 6511 | debug_str: []const u8, |
| 6512 | debug_line: []const u8, |
| 6513 | debug_line_str: []const u8, |
| 6514 | debug_ranges: []const u8, |
| 6515 | |
| 6516 | pub fn parse(allocator: Allocator, object: Object) !?DebugInfo { |
| 6517 | var debug_info = blk: { |
| 6518 | const index = object.dwarf_debug_info_index orelse return null; |
| 6519 | break :blk try object.getSectionContents(index); |
| 6520 | }; |
| 6521 | var debug_abbrev = blk: { |
| 6522 | const index = object.dwarf_debug_abbrev_index orelse return null; |
| 6523 | break :blk try object.getSectionContents(index); |
| 6524 | }; |
| 6525 | var debug_str = blk: { |
| 6526 | const index = object.dwarf_debug_str_index orelse return null; |
| 6527 | break :blk try object.getSectionContents(index); |
| 6528 | }; |
| 6529 | var debug_line = blk: { |
| 6530 | const index = object.dwarf_debug_line_index orelse return null; |
| 6531 | break :blk try object.getSectionContents(index); |
| 6532 | }; |
| 6533 | var debug_line_str = blk: { |
| 6534 | if (object.dwarf_debug_line_str_index) |ind| { |
| 6535 | break :blk try object.getSectionContents(ind); |
| 6536 | } |
| 6537 | break :blk &[0]u8{}; |
| 6538 | }; |
| 6539 | var debug_ranges = blk: { |
| 6540 | if (object.dwarf_debug_ranges_index) |ind| { |
| 6541 | break :blk try object.getSectionContents(ind); |
| 6542 | } |
| 6543 | break :blk &[0]u8{}; |
| 6544 | }; |
| 6545 | |
| 6546 | var inner: dwarf.DwarfInfo = .{ |
| 6547 | .endian = .Little, |
| 6548 | .debug_info = debug_info, |
| 6549 | .debug_abbrev = debug_abbrev, |
| 6550 | .debug_str = debug_str, |
| 6551 | .debug_line = debug_line, |
| 6552 | .debug_line_str = debug_line_str, |
| 6553 | .debug_ranges = debug_ranges, |
| 6554 | }; |
| 6555 | try dwarf.openDwarfDebugInfo(&inner, allocator); |
| 6556 | |
| 6557 | return DebugInfo{ |
| 6558 | .inner = inner, |
| 6559 | .debug_info = debug_info, |
| 6560 | .debug_abbrev = debug_abbrev, |
| 6561 | .debug_str = debug_str, |
| 6562 | .debug_line = debug_line, |
| 6563 | .debug_line_str = debug_line_str, |
| 6564 | .debug_ranges = debug_ranges, |
| 6565 | }; |
| 6566 | } |
| 6567 | |
| 6568 | pub fn deinit(self: *DebugInfo, allocator: Allocator) void { |
| 6569 | self.inner.deinit(allocator); |
| 6570 | } |
| 6571 | }; |
| 6572 | |
| 6573 | pub fn generateSymbolStabs( |
| 6574 | self: *MachO, |
| 6575 | object: Object, |
| 6576 | locals: *std.ArrayList(macho.nlist_64), |
| 6577 | ) !void { |
| 6578 | assert(!self.base.options.strip); |
| 6579 | |
| 6580 | const gpa = self.base.allocator; |
| 6581 | |
| 6582 | log.debug("parsing debug info in '{s}'", .{object.name}); |
| 6583 | |
| 6584 | var debug_info = (try DebugInfo.parse(gpa, object)) orelse return; |
| 6585 | |
| 6586 | // We assume there is only one CU. |
| 6587 | const compile_unit = debug_info.inner.findCompileUnit(0x0) catch |err| switch (err) { |
| 6588 | error.MissingDebugInfo => { |
| 6589 | // TODO audit cases with missing debug info and audit our dwarf.zig module. |
| 6590 | log.debug("invalid or missing debug info in {s}; skipping", .{object.name}); |
| 6591 | return; |
| 6592 | }, |
| 6593 | else => |e| return e, |
| 6594 | }; |
| 6595 | const tu_name = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT.name); |
| 6596 | const tu_comp_dir = try compile_unit.die.getAttrString(&debug_info.inner, dwarf.AT.comp_dir); |
| 6597 | |
| 6598 | // Open scope |
| 6599 | try locals.ensureUnusedCapacity(3); |
| 6600 | locals.appendAssumeCapacity(.{ |
| 6601 | .n_strx = try self.strtab.insert(gpa, tu_comp_dir), |
| 6602 | .n_type = macho.N_SO, |
| 6603 | .n_sect = 0, |
| 6604 | .n_desc = 0, |
| 6605 | .n_value = 0, |
| 6606 | }); |
| 6607 | locals.appendAssumeCapacity(.{ |
| 6608 | .n_strx = try self.strtab.insert(gpa, tu_name), |
| 6609 | .n_type = macho.N_SO, |
| 6610 | .n_sect = 0, |
| 6611 | .n_desc = 0, |
| 6612 | .n_value = 0, |
| 6613 | }); |
| 6614 | locals.appendAssumeCapacity(.{ |
| 6615 | .n_strx = try self.strtab.insert(gpa, object.name), |
| 6616 | .n_type = macho.N_OSO, |
| 6617 | .n_sect = 0, |
| 6618 | .n_desc = 1, |
| 6619 | .n_value = object.mtime, |
| 6620 | }); |
| 6621 | |
| 6622 | var stabs_buf: [4]macho.nlist_64 = undefined; |
| 6623 | |
| 6624 | for (object.managed_atoms.items) |atom| { |
| 6625 | const stabs = try self.generateSymbolStabsForSymbol( |
| 6626 | atom.getSymbolWithLoc(), |
| 6627 | debug_info, |
| 6628 | &stabs_buf, |
| 6629 | ); |
| 6630 | try locals.appendSlice(stabs); |
| 6631 | |
| 6632 | for (atom.contained.items) |sym_at_off| { |
| 6633 | const sym_loc = SymbolWithLoc{ |
| 6634 | .sym_index = sym_at_off.sym_index, |
| 6635 | .file = atom.file, |
| 6636 | }; |
| 6637 | const contained_stabs = try self.generateSymbolStabsForSymbol( |
| 6638 | sym_loc, |
| 6639 | debug_info, |
| 6640 | &stabs_buf, |
| 6641 | ); |
| 6642 | try locals.appendSlice(contained_stabs); |
| 6643 | } |
| 6644 | } |
| 6645 | |
| 6646 | // Close scope |
| 6647 | try locals.append(.{ |
| 6648 | .n_strx = 0, |
| 6649 | .n_type = macho.N_SO, |
| 6650 | .n_sect = 0, |
| 6651 | .n_desc = 0, |
| 6652 | .n_value = 0, |
| 6653 | }); |
| 6654 | } |
| 6655 | |
| 6656 | fn generateSymbolStabsForSymbol( |
| 6657 | self: *MachO, |
| 6658 | sym_loc: SymbolWithLoc, |
| 6659 | debug_info: DebugInfo, |
| 6660 | buf: *[4]macho.nlist_64, |
| 6661 | ) ![]const macho.nlist_64 { |
| 6662 | const gpa = self.base.allocator; |
| 6663 | const object = self.objects.items[sym_loc.file.?]; |
| 6664 | const sym = self.getSymbol(sym_loc); |
| 6665 | const sym_name = self.getSymbolName(sym_loc); |
| 6666 | |
| 6667 | if (sym.n_strx == 0) return buf[0..0]; |
| 6668 | if (sym.n_desc == N_DESC_GCED) return buf[0..0]; |
| 6669 | if (self.symbolIsTemp(sym_loc)) return buf[0..0]; |
| 6670 | |
| 6671 | const source_sym = object.getSourceSymbol(sym_loc.sym_index) orelse return buf[0..0]; |
| 6672 | const size: ?u64 = size: { |
| 6673 | if (source_sym.tentative()) break :size null; |
| 6674 | for (debug_info.inner.func_list.items) |func| { |
| 6675 | if (func.pc_range) |range| { |
| 6676 | if (source_sym.n_value >= range.start and source_sym.n_value < range.end) { |
| 6677 | break :size range.end - range.start; |
| 6678 | } |
| 6679 | } |
| 6680 | } |
| 6681 | break :size null; |
| 6682 | }; |
| 6683 | |
| 6684 | if (size) |ss| { |
| 6685 | buf[0] = .{ |
| 6686 | .n_strx = 0, |
| 6687 | .n_type = macho.N_BNSYM, |
| 6688 | .n_sect = sym.n_sect, |
| 6689 | .n_desc = 0, |
| 6690 | .n_value = sym.n_value, |
| 6691 | }; |
| 6692 | buf[1] = .{ |
| 6693 | .n_strx = try self.strtab.insert(gpa, sym_name), |
| 6694 | .n_type = macho.N_FUN, |
| 6695 | .n_sect = sym.n_sect, |
| 6696 | .n_desc = 0, |
| 6697 | .n_value = sym.n_value, |
| 6698 | }; |
| 6699 | buf[2] = .{ |
| 6700 | .n_strx = 0, |
| 6701 | .n_type = macho.N_FUN, |
| 6702 | .n_sect = 0, |
| 6703 | .n_desc = 0, |
| 6704 | .n_value = ss, |
| 6705 | }; |
| 6706 | buf[3] = .{ |
| 6707 | .n_strx = 0, |
| 6708 | .n_type = macho.N_ENSYM, |
| 6709 | .n_sect = sym.n_sect, |
| 6710 | .n_desc = 0, |
| 6711 | .n_value = ss, |
| 6712 | }; |
| 6713 | return buf; |
| 6714 | } else { |
| 6715 | buf[0] = .{ |
| 6716 | .n_strx = try self.strtab.insert(gpa, sym_name), |
| 6717 | .n_type = macho.N_STSYM, |
| 6718 | .n_sect = sym.n_sect, |
| 6719 | .n_desc = 0, |
| 6720 | .n_value = sym.n_value, |
| 6721 | }; |
| 6722 | return buf[0..1]; |
| 6723 | } |
| 6724 | } |
| 6725 | |
| 6609 | 6726 | fn snapshotState(self: *MachO) !void { |
| 6610 | 6727 | const emit = self.base.options.emit orelse { |
| 6611 | 6728 | log.debug("no emit directory found; skipping snapshot...", .{}); |
| ... | ... | @@ -6655,7 +6772,7 @@ fn snapshotState(self: *MachO) !void { |
| 6655 | 6772 | const arena = arena_allocator.allocator(); |
| 6656 | 6773 | |
| 6657 | 6774 | const out_file = try emit.directory.handle.createFile("snapshots.json", .{ |
| 6658 | | .truncate = self.cold_start, |
| 6775 | .truncate = false, |
| 6659 | 6776 | .read = true, |
| 6660 | 6777 | }); |
| 6661 | 6778 | defer out_file.close(); |
| ... | ... | @@ -6675,8 +6792,7 @@ fn snapshotState(self: *MachO) !void { |
| 6675 | 6792 | var nodes = std.ArrayList(Snapshot.Node).init(arena); |
| 6676 | 6793 | |
| 6677 | 6794 | for (self.section_ordinals.keys()) |key| { |
| 6678 | | const seg = self.load_commands.items[key.seg].segment; |
| 6679 | | const sect = seg.sections.items[key.sect]; |
| 6795 | const sect = self.getSection(key); |
| 6680 | 6796 | const sect_name = try std.fmt.allocPrint(arena, "{s},{s}", .{ sect.segName(), sect.sectName() }); |
| 6681 | 6797 | try nodes.append(.{ |
| 6682 | 6798 | .address = sect.addr, |
| ... | ... | @@ -6684,6 +6800,8 @@ fn snapshotState(self: *MachO) !void { |
| 6684 | 6800 | .payload = .{ .name = sect_name }, |
| 6685 | 6801 | }); |
| 6686 | 6802 | |
| 6803 | const is_tlv = sect.type_() == macho.S_THREAD_LOCAL_VARIABLES; |
| 6804 | |
| 6687 | 6805 | var atom: *Atom = self.atoms.get(key) orelse { |
| 6688 | 6806 | try nodes.append(.{ |
| 6689 | 6807 | .address = sect.addr + sect.size, |
| ... | ... | @@ -6698,103 +6816,63 @@ fn snapshotState(self: *MachO) !void { |
| 6698 | 6816 | } |
| 6699 | 6817 | |
| 6700 | 6818 | while (true) { |
| 6701 | | const atom_sym = self.locals.items[atom.local_sym_index]; |
| 6702 | | const should_skip_atom: bool = blk: { |
| 6703 | | if (self.mh_execute_header_index) |index| { |
| 6704 | | if (index == atom.local_sym_index) break :blk true; |
| 6705 | | } |
| 6706 | | if (mem.eql(u8, self.getString(atom_sym.n_strx), "___dso_handle")) break :blk true; |
| 6707 | | break :blk false; |
| 6708 | | }; |
| 6709 | | |
| 6710 | | if (should_skip_atom) { |
| 6711 | | if (atom.next) |next| { |
| 6712 | | atom = next; |
| 6713 | | } else break; |
| 6714 | | continue; |
| 6715 | | } |
| 6716 | | |
| 6819 | const atom_sym = atom.getSymbol(self); |
| 6717 | 6820 | var node = Snapshot.Node{ |
| 6718 | 6821 | .address = atom_sym.n_value, |
| 6719 | 6822 | .tag = .atom_start, |
| 6720 | 6823 | .payload = .{ |
| 6721 | | .name = self.getString(atom_sym.n_strx), |
| 6722 | | .is_global = self.symbol_resolver.contains(atom_sym.n_strx), |
| 6824 | .name = atom.getName(self), |
| 6825 | .is_global = self.globals.contains(atom.getName(self)), |
| 6723 | 6826 | }, |
| 6724 | 6827 | }; |
| 6725 | 6828 | |
| 6726 | 6829 | var aliases = std.ArrayList([]const u8).init(arena); |
| 6727 | | for (atom.aliases.items) |loc| { |
| 6728 | | try aliases.append(self.getString(self.locals.items[loc].n_strx)); |
| 6830 | for (atom.contained.items) |sym_off| { |
| 6831 | if (sym_off.offset == 0) { |
| 6832 | try aliases.append(self.getSymbolName(.{ |
| 6833 | .sym_index = sym_off.sym_index, |
| 6834 | .file = atom.file, |
| 6835 | })); |
| 6836 | } |
| 6729 | 6837 | } |
| 6730 | 6838 | node.payload.aliases = aliases.toOwnedSlice(); |
| 6731 | 6839 | try nodes.append(node); |
| 6732 | 6840 | |
| 6733 | 6841 | var relocs = try std.ArrayList(Snapshot.Node).initCapacity(arena, atom.relocs.items.len); |
| 6734 | 6842 | for (atom.relocs.items) |rel| { |
| 6735 | | const arch = self.base.options.target.cpu.arch; |
| 6736 | 6843 | const source_addr = blk: { |
| 6737 | | const sym = self.locals.items[atom.local_sym_index]; |
| 6738 | | break :blk sym.n_value + rel.offset; |
| 6844 | const source_sym = atom.getSymbol(self); |
| 6845 | break :blk source_sym.n_value + rel.offset; |
| 6739 | 6846 | }; |
| 6740 | 6847 | const target_addr = blk: { |
| 6741 | | const is_via_got = got: { |
| 6742 | | switch (arch) { |
| 6743 | | .aarch64 => break :got switch (@intToEnum(macho.reloc_type_arm64, rel.@"type")) { |
| 6744 | | .ARM64_RELOC_GOT_LOAD_PAGE21, .ARM64_RELOC_GOT_LOAD_PAGEOFF12 => true, |
| 6745 | | else => false, |
| 6746 | | }, |
| 6747 | | .x86_64 => break :got switch (@intToEnum(macho.reloc_type_x86_64, rel.@"type")) { |
| 6748 | | .X86_64_RELOC_GOT, .X86_64_RELOC_GOT_LOAD => true, |
| 6749 | | else => false, |
| 6750 | | }, |
| 6751 | | else => unreachable, |
| 6848 | const target_atom = rel.getTargetAtom(self) orelse { |
| 6849 | // If there is no atom for target, we still need to check for special, atom-less |
| 6850 | // symbols such as `___dso_handle`. |
| 6851 | const target_name = self.getSymbolName(rel.target); |
| 6852 | if (self.globals.contains(target_name)) { |
| 6853 | const atomless_sym = self.getSymbol(rel.target); |
| 6854 | break :blk atomless_sym.n_value; |
| 6752 | 6855 | } |
| 6856 | break :blk 0; |
| 6753 | 6857 | }; |
| 6754 | | |
| 6755 | | if (is_via_got) { |
| 6756 | | const got_index = self.got_entries_table.get(rel.target) orelse break :blk 0; |
| 6757 | | const got_atom = self.got_entries.items[got_index].atom; |
| 6758 | | break :blk self.locals.items[got_atom.local_sym_index].n_value; |
| 6759 | | } |
| 6760 | | |
| 6761 | | switch (rel.target) { |
| 6762 | | .local => |sym_index| { |
| 6763 | | const sym = self.locals.items[sym_index]; |
| 6764 | | const is_tlv = is_tlv: { |
| 6765 | | const source_sym = self.locals.items[atom.local_sym_index]; |
| 6766 | | const match = self.section_ordinals.keys()[source_sym.n_sect - 1]; |
| 6767 | | const match_seg = self.load_commands.items[match.seg].segment; |
| 6768 | | const match_sect = match_seg.sections.items[match.sect]; |
| 6769 | | break :is_tlv match_sect.type_() == macho.S_THREAD_LOCAL_VARIABLES; |
| 6770 | | }; |
| 6771 | | if (is_tlv) { |
| 6772 | | const match_seg = self.load_commands.items[self.data_segment_cmd_index.?].segment; |
| 6773 | | const base_address = inner: { |
| 6774 | | if (self.tlv_data_section_index) |i| { |
| 6775 | | break :inner match_seg.sections.items[i].addr; |
| 6776 | | } else if (self.tlv_bss_section_index) |i| { |
| 6777 | | break :inner match_seg.sections.items[i].addr; |
| 6778 | | } else unreachable; |
| 6779 | | }; |
| 6780 | | break :blk sym.n_value - base_address; |
| 6781 | | } |
| 6782 | | break :blk sym.n_value; |
| 6783 | | }, |
| 6784 | | .global => |n_strx| { |
| 6785 | | const resolv = self.symbol_resolver.get(n_strx).?; |
| 6786 | | switch (resolv.where) { |
| 6787 | | .global => break :blk self.globals.items[resolv.where_index].n_value, |
| 6788 | | .undef => { |
| 6789 | | if (self.stubs_table.get(n_strx)) |stub_index| { |
| 6790 | | const stub_atom = self.stubs.items[stub_index]; |
| 6791 | | break :blk self.locals.items[stub_atom.local_sym_index].n_value; |
| 6792 | | } |
| 6793 | | break :blk 0; |
| 6794 | | }, |
| 6795 | | } |
| 6796 | | }, |
| 6797 | | } |
| 6858 | const target_sym = if (target_atom.isSymbolContained(rel.target, self)) |
| 6859 | self.getSymbol(rel.target) |
| 6860 | else |
| 6861 | target_atom.getSymbol(self); |
| 6862 | const base_address: u64 = if (is_tlv) base_address: { |
| 6863 | const sect_id: u16 = sect_id: { |
| 6864 | if (self.tlv_data_section_index) |i| { |
| 6865 | break :sect_id i; |
| 6866 | } else if (self.tlv_bss_section_index) |i| { |
| 6867 | break :sect_id i; |
| 6868 | } else unreachable; |
| 6869 | }; |
| 6870 | break :base_address self.getSection(.{ |
| 6871 | .seg = self.data_segment_cmd_index.?, |
| 6872 | .sect = sect_id, |
| 6873 | }).addr; |
| 6874 | } else 0; |
| 6875 | break :blk target_sym.n_value - base_address; |
| 6798 | 6876 | }; |
| 6799 | 6877 | |
| 6800 | 6878 | relocs.appendAssumeCapacity(.{ |
| ... | ... | @@ -6815,15 +6893,18 @@ fn snapshotState(self: *MachO) !void { |
| 6815 | 6893 | var next_i: usize = 0; |
| 6816 | 6894 | var last_rel: usize = 0; |
| 6817 | 6895 | while (next_i < atom.contained.items.len) : (next_i += 1) { |
| 6818 | | const loc = atom.contained.items[next_i]; |
| 6819 | | const cont_sym = self.locals.items[loc.local_sym_index]; |
| 6820 | | const cont_sym_name = self.getString(cont_sym.n_strx); |
| 6896 | const loc = SymbolWithLoc{ |
| 6897 | .sym_index = atom.contained.items[next_i].sym_index, |
| 6898 | .file = atom.file, |
| 6899 | }; |
| 6900 | const cont_sym = self.getSymbol(loc); |
| 6901 | const cont_sym_name = self.getSymbolName(loc); |
| 6821 | 6902 | var contained_node = Snapshot.Node{ |
| 6822 | 6903 | .address = cont_sym.n_value, |
| 6823 | 6904 | .tag = .atom_start, |
| 6824 | 6905 | .payload = .{ |
| 6825 | 6906 | .name = cont_sym_name, |
| 6826 | | .is_global = self.symbol_resolver.contains(cont_sym.n_strx), |
| 6907 | .is_global = self.globals.contains(cont_sym_name), |
| 6827 | 6908 | }, |
| 6828 | 6909 | }; |
| 6829 | 6910 | |
| ... | ... | @@ -6831,10 +6912,14 @@ fn snapshotState(self: *MachO) !void { |
| 6831 | 6912 | var inner_aliases = std.ArrayList([]const u8).init(arena); |
| 6832 | 6913 | while (true) { |
| 6833 | 6914 | if (next_i + 1 >= atom.contained.items.len) break; |
| 6834 | | const next_sym = self.locals.items[atom.contained.items[next_i + 1].local_sym_index]; |
| 6915 | const next_sym_loc = SymbolWithLoc{ |
| 6916 | .sym_index = atom.contained.items[next_i + 1].sym_index, |
| 6917 | .file = atom.file, |
| 6918 | }; |
| 6919 | const next_sym = self.getSymbol(next_sym_loc); |
| 6835 | 6920 | if (next_sym.n_value != cont_sym.n_value) break; |
| 6836 | | const next_sym_name = self.getString(next_sym.n_strx); |
| 6837 | | if (self.symbol_resolver.contains(next_sym.n_strx)) { |
| 6921 | const next_sym_name = self.getSymbolName(next_sym_loc); |
| 6922 | if (self.globals.contains(next_sym_name)) { |
| 6838 | 6923 | try inner_aliases.append(contained_node.payload.name); |
| 6839 | 6924 | contained_node.payload.name = next_sym_name; |
| 6840 | 6925 | contained_node.payload.is_global = true; |
| ... | ... | @@ -6843,7 +6928,10 @@ fn snapshotState(self: *MachO) !void { |
| 6843 | 6928 | } |
| 6844 | 6929 | |
| 6845 | 6930 | const cont_size = if (next_i + 1 < atom.contained.items.len) |
| 6846 | | self.locals.items[atom.contained.items[next_i + 1].local_sym_index].n_value - cont_sym.n_value |
| 6931 | self.getSymbol(.{ |
| 6932 | .sym_index = atom.contained.items[next_i + 1].sym_index, |
| 6933 | .file = atom.file, |
| 6934 | }).n_value - cont_sym.n_value |
| 6847 | 6935 | else |
| 6848 | 6936 | atom_sym.n_value + atom.size - cont_sym.n_value; |
| 6849 | 6937 | |
| ... | ... | @@ -6890,69 +6978,181 @@ fn snapshotState(self: *MachO) !void { |
| 6890 | 6978 | try writer.writeByte(']'); |
| 6891 | 6979 | } |
| 6892 | 6980 | |
| 6893 | | fn logSymtab(self: MachO) void { |
| 6894 | | log.debug("locals:", .{}); |
| 6895 | | for (self.locals.items) |sym, id| { |
| 6896 | | log.debug(" {d}: {s}: @{x} in {d}", .{ id, self.getString(sym.n_strx), sym.n_value, sym.n_sect }); |
| 6981 | fn logSymAttributes(sym: macho.nlist_64, buf: *[9]u8) []const u8 { |
| 6982 | mem.set(u8, buf[0..4], '_'); |
| 6983 | mem.set(u8, buf[4..], ' '); |
| 6984 | if (sym.sect()) { |
| 6985 | buf[0] = 's'; |
| 6897 | 6986 | } |
| 6898 | | |
| 6899 | | log.debug("globals:", .{}); |
| 6900 | | for (self.globals.items) |sym, id| { |
| 6901 | | log.debug(" {d}: {s}: @{x} in {d}", .{ id, self.getString(sym.n_strx), sym.n_value, sym.n_sect }); |
| 6987 | if (sym.ext()) { |
| 6988 | if (sym.weakDef() or sym.pext()) { |
| 6989 | buf[1] = 'w'; |
| 6990 | } else { |
| 6991 | buf[1] = 'e'; |
| 6992 | } |
| 6902 | 6993 | } |
| 6903 | | |
| 6904 | | log.debug("undefs:", .{}); |
| 6905 | | for (self.undefs.items) |sym, id| { |
| 6906 | | log.debug(" {d}: {s}: in {d}", .{ id, self.getString(sym.n_strx), sym.n_desc }); |
| 6994 | if (sym.tentative()) { |
| 6995 | buf[2] = 't'; |
| 6996 | } |
| 6997 | if (sym.undf()) { |
| 6998 | buf[3] = 'u'; |
| 6907 | 6999 | } |
| 7000 | if (sym.n_desc == N_DESC_GCED) { |
| 7001 | mem.copy(u8, buf[5..], "DEAD"); |
| 7002 | } |
| 7003 | return buf[0..]; |
| 7004 | } |
| 6908 | 7005 | |
| 6909 | | { |
| 6910 | | log.debug("resolver:", .{}); |
| 6911 | | var it = self.symbol_resolver.iterator(); |
| 6912 | | while (it.next()) |entry| { |
| 6913 | | log.debug(" {s} => {}", .{ self.getString(entry.key_ptr.*), entry.value_ptr.* }); |
| 7006 | fn logSymtab(self: *MachO) void { |
| 7007 | var buf: [9]u8 = undefined; |
| 7008 | |
| 7009 | log.debug("symtab:", .{}); |
| 7010 | for (self.objects.items) |object, id| { |
| 7011 | log.debug(" object({d}): {s}", .{ id, object.name }); |
| 7012 | for (object.symtab.items) |sym, sym_id| { |
| 7013 | const where = if (sym.undf() and !sym.tentative()) "ord" else "sect"; |
| 7014 | const def_index = if (sym.undf() and !sym.tentative()) |
| 7015 | @divTrunc(sym.n_desc, macho.N_SYMBOL_RESOLVER) |
| 7016 | else |
| 7017 | sym.n_sect; |
| 7018 | log.debug(" %{d}: {s} @{x} in {s}({d}), {s}", .{ |
| 7019 | sym_id, |
| 7020 | object.getString(sym.n_strx), |
| 7021 | sym.n_value, |
| 7022 | where, |
| 7023 | def_index, |
| 7024 | logSymAttributes(sym, &buf), |
| 7025 | }); |
| 6914 | 7026 | } |
| 6915 | 7027 | } |
| 7028 | log.debug(" object(null)", .{}); |
| 7029 | for (self.locals.items) |sym, sym_id| { |
| 7030 | const where = if (sym.undf() and !sym.tentative()) "ord" else "sect"; |
| 7031 | const def_index = if (sym.undf() and !sym.tentative()) |
| 7032 | @divTrunc(sym.n_desc, macho.N_SYMBOL_RESOLVER) |
| 7033 | else |
| 7034 | sym.n_sect; |
| 7035 | log.debug(" %{d}: {s} @{x} in {s}({d}), {s}", .{ |
| 7036 | sym_id, |
| 7037 | self.strtab.get(sym.n_strx), |
| 7038 | sym.n_value, |
| 7039 | where, |
| 7040 | def_index, |
| 7041 | logSymAttributes(sym, &buf), |
| 7042 | }); |
| 7043 | } |
| 7044 | |
| 7045 | log.debug("globals table:", .{}); |
| 7046 | for (self.globals.keys()) |name, id| { |
| 7047 | const value = self.globals.values()[id]; |
| 7048 | log.debug(" {s} => %{d} in object({d})", .{ name, value.sym_index, value.file }); |
| 7049 | } |
| 6916 | 7050 | |
| 6917 | 7051 | log.debug("GOT entries:", .{}); |
| 6918 | | for (self.got_entries_table.values()) |value| { |
| 6919 | | const key = self.got_entries.items[value].target; |
| 6920 | | const atom = self.got_entries.items[value].atom; |
| 6921 | | const n_value = self.locals.items[atom.local_sym_index].n_value; |
| 6922 | | switch (key) { |
| 6923 | | .local => |ndx| log.debug(" {d}: @{x}", .{ ndx, n_value }), |
| 6924 | | .global => |n_strx| log.debug(" {s}: @{x}", .{ self.getString(n_strx), n_value }), |
| 7052 | for (self.got_entries.items) |entry, i| { |
| 7053 | const atom_sym = entry.getSymbol(self); |
| 7054 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 7055 | const target_sym = self.getSymbol(entry.target); |
| 7056 | if (target_sym.undf()) { |
| 7057 | log.debug(" {d}@{x} => import('{s}')", .{ |
| 7058 | i, |
| 7059 | atom_sym.n_value, |
| 7060 | self.getSymbolName(entry.target), |
| 7061 | }); |
| 7062 | } else { |
| 7063 | log.debug(" {d}@{x} => local(%{d}) in object({d}) {s}", .{ |
| 7064 | i, |
| 7065 | atom_sym.n_value, |
| 7066 | entry.target.sym_index, |
| 7067 | entry.target.file, |
| 7068 | logSymAttributes(target_sym, &buf), |
| 7069 | }); |
| 6925 | 7070 | } |
| 6926 | 7071 | } |
| 6927 | 7072 | |
| 6928 | 7073 | log.debug("__thread_ptrs entries:", .{}); |
| 6929 | | for (self.tlv_ptr_entries_table.values()) |value| { |
| 6930 | | const key = self.tlv_ptr_entries.items[value].target; |
| 6931 | | const atom = self.tlv_ptr_entries.items[value].atom; |
| 6932 | | const n_value = self.locals.items[atom.local_sym_index].n_value; |
| 6933 | | assert(key == .global); |
| 6934 | | log.debug(" {s}: @{x}", .{ self.getString(key.global), n_value }); |
| 7074 | for (self.tlv_ptr_entries.items) |entry, i| { |
| 7075 | const atom_sym = entry.getSymbol(self); |
| 7076 | if (atom_sym.n_desc == N_DESC_GCED) continue; |
| 7077 | const target_sym = self.getSymbol(entry.target); |
| 7078 | assert(target_sym.undf()); |
| 7079 | log.debug(" {d}@{x} => import('{s}')", .{ |
| 7080 | i, |
| 7081 | atom_sym.n_value, |
| 7082 | self.getSymbolName(entry.target), |
| 7083 | }); |
| 6935 | 7084 | } |
| 6936 | 7085 | |
| 6937 | | log.debug("stubs:", .{}); |
| 6938 | | for (self.stubs_table.keys()) |key| { |
| 6939 | | const value = self.stubs_table.get(key).?; |
| 6940 | | const atom = self.stubs.items[value]; |
| 6941 | | const sym = self.locals.items[atom.local_sym_index]; |
| 6942 | | log.debug(" {s}: @{x}", .{ self.getString(key), sym.n_value }); |
| 7086 | log.debug("stubs entries:", .{}); |
| 7087 | for (self.stubs.items) |entry, i| { |
| 7088 | const target_sym = self.getSymbol(entry.target); |
| 7089 | const atom_sym = entry.getSymbol(self); |
| 7090 | assert(target_sym.undf()); |
| 7091 | log.debug(" {d}@{x} => import('{s}')", .{ |
| 7092 | i, |
| 7093 | atom_sym.n_value, |
| 7094 | self.getSymbolName(entry.target), |
| 7095 | }); |
| 6943 | 7096 | } |
| 6944 | 7097 | } |
| 6945 | 7098 | |
| 6946 | | fn logSectionOrdinals(self: MachO) void { |
| 7099 | fn logSectionOrdinals(self: *MachO) void { |
| 6947 | 7100 | for (self.section_ordinals.keys()) |match, i| { |
| 6948 | | const seg = self.load_commands.items[match.seg].segment; |
| 6949 | | const sect = seg.sections.items[match.sect]; |
| 6950 | | log.debug("ord {d}: {d},{d} => {s},{s}", .{ |
| 6951 | | i + 1, |
| 6952 | | match.seg, |
| 6953 | | match.sect, |
| 6954 | | sect.segName(), |
| 6955 | | sect.sectName(), |
| 7101 | const sect = self.getSection(match); |
| 7102 | log.debug("sect({d}, '{s},{s}')", .{ i + 1, sect.segName(), sect.sectName() }); |
| 7103 | } |
| 7104 | } |
| 7105 | |
| 7106 | fn logAtoms(self: *MachO) void { |
| 7107 | log.debug("atoms:", .{}); |
| 7108 | var it = self.atoms.iterator(); |
| 7109 | while (it.next()) |entry| { |
| 7110 | const match = entry.key_ptr.*; |
| 7111 | var atom = entry.value_ptr.*; |
| 7112 | |
| 7113 | while (atom.prev) |prev| { |
| 7114 | atom = prev; |
| 7115 | } |
| 7116 | |
| 7117 | const sect = self.getSection(match); |
| 7118 | log.debug("{s},{s}", .{ sect.segName(), sect.sectName() }); |
| 7119 | |
| 7120 | while (true) { |
| 7121 | self.logAtom(atom); |
| 7122 | if (atom.next) |next| { |
| 7123 | atom = next; |
| 7124 | } else break; |
| 7125 | } |
| 7126 | } |
| 7127 | } |
| 7128 | |
| 7129 | pub fn logAtom(self: *MachO, atom: *const Atom) void { |
| 7130 | const sym = atom.getSymbol(self); |
| 7131 | const sym_name = atom.getName(self); |
| 7132 | log.debug(" ATOM(%{d}, '{s}') @ {x} (sizeof({x}), alignof({x})) in object({d}) in sect({d})", .{ |
| 7133 | atom.sym_index, |
| 7134 | sym_name, |
| 7135 | sym.n_value, |
| 7136 | atom.size, |
| 7137 | atom.alignment, |
| 7138 | atom.file, |
| 7139 | sym.n_sect, |
| 7140 | }); |
| 7141 | |
| 7142 | for (atom.contained.items) |sym_off| { |
| 7143 | const inner_sym = self.getSymbol(.{ |
| 7144 | .sym_index = sym_off.sym_index, |
| 7145 | .file = atom.file, |
| 7146 | }); |
| 7147 | const inner_sym_name = self.getSymbolName(.{ |
| 7148 | .sym_index = sym_off.sym_index, |
| 7149 | .file = atom.file, |
| 7150 | }); |
| 7151 | log.debug(" (%{d}, '{s}') @ {x} ({x})", .{ |
| 7152 | sym_off.sym_index, |
| 7153 | inner_sym_name, |
| 7154 | inner_sym.n_value, |
| 7155 | sym_off.offset, |
| 6956 | 7156 | }); |
| 6957 | 7157 | } |
| 6958 | 7158 | } |