| ... | ... | @@ -10,1944 +10,4382 @@ const mem = std.mem; |
| 10 | 10 | |
| 11 | 11 | const aarch64 = @import("../../arch/aarch64/bits.zig"); |
| 12 | 12 | const bind = @import("bind.zig"); |
| 13 | const dead_strip = @import("dead_strip.zig"); |
| 14 | const fat = @import("fat.zig"); |
| 13 | 15 | const link = @import("../../link.zig"); |
| 16 | const thunks = @import("thunks.zig"); |
| 14 | 17 | const trace = @import("../../tracy.zig").trace; |
| 15 | 18 | |
| 16 | | const Atom = MachO.Atom; |
| 19 | const Allocator = mem.Allocator; |
| 20 | const Archive = @import("Archive.zig"); |
| 21 | const Atom = @import("ZldAtom.zig"); |
| 17 | 22 | const Cache = @import("../../Cache.zig"); |
| 18 | 23 | const CodeSignature = @import("CodeSignature.zig"); |
| 19 | 24 | const Compilation = @import("../../Compilation.zig"); |
| 25 | const DwarfInfo = @import("DwarfInfo.zig"); |
| 20 | 26 | const Dylib = @import("Dylib.zig"); |
| 21 | 27 | const MachO = @import("../MachO.zig"); |
| 28 | const LibStub = @import("../tapi.zig").LibStub; |
| 22 | 29 | const Object = @import("Object.zig"); |
| 23 | | const SymbolWithLoc = MachO.SymbolWithLoc; |
| 30 | const StringTable = @import("../strtab.zig").StringTable; |
| 24 | 31 | const Trie = @import("Trie.zig"); |
| 25 | 32 | |
| 26 | | const dead_strip = @import("dead_strip.zig"); |
| 27 | | |
| 28 | | pub fn linkWithZld(macho_file: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) !void { |
| 29 | | const tracy = trace(@src()); |
| 30 | | defer tracy.end(); |
| 31 | | |
| 32 | | const gpa = macho_file.base.allocator; |
| 33 | | var arena_allocator = std.heap.ArenaAllocator.init(gpa); |
| 34 | | defer arena_allocator.deinit(); |
| 35 | | const arena = arena_allocator.allocator(); |
| 33 | pub const Zld = struct { |
| 34 | gpa: Allocator, |
| 35 | file: fs.File, |
| 36 | page_size: u16, |
| 37 | options: link.Options, |
| 36 | 38 | |
| 37 | | const directory = macho_file.base.options.emit.?.directory; // Just an alias to make it shorter to type. |
| 38 | | const full_out_path = try directory.join(arena, &[_][]const u8{macho_file.base.options.emit.?.sub_path}); |
| 39 | objects: std.ArrayListUnmanaged(Object) = .{}, |
| 40 | archives: std.ArrayListUnmanaged(Archive) = .{}, |
| 41 | dylibs: std.ArrayListUnmanaged(Dylib) = .{}, |
| 42 | dylibs_map: std.StringHashMapUnmanaged(u16) = .{}, |
| 43 | referenced_dylibs: std.AutoArrayHashMapUnmanaged(u16, void) = .{}, |
| 39 | 44 | |
| 40 | | // If there is no Zig code to compile, then we should skip flushing the output file because it |
| 41 | | // will not be part of the linker line anyway. |
| 42 | | const module_obj_path: ?[]const u8 = if (macho_file.base.options.module) |module| blk: { |
| 43 | | if (macho_file.base.options.use_stage1) { |
| 44 | | const obj_basename = try std.zig.binNameAlloc(arena, .{ |
| 45 | | .root_name = macho_file.base.options.root_name, |
| 46 | | .target = macho_file.base.options.target, |
| 47 | | .output_mode = .Obj, |
| 48 | | }); |
| 49 | | switch (macho_file.base.options.cache_mode) { |
| 50 | | .incremental => break :blk try module.zig_cache_artifact_directory.join( |
| 51 | | arena, |
| 52 | | &[_][]const u8{obj_basename}, |
| 53 | | ), |
| 54 | | .whole => break :blk try fs.path.join(arena, &.{ |
| 55 | | fs.path.dirname(full_out_path).?, obj_basename, |
| 56 | | }), |
| 57 | | } |
| 58 | | } |
| 45 | segments: std.ArrayListUnmanaged(macho.segment_command_64) = .{}, |
| 46 | sections: std.MultiArrayList(Section) = .{}, |
| 59 | 47 | |
| 60 | | try macho_file.flushModule(comp, prog_node); |
| 48 | locals: std.ArrayListUnmanaged(macho.nlist_64) = .{}, |
| 49 | globals: std.ArrayListUnmanaged(SymbolWithLoc) = .{}, |
| 61 | 50 | |
| 62 | | if (fs.path.dirname(full_out_path)) |dirname| { |
| 63 | | break :blk try fs.path.join(arena, &.{ dirname, macho_file.base.intermediary_basename.? }); |
| 64 | | } else { |
| 65 | | break :blk macho_file.base.intermediary_basename.?; |
| 66 | | } |
| 67 | | } else null; |
| 51 | entry_index: ?u32 = null, |
| 52 | mh_execute_header_index: ?u32 = null, |
| 53 | dso_handle_index: ?u32 = null, |
| 54 | dyld_stub_binder_index: ?u32 = null, |
| 55 | dyld_private_sym_index: ?u32 = null, |
| 56 | stub_helper_preamble_sym_index: ?u32 = null, |
| 68 | 57 | |
| 69 | | var sub_prog_node = prog_node.start("MachO Flush", 0); |
| 70 | | sub_prog_node.activate(); |
| 71 | | sub_prog_node.context.refresh(); |
| 72 | | defer sub_prog_node.end(); |
| 58 | strtab: StringTable(.strtab) = .{}, |
| 73 | 59 | |
| 74 | | const cpu_arch = macho_file.base.options.target.cpu.arch; |
| 75 | | const os_tag = macho_file.base.options.target.os.tag; |
| 76 | | const abi = macho_file.base.options.target.abi; |
| 77 | | const is_lib = macho_file.base.options.output_mode == .Lib; |
| 78 | | const is_dyn_lib = macho_file.base.options.link_mode == .Dynamic and is_lib; |
| 79 | | const is_exe_or_dyn_lib = is_dyn_lib or macho_file.base.options.output_mode == .Exe; |
| 80 | | const stack_size = macho_file.base.options.stack_size_override orelse 0; |
| 81 | | const is_debug_build = macho_file.base.options.optimize_mode == .Debug; |
| 82 | | const gc_sections = macho_file.base.options.gc_sections orelse !is_debug_build; |
| 60 | tlv_ptr_entries: std.ArrayListUnmanaged(IndirectPointer) = .{}, |
| 61 | tlv_ptr_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, |
| 83 | 62 | |
| 84 | | const id_symlink_basename = "zld.id"; |
| 63 | got_entries: std.ArrayListUnmanaged(IndirectPointer) = .{}, |
| 64 | got_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, |
| 85 | 65 | |
| 86 | | var man: Cache.Manifest = undefined; |
| 87 | | defer if (!macho_file.base.options.disable_lld_caching) man.deinit(); |
| 66 | stubs: std.ArrayListUnmanaged(IndirectPointer) = .{}, |
| 67 | stubs_table: std.AutoHashMapUnmanaged(SymbolWithLoc, u32) = .{}, |
| 88 | 68 | |
| 89 | | var digest: [Cache.hex_digest_len]u8 = undefined; |
| 69 | thunk_table: std.AutoHashMapUnmanaged(AtomIndex, thunks.ThunkIndex) = .{}, |
| 70 | thunks: std.ArrayListUnmanaged(thunks.Thunk) = .{}, |
| 90 | 71 | |
| 91 | | if (!macho_file.base.options.disable_lld_caching) { |
| 92 | | man = comp.cache_parent.obtain(); |
| 72 | atoms: std.ArrayListUnmanaged(Atom) = .{}, |
| 93 | 73 | |
| 94 | | // We are about to obtain this lock, so here we give other processes a chance first. |
| 95 | | macho_file.base.releaseLock(); |
| 74 | fn parseObject(self: *Zld, path: []const u8) !bool { |
| 75 | const gpa = self.gpa; |
| 76 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { |
| 77 | error.FileNotFound => return false, |
| 78 | else => |e| return e, |
| 79 | }; |
| 80 | defer file.close(); |
| 81 | |
| 82 | const name = try gpa.dupe(u8, path); |
| 83 | errdefer gpa.free(name); |
| 84 | const cpu_arch = self.options.target.cpu.arch; |
| 85 | const mtime: u64 = mtime: { |
| 86 | const stat = file.stat() catch break :mtime 0; |
| 87 | break :mtime @intCast(u64, @divFloor(stat.mtime, 1_000_000_000)); |
| 88 | }; |
| 89 | const file_stat = try file.stat(); |
| 90 | const file_size = math.cast(usize, file_stat.size) orelse return error.Overflow; |
| 91 | const contents = try file.readToEndAllocOptions(gpa, file_size, file_size, @alignOf(u64), null); |
| 92 | |
| 93 | var object = Object{ |
| 94 | .name = name, |
| 95 | .mtime = mtime, |
| 96 | .contents = contents, |
| 97 | }; |
| 96 | 98 | |
| 97 | | comptime assert(Compilation.link_hash_implementation_version == 7); |
| 99 | object.parse(gpa, cpu_arch) catch |err| switch (err) { |
| 100 | error.EndOfStream, error.NotObject => { |
| 101 | object.deinit(gpa); |
| 102 | return false; |
| 103 | }, |
| 104 | else => |e| return e, |
| 105 | }; |
| 98 | 106 | |
| 99 | | for (macho_file.base.options.objects) |obj| { |
| 100 | | _ = try man.addFile(obj.path, null); |
| 101 | | man.hash.add(obj.must_link); |
| 102 | | } |
| 103 | | for (comp.c_object_table.keys()) |key| { |
| 104 | | _ = try man.addFile(key.status.success.object_path, null); |
| 105 | | } |
| 106 | | try man.addOptionalFile(module_obj_path); |
| 107 | | // We can skip hashing libc and libc++ components that we are in charge of building from Zig |
| 108 | | // installation sources because they are always a product of the compiler version + target information. |
| 109 | | man.hash.add(stack_size); |
| 110 | | man.hash.addOptional(macho_file.base.options.pagezero_size); |
| 111 | | man.hash.addOptional(macho_file.base.options.search_strategy); |
| 112 | | man.hash.addOptional(macho_file.base.options.headerpad_size); |
| 113 | | man.hash.add(macho_file.base.options.headerpad_max_install_names); |
| 114 | | man.hash.add(gc_sections); |
| 115 | | man.hash.add(macho_file.base.options.dead_strip_dylibs); |
| 116 | | man.hash.add(macho_file.base.options.strip); |
| 117 | | man.hash.addListOfBytes(macho_file.base.options.lib_dirs); |
| 118 | | man.hash.addListOfBytes(macho_file.base.options.framework_dirs); |
| 119 | | link.hashAddSystemLibs(&man.hash, macho_file.base.options.frameworks); |
| 120 | | man.hash.addListOfBytes(macho_file.base.options.rpath_list); |
| 121 | | if (is_dyn_lib) { |
| 122 | | man.hash.addOptionalBytes(macho_file.base.options.install_name); |
| 123 | | man.hash.addOptional(macho_file.base.options.version); |
| 124 | | } |
| 125 | | link.hashAddSystemLibs(&man.hash, macho_file.base.options.system_libs); |
| 126 | | man.hash.addOptionalBytes(macho_file.base.options.sysroot); |
| 127 | | try man.addOptionalFile(macho_file.base.options.entitlements); |
| 107 | try self.objects.append(gpa, object); |
| 128 | 108 | |
| 129 | | // We don't actually care whether it's a cache hit or miss; we just need the digest and the lock. |
| 130 | | _ = try man.hit(); |
| 131 | | digest = man.final(); |
| 109 | return true; |
| 110 | } |
| 132 | 111 | |
| 133 | | var prev_digest_buf: [digest.len]u8 = undefined; |
| 134 | | const prev_digest: []u8 = Cache.readSmallFile( |
| 135 | | directory.handle, |
| 136 | | id_symlink_basename, |
| 137 | | &prev_digest_buf, |
| 138 | | ) catch |err| blk: { |
| 139 | | log.debug("MachO Zld new_digest={s} error: {s}", .{ |
| 140 | | std.fmt.fmtSliceHexLower(&digest), |
| 141 | | @errorName(err), |
| 142 | | }); |
| 143 | | // Handle this as a cache miss. |
| 144 | | break :blk prev_digest_buf[0..0]; |
| 112 | fn parseArchive(self: *Zld, path: []const u8, force_load: bool) !bool { |
| 113 | const gpa = self.gpa; |
| 114 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { |
| 115 | error.FileNotFound => return false, |
| 116 | else => |e| return e, |
| 117 | }; |
| 118 | errdefer file.close(); |
| 119 | |
| 120 | const name = try gpa.dupe(u8, path); |
| 121 | errdefer gpa.free(name); |
| 122 | const cpu_arch = self.options.target.cpu.arch; |
| 123 | const reader = file.reader(); |
| 124 | const fat_offset = try fat.getLibraryOffset(reader, cpu_arch); |
| 125 | try reader.context.seekTo(fat_offset); |
| 126 | |
| 127 | var archive = Archive{ |
| 128 | .name = name, |
| 129 | .fat_offset = fat_offset, |
| 130 | .file = file, |
| 145 | 131 | }; |
| 146 | | if (mem.eql(u8, prev_digest, &digest)) { |
| 147 | | // Hot diggity dog! The output binary is already there. |
| 148 | | log.debug("MachO Zld digest={s} match - skipping invocation", .{ |
| 149 | | std.fmt.fmtSliceHexLower(&digest), |
| 150 | | }); |
| 151 | | macho_file.base.lock = man.toOwnedLock(); |
| 152 | | return; |
| 153 | | } |
| 154 | | log.debug("MachO Zld prev_digest={s} new_digest={s}", .{ |
| 155 | | std.fmt.fmtSliceHexLower(prev_digest), |
| 156 | | std.fmt.fmtSliceHexLower(&digest), |
| 157 | | }); |
| 158 | 132 | |
| 159 | | // We are about to change the output file to be different, so we invalidate the build hash now. |
| 160 | | directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) { |
| 161 | | error.FileNotFound => {}, |
| 133 | archive.parse(gpa, reader) catch |err| switch (err) { |
| 134 | error.EndOfStream, error.NotArchive => { |
| 135 | archive.deinit(gpa); |
| 136 | return false; |
| 137 | }, |
| 162 | 138 | else => |e| return e, |
| 163 | 139 | }; |
| 164 | | } |
| 165 | 140 | |
| 166 | | if (macho_file.base.options.output_mode == .Obj) { |
| 167 | | // LLD's MachO driver does not support the equivalent of `-r` so we do a simple file copy |
| 168 | | // here. TODO: think carefully about how we can avoid this redundant operation when doing |
| 169 | | // build-obj. See also the corresponding TODO in linkAsArchive. |
| 170 | | const the_object_path = blk: { |
| 171 | | if (macho_file.base.options.objects.len != 0) { |
| 172 | | break :blk macho_file.base.options.objects[0].path; |
| 141 | if (force_load) { |
| 142 | defer archive.deinit(gpa); |
| 143 | // Get all offsets from the ToC |
| 144 | var offsets = std.AutoArrayHashMap(u32, void).init(gpa); |
| 145 | defer offsets.deinit(); |
| 146 | for (archive.toc.values()) |offs| { |
| 147 | for (offs.items) |off| { |
| 148 | _ = try offsets.getOrPut(off); |
| 149 | } |
| 150 | } |
| 151 | for (offsets.keys()) |off| { |
| 152 | const object = try archive.parseObject(gpa, cpu_arch, off); |
| 153 | try self.objects.append(gpa, object); |
| 173 | 154 | } |
| 155 | } else { |
| 156 | try self.archives.append(gpa, archive); |
| 157 | } |
| 174 | 158 | |
| 175 | | if (comp.c_object_table.count() != 0) |
| 176 | | break :blk comp.c_object_table.keys()[0].status.success.object_path; |
| 159 | return true; |
| 160 | } |
| 177 | 161 | |
| 178 | | if (module_obj_path) |p| |
| 179 | | break :blk p; |
| 162 | const ParseDylibError = error{ |
| 163 | OutOfMemory, |
| 164 | EmptyStubFile, |
| 165 | MismatchedCpuArchitecture, |
| 166 | UnsupportedCpuArchitecture, |
| 167 | EndOfStream, |
| 168 | } || fs.File.OpenError || std.os.PReadError || Dylib.Id.ParseError; |
| 169 | |
| 170 | const DylibCreateOpts = struct { |
| 171 | syslibroot: ?[]const u8, |
| 172 | id: ?Dylib.Id = null, |
| 173 | dependent: bool = false, |
| 174 | needed: bool = false, |
| 175 | weak: bool = false, |
| 176 | }; |
| 180 | 177 | |
| 181 | | // TODO I think this is unreachable. Audit this situation when solving the above TODO |
| 182 | | // regarding eliding redundant object -> object transformations. |
| 183 | | return error.NoObjectsToLink; |
| 178 | fn parseDylib( |
| 179 | self: *Zld, |
| 180 | path: []const u8, |
| 181 | dependent_libs: anytype, |
| 182 | opts: DylibCreateOpts, |
| 183 | ) ParseDylibError!bool { |
| 184 | const gpa = self.gpa; |
| 185 | const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { |
| 186 | error.FileNotFound => return false, |
| 187 | else => |e| return e, |
| 188 | }; |
| 189 | defer file.close(); |
| 190 | |
| 191 | const cpu_arch = self.options.target.cpu.arch; |
| 192 | const file_stat = try file.stat(); |
| 193 | var file_size = math.cast(usize, file_stat.size) orelse return error.Overflow; |
| 194 | |
| 195 | const reader = file.reader(); |
| 196 | const fat_offset = math.cast(usize, try fat.getLibraryOffset(reader, cpu_arch)) orelse |
| 197 | return error.Overflow; |
| 198 | try file.seekTo(fat_offset); |
| 199 | file_size -= fat_offset; |
| 200 | |
| 201 | const contents = try file.readToEndAllocOptions(gpa, file_size, file_size, @alignOf(u64), null); |
| 202 | defer gpa.free(contents); |
| 203 | |
| 204 | const dylib_id = @intCast(u16, self.dylibs.items.len); |
| 205 | var dylib = Dylib{ .weak = opts.weak }; |
| 206 | |
| 207 | dylib.parseFromBinary( |
| 208 | gpa, |
| 209 | cpu_arch, |
| 210 | dylib_id, |
| 211 | dependent_libs, |
| 212 | path, |
| 213 | contents, |
| 214 | ) catch |err| switch (err) { |
| 215 | error.EndOfStream, error.NotDylib => { |
| 216 | try file.seekTo(0); |
| 217 | |
| 218 | var lib_stub = LibStub.loadFromFile(gpa, file) catch { |
| 219 | dylib.deinit(gpa); |
| 220 | return false; |
| 221 | }; |
| 222 | defer lib_stub.deinit(); |
| 223 | |
| 224 | try dylib.parseFromStub( |
| 225 | gpa, |
| 226 | self.options.target, |
| 227 | lib_stub, |
| 228 | dylib_id, |
| 229 | dependent_libs, |
| 230 | path, |
| 231 | ); |
| 232 | }, |
| 233 | else => |e| return e, |
| 184 | 234 | }; |
| 185 | | // This can happen when using --enable-cache and using the stage1 backend. In this case |
| 186 | | // we can skip the file copy. |
| 187 | | if (!mem.eql(u8, the_object_path, full_out_path)) { |
| 188 | | try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{}); |
| 189 | | } |
| 190 | | } else { |
| 191 | | const sub_path = macho_file.base.options.emit.?.sub_path; |
| 192 | | if (macho_file.base.file == null) { |
| 193 | | macho_file.base.file = try directory.handle.createFile(sub_path, .{ |
| 194 | | .truncate = true, |
| 195 | | .read = true, |
| 196 | | .mode = link.determineMode(macho_file.base.options), |
| 197 | | }); |
| 198 | | } |
| 199 | | // Index 0 is always a null symbol. |
| 200 | | try macho_file.locals.append(gpa, .{ |
| 201 | | .n_strx = 0, |
| 202 | | .n_type = 0, |
| 203 | | .n_sect = 0, |
| 204 | | .n_desc = 0, |
| 205 | | .n_value = 0, |
| 206 | | }); |
| 207 | | try macho_file.strtab.buffer.append(gpa, 0); |
| 208 | | try initSections(macho_file); |
| 209 | | |
| 210 | | var lib_not_found = false; |
| 211 | | var framework_not_found = false; |
| 212 | | |
| 213 | | // Positional arguments to the linker such as object files and static archives. |
| 214 | | var positionals = std.ArrayList([]const u8).init(arena); |
| 215 | | try positionals.ensureUnusedCapacity(macho_file.base.options.objects.len); |
| 216 | 235 | |
| 217 | | var must_link_archives = std.StringArrayHashMap(void).init(arena); |
| 218 | | try must_link_archives.ensureUnusedCapacity(macho_file.base.options.objects.len); |
| 236 | if (opts.id) |id| { |
| 237 | if (dylib.id.?.current_version < id.compatibility_version) { |
| 238 | log.warn("found dylib is incompatible with the required minimum version", .{}); |
| 239 | log.warn(" dylib: {s}", .{id.name}); |
| 240 | log.warn(" required minimum version: {}", .{id.compatibility_version}); |
| 241 | log.warn(" dylib version: {}", .{dylib.id.?.current_version}); |
| 219 | 242 | |
| 220 | | for (macho_file.base.options.objects) |obj| { |
| 221 | | if (must_link_archives.contains(obj.path)) continue; |
| 222 | | if (obj.must_link) { |
| 223 | | _ = must_link_archives.getOrPutAssumeCapacity(obj.path); |
| 224 | | } else { |
| 225 | | _ = positionals.appendAssumeCapacity(obj.path); |
| 243 | // TODO maybe this should be an error and facilitate auto-cleanup? |
| 244 | dylib.deinit(gpa); |
| 245 | return false; |
| 226 | 246 | } |
| 227 | 247 | } |
| 228 | 248 | |
| 229 | | for (comp.c_object_table.keys()) |key| { |
| 230 | | try positionals.append(key.status.success.object_path); |
| 231 | | } |
| 249 | try self.dylibs.append(gpa, dylib); |
| 250 | try self.dylibs_map.putNoClobber(gpa, dylib.id.?.name, dylib_id); |
| 232 | 251 | |
| 233 | | if (module_obj_path) |p| { |
| 234 | | try positionals.append(p); |
| 235 | | } |
| 252 | const should_link_dylib_even_if_unreachable = blk: { |
| 253 | if (self.options.dead_strip_dylibs and !opts.needed) break :blk false; |
| 254 | break :blk !(opts.dependent or self.referenced_dylibs.contains(dylib_id)); |
| 255 | }; |
| 236 | 256 | |
| 237 | | if (comp.compiler_rt_lib) |lib| { |
| 238 | | try positionals.append(lib.full_object_path); |
| 257 | if (should_link_dylib_even_if_unreachable) { |
| 258 | try self.referenced_dylibs.putNoClobber(gpa, dylib_id, {}); |
| 239 | 259 | } |
| 240 | 260 | |
| 241 | | // libc++ dep |
| 242 | | if (macho_file.base.options.link_libcpp) { |
| 243 | | try positionals.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 244 | | try positionals.append(comp.libcxx_static_lib.?.full_object_path); |
| 261 | return true; |
| 262 | } |
| 263 | |
| 264 | fn parseInputFiles( |
| 265 | self: *Zld, |
| 266 | files: []const []const u8, |
| 267 | syslibroot: ?[]const u8, |
| 268 | dependent_libs: anytype, |
| 269 | ) !void { |
| 270 | for (files) |file_name| { |
| 271 | const full_path = full_path: { |
| 272 | var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; |
| 273 | break :full_path try fs.realpath(file_name, &buffer); |
| 274 | }; |
| 275 | log.debug("parsing input file path '{s}'", .{full_path}); |
| 276 | |
| 277 | if (try self.parseObject(full_path)) continue; |
| 278 | if (try self.parseArchive(full_path, false)) continue; |
| 279 | if (try self.parseDylib(full_path, dependent_libs, .{ |
| 280 | .syslibroot = syslibroot, |
| 281 | })) continue; |
| 282 | |
| 283 | log.debug("unknown filetype for positional input file: '{s}'", .{file_name}); |
| 245 | 284 | } |
| 285 | } |
| 246 | 286 | |
| 247 | | // Shared and static libraries passed via `-l` flag. |
| 248 | | var candidate_libs = std.StringArrayHashMap(link.SystemLib).init(arena); |
| 287 | fn parseAndForceLoadStaticArchives(self: *Zld, files: []const []const u8) !void { |
| 288 | for (files) |file_name| { |
| 289 | const full_path = full_path: { |
| 290 | var buffer: [fs.MAX_PATH_BYTES]u8 = undefined; |
| 291 | break :full_path try fs.realpath(file_name, &buffer); |
| 292 | }; |
| 293 | log.debug("parsing and force loading static archive '{s}'", .{full_path}); |
| 249 | 294 | |
| 250 | | const system_lib_names = macho_file.base.options.system_libs.keys(); |
| 251 | | for (system_lib_names) |system_lib_name| { |
| 252 | | // By this time, we depend on these libs being dynamically linked libraries and not static libraries |
| 253 | | // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which |
| 254 | | // case we want to avoid prepending "-l". |
| 255 | | if (Compilation.classifyFileExt(system_lib_name) == .shared_library) { |
| 256 | | try positionals.append(system_lib_name); |
| 257 | | continue; |
| 258 | | } |
| 295 | if (try self.parseArchive(full_path, true)) continue; |
| 296 | log.debug("unknown filetype: expected static archive: '{s}'", .{file_name}); |
| 297 | } |
| 298 | } |
| 259 | 299 | |
| 260 | | const system_lib_info = macho_file.base.options.system_libs.get(system_lib_name).?; |
| 261 | | try candidate_libs.put(system_lib_name, .{ |
| 262 | | .needed = system_lib_info.needed, |
| 263 | | .weak = system_lib_info.weak, |
| 264 | | }); |
| 300 | fn parseLibs( |
| 301 | self: *Zld, |
| 302 | lib_names: []const []const u8, |
| 303 | lib_infos: []const link.SystemLib, |
| 304 | syslibroot: ?[]const u8, |
| 305 | dependent_libs: anytype, |
| 306 | ) !void { |
| 307 | for (lib_names) |lib, i| { |
| 308 | const lib_info = lib_infos[i]; |
| 309 | log.debug("parsing lib path '{s}'", .{lib}); |
| 310 | if (try self.parseDylib(lib, dependent_libs, .{ |
| 311 | .syslibroot = syslibroot, |
| 312 | .needed = lib_info.needed, |
| 313 | .weak = lib_info.weak, |
| 314 | })) continue; |
| 315 | if (try self.parseArchive(lib, false)) continue; |
| 316 | |
| 317 | log.debug("unknown filetype for a library: '{s}'", .{lib}); |
| 265 | 318 | } |
| 319 | } |
| 266 | 320 | |
| 267 | | var lib_dirs = std.ArrayList([]const u8).init(arena); |
| 268 | | for (macho_file.base.options.lib_dirs) |dir| { |
| 269 | | if (try MachO.resolveSearchDir(arena, dir, macho_file.base.options.sysroot)) |search_dir| { |
| 270 | | try lib_dirs.append(search_dir); |
| 321 | fn parseDependentLibs(self: *Zld, syslibroot: ?[]const u8, dependent_libs: anytype) !void { |
| 322 | // At this point, we can now parse dependents of dylibs preserving the inclusion order of: |
| 323 | // 1) anything on the linker line is parsed first |
| 324 | // 2) afterwards, we parse dependents of the included dylibs |
| 325 | // TODO this should not be performed if the user specifies `-flat_namespace` flag. |
| 326 | // See ld64 manpages. |
| 327 | var arena_alloc = std.heap.ArenaAllocator.init(self.gpa); |
| 328 | const arena = arena_alloc.allocator(); |
| 329 | defer arena_alloc.deinit(); |
| 330 | |
| 331 | while (dependent_libs.readItem()) |*dep_id| { |
| 332 | defer dep_id.id.deinit(self.gpa); |
| 333 | |
| 334 | if (self.dylibs_map.contains(dep_id.id.name)) continue; |
| 335 | |
| 336 | const weak = self.dylibs.items[dep_id.parent].weak; |
| 337 | const has_ext = blk: { |
| 338 | const basename = fs.path.basename(dep_id.id.name); |
| 339 | break :blk mem.lastIndexOfScalar(u8, basename, '.') != null; |
| 340 | }; |
| 341 | const extension = if (has_ext) fs.path.extension(dep_id.id.name) else ""; |
| 342 | const without_ext = if (has_ext) blk: { |
| 343 | const index = mem.lastIndexOfScalar(u8, dep_id.id.name, '.') orelse unreachable; |
| 344 | break :blk dep_id.id.name[0..index]; |
| 345 | } else dep_id.id.name; |
| 346 | |
| 347 | for (&[_][]const u8{ extension, ".tbd" }) |ext| { |
| 348 | const with_ext = try std.fmt.allocPrint(arena, "{s}{s}", .{ without_ext, ext }); |
| 349 | const full_path = if (syslibroot) |root| try fs.path.join(arena, &.{ root, with_ext }) else with_ext; |
| 350 | |
| 351 | log.debug("trying dependency at fully resolved path {s}", .{full_path}); |
| 352 | |
| 353 | const did_parse_successfully = try self.parseDylib(full_path, dependent_libs, .{ |
| 354 | .id = dep_id.id, |
| 355 | .syslibroot = syslibroot, |
| 356 | .dependent = true, |
| 357 | .weak = weak, |
| 358 | }); |
| 359 | if (did_parse_successfully) break; |
| 271 | 360 | } else { |
| 272 | | log.warn("directory not found for '-L{s}'", .{dir}); |
| 361 | log.debug("unable to resolve dependency {s}", .{dep_id.id.name}); |
| 273 | 362 | } |
| 274 | 363 | } |
| 364 | } |
| 275 | 365 | |
| 276 | | var libs = std.StringArrayHashMap(link.SystemLib).init(arena); |
| 366 | pub fn getOutputSection(self: *Zld, sect: macho.section_64) !?u8 { |
| 367 | const segname = sect.segName(); |
| 368 | const sectname = sect.sectName(); |
| 369 | const res: ?u8 = blk: { |
| 370 | if (mem.eql(u8, "__LLVM", segname)) { |
| 371 | log.debug("TODO LLVM section: type 0x{x}, name '{s},{s}'", .{ |
| 372 | sect.flags, segname, sectname, |
| 373 | }); |
| 374 | break :blk null; |
| 375 | } |
| 277 | 376 | |
| 278 | | // Assume ld64 default -search_paths_first if no strategy specified. |
| 279 | | const search_strategy = macho_file.base.options.search_strategy orelse .paths_first; |
| 280 | | outer: for (candidate_libs.keys()) |lib_name| { |
| 281 | | switch (search_strategy) { |
| 282 | | .paths_first => { |
| 283 | | // Look in each directory for a dylib (stub first), and then for archive |
| 284 | | for (lib_dirs.items) |dir| { |
| 285 | | for (&[_][]const u8{ ".tbd", ".dylib", ".a" }) |ext| { |
| 286 | | if (try MachO.resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 287 | | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 288 | | continue :outer; |
| 289 | | } |
| 290 | | } |
| 291 | | } else { |
| 292 | | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 293 | | lib_not_found = true; |
| 377 | if (sect.isCode()) { |
| 378 | break :blk self.getSectionByName("__TEXT", "__text") orelse try self.initSection( |
| 379 | "__TEXT", |
| 380 | "__text", |
| 381 | .{ |
| 382 | .flags = macho.S_REGULAR | |
| 383 | macho.S_ATTR_PURE_INSTRUCTIONS | |
| 384 | macho.S_ATTR_SOME_INSTRUCTIONS, |
| 385 | }, |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | if (sect.isDebug()) { |
| 390 | // TODO debug attributes |
| 391 | if (mem.eql(u8, "__LD", segname) and mem.eql(u8, "__compact_unwind", sectname)) { |
| 392 | log.debug("TODO compact unwind section: type 0x{x}, name '{s},{s}'", .{ |
| 393 | sect.flags, segname, sectname, |
| 394 | }); |
| 395 | } |
| 396 | break :blk null; |
| 397 | } |
| 398 | |
| 399 | switch (sect.@"type"()) { |
| 400 | macho.S_4BYTE_LITERALS, |
| 401 | macho.S_8BYTE_LITERALS, |
| 402 | macho.S_16BYTE_LITERALS, |
| 403 | => { |
| 404 | break :blk self.getSectionByName("__TEXT", "__const") orelse try self.initSection( |
| 405 | "__TEXT", |
| 406 | "__const", |
| 407 | .{}, |
| 408 | ); |
| 409 | }, |
| 410 | macho.S_CSTRING_LITERALS => { |
| 411 | if (mem.startsWith(u8, sectname, "__objc")) { |
| 412 | break :blk self.getSectionByName(segname, sectname) orelse try self.initSection( |
| 413 | segname, |
| 414 | sectname, |
| 415 | .{}, |
| 416 | ); |
| 294 | 417 | } |
| 418 | break :blk self.getSectionByName("__TEXT", "__cstring") orelse try self.initSection( |
| 419 | "__TEXT", |
| 420 | "__cstring", |
| 421 | .{ .flags = macho.S_CSTRING_LITERALS }, |
| 422 | ); |
| 295 | 423 | }, |
| 296 | | .dylibs_first => { |
| 297 | | // First, look for a dylib in each search dir |
| 298 | | for (lib_dirs.items) |dir| { |
| 299 | | for (&[_][]const u8{ ".tbd", ".dylib" }) |ext| { |
| 300 | | if (try MachO.resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 301 | | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 302 | | continue :outer; |
| 303 | | } |
| 424 | macho.S_MOD_INIT_FUNC_POINTERS, |
| 425 | macho.S_MOD_TERM_FUNC_POINTERS, |
| 426 | => { |
| 427 | break :blk self.getSectionByName("__DATA_CONST", sectname) orelse try self.initSection( |
| 428 | "__DATA_CONST", |
| 429 | sectname, |
| 430 | .{ .flags = sect.flags }, |
| 431 | ); |
| 432 | }, |
| 433 | macho.S_LITERAL_POINTERS, |
| 434 | macho.S_ZEROFILL, |
| 435 | macho.S_THREAD_LOCAL_VARIABLES, |
| 436 | macho.S_THREAD_LOCAL_VARIABLE_POINTERS, |
| 437 | macho.S_THREAD_LOCAL_REGULAR, |
| 438 | macho.S_THREAD_LOCAL_ZEROFILL, |
| 439 | => { |
| 440 | break :blk self.getSectionByName(segname, sectname) orelse try self.initSection( |
| 441 | segname, |
| 442 | sectname, |
| 443 | .{ .flags = sect.flags }, |
| 444 | ); |
| 445 | }, |
| 446 | macho.S_COALESCED => { |
| 447 | break :blk self.getSectionByName(segname, sectname) orelse try self.initSection( |
| 448 | segname, |
| 449 | sectname, |
| 450 | .{}, |
| 451 | ); |
| 452 | }, |
| 453 | macho.S_REGULAR => { |
| 454 | if (mem.eql(u8, segname, "__TEXT")) { |
| 455 | if (mem.eql(u8, sectname, "__rodata") or |
| 456 | mem.eql(u8, sectname, "__typelink") or |
| 457 | mem.eql(u8, sectname, "__itablink") or |
| 458 | mem.eql(u8, sectname, "__gosymtab") or |
| 459 | mem.eql(u8, sectname, "__gopclntab")) |
| 460 | { |
| 461 | break :blk self.getSectionByName("__DATA_CONST", "__const") orelse try self.initSection( |
| 462 | "__DATA_CONST", |
| 463 | "__const", |
| 464 | .{}, |
| 465 | ); |
| 304 | 466 | } |
| 305 | | } else for (lib_dirs.items) |dir| { |
| 306 | | if (try MachO.resolveLib(arena, dir, lib_name, ".a")) |full_path| { |
| 307 | | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 308 | | } else { |
| 309 | | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 310 | | lib_not_found = true; |
| 467 | } |
| 468 | if (mem.eql(u8, segname, "__DATA")) { |
| 469 | if (mem.eql(u8, sectname, "__const") or |
| 470 | mem.eql(u8, sectname, "__cfstring") or |
| 471 | mem.eql(u8, sectname, "__objc_classlist") or |
| 472 | mem.eql(u8, sectname, "__objc_imageinfo")) |
| 473 | { |
| 474 | break :blk self.getSectionByName("__DATA_CONST", sectname) orelse |
| 475 | try self.initSection( |
| 476 | "__DATA_CONST", |
| 477 | sectname, |
| 478 | .{}, |
| 479 | ); |
| 480 | } else if (mem.eql(u8, sectname, "__data")) { |
| 481 | break :blk self.getSectionByName("__DATA", "__data") orelse |
| 482 | try self.initSection( |
| 483 | "__DATA", |
| 484 | "__data", |
| 485 | .{}, |
| 486 | ); |
| 311 | 487 | } |
| 312 | 488 | } |
| 489 | break :blk self.getSectionByName(segname, sectname) orelse try self.initSection( |
| 490 | segname, |
| 491 | sectname, |
| 492 | .{}, |
| 493 | ); |
| 313 | 494 | }, |
| 495 | else => break :blk null, |
| 314 | 496 | } |
| 315 | | } |
| 497 | }; |
| 498 | return res; |
| 499 | } |
| 316 | 500 | |
| 317 | | if (lib_not_found) { |
| 318 | | log.warn("Library search paths:", .{}); |
| 319 | | for (lib_dirs.items) |dir| { |
| 320 | | log.warn(" {s}", .{dir}); |
| 321 | | } |
| 501 | pub fn addAtomToSection(self: *Zld, atom_index: AtomIndex) void { |
| 502 | const atom = self.getAtomPtr(atom_index); |
| 503 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 504 | var section = self.sections.get(sym.n_sect - 1); |
| 505 | if (section.header.size > 0) { |
| 506 | const last_atom = self.getAtomPtr(section.last_atom_index); |
| 507 | last_atom.next_index = atom_index; |
| 508 | atom.prev_index = section.last_atom_index; |
| 509 | } else { |
| 510 | section.first_atom_index = atom_index; |
| 322 | 511 | } |
| 512 | section.last_atom_index = atom_index; |
| 513 | section.header.size += atom.size; |
| 514 | self.sections.set(sym.n_sect - 1, section); |
| 515 | } |
| 323 | 516 | |
| 324 | | try macho_file.resolveLibSystem(arena, comp, lib_dirs.items, &libs); |
| 517 | pub fn createEmptyAtom(self: *Zld, sym_index: u32, size: u64, alignment: u32) !AtomIndex { |
| 518 | const gpa = self.gpa; |
| 519 | const index = @intCast(AtomIndex, self.atoms.items.len); |
| 520 | const atom = try self.atoms.addOne(gpa); |
| 521 | atom.* = Atom.empty; |
| 522 | atom.sym_index = sym_index; |
| 523 | atom.size = size; |
| 524 | atom.alignment = alignment; |
| 325 | 525 | |
| 326 | | // frameworks |
| 327 | | var framework_dirs = std.ArrayList([]const u8).init(arena); |
| 328 | | for (macho_file.base.options.framework_dirs) |dir| { |
| 329 | | if (try MachO.resolveSearchDir(arena, dir, macho_file.base.options.sysroot)) |search_dir| { |
| 330 | | try framework_dirs.append(search_dir); |
| 331 | | } else { |
| 332 | | log.warn("directory not found for '-F{s}'", .{dir}); |
| 333 | | } |
| 334 | | } |
| 526 | log.debug("creating ATOM(%{d}) at index {d}", .{ sym_index, index }); |
| 335 | 527 | |
| 336 | | outer: for (macho_file.base.options.frameworks.keys()) |f_name| { |
| 337 | | for (framework_dirs.items) |dir| { |
| 338 | | for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| { |
| 339 | | if (try MachO.resolveFramework(arena, dir, f_name, ext)) |full_path| { |
| 340 | | const info = macho_file.base.options.frameworks.get(f_name).?; |
| 341 | | try libs.put(full_path, .{ |
| 342 | | .needed = info.needed, |
| 343 | | .weak = info.weak, |
| 344 | | }); |
| 345 | | continue :outer; |
| 346 | | } |
| 528 | return index; |
| 529 | } |
| 530 | |
| 531 | pub fn createGotAtom(self: *Zld) !AtomIndex { |
| 532 | const sym_index = try self.allocateSymbol(); |
| 533 | const atom_index = try self.createEmptyAtom(sym_index, @sizeOf(u64), 3); |
| 534 | const sym = self.getSymbolPtr(.{ .sym_index = sym_index }); |
| 535 | sym.n_type = macho.N_SECT; |
| 536 | |
| 537 | const sect_id = self.getSectionByName("__DATA_CONST", "__got") orelse |
| 538 | try self.initSection("__DATA_CONST", "__got", .{ |
| 539 | .flags = macho.S_NON_LAZY_SYMBOL_POINTERS, |
| 540 | }); |
| 541 | sym.n_sect = sect_id + 1; |
| 542 | |
| 543 | self.addAtomToSection(atom_index); |
| 544 | |
| 545 | return atom_index; |
| 546 | } |
| 547 | |
| 548 | fn writeGotPointer(self: *Zld, got_index: u32, writer: anytype) !void { |
| 549 | const target_addr = blk: { |
| 550 | const entry = self.got_entries.items[got_index]; |
| 551 | const sym = entry.getTargetSymbol(self); |
| 552 | break :blk sym.n_value; |
| 553 | }; |
| 554 | try writer.writeIntLittle(u64, target_addr); |
| 555 | } |
| 556 | |
| 557 | pub fn createTlvPtrAtom(self: *Zld) !AtomIndex { |
| 558 | const sym_index = try self.allocateSymbol(); |
| 559 | const atom_index = try self.createEmptyAtom(sym_index, @sizeOf(u64), 3); |
| 560 | const sym = self.getSymbolPtr(.{ .sym_index = sym_index }); |
| 561 | sym.n_type = macho.N_SECT; |
| 562 | |
| 563 | const sect_id = (try self.getOutputSection(.{ |
| 564 | .segname = makeStaticString("__DATA"), |
| 565 | .sectname = makeStaticString("__thread_ptrs"), |
| 566 | .flags = macho.S_THREAD_LOCAL_VARIABLE_POINTERS, |
| 567 | })).?; |
| 568 | sym.n_sect = sect_id + 1; |
| 569 | |
| 570 | self.addAtomToSection(atom_index); |
| 571 | |
| 572 | return atom_index; |
| 573 | } |
| 574 | |
| 575 | fn createDyldStubBinderGotAtom(self: *Zld) !void { |
| 576 | const sym_index = self.dyld_stub_binder_index orelse return; |
| 577 | const gpa = self.gpa; |
| 578 | const target = SymbolWithLoc{ .sym_index = sym_index }; |
| 579 | const atom_index = try self.createGotAtom(); |
| 580 | const got_index = @intCast(u32, self.got_entries.items.len); |
| 581 | try self.got_entries.append(gpa, .{ |
| 582 | .target = target, |
| 583 | .atom_index = atom_index, |
| 584 | }); |
| 585 | try self.got_table.putNoClobber(gpa, target, got_index); |
| 586 | } |
| 587 | |
| 588 | fn createDyldPrivateAtom(self: *Zld) !void { |
| 589 | if (self.dyld_stub_binder_index == null) return; |
| 590 | |
| 591 | const sym_index = try self.allocateSymbol(); |
| 592 | const atom_index = try self.createEmptyAtom(sym_index, @sizeOf(u64), 3); |
| 593 | const sym = self.getSymbolPtr(.{ .sym_index = sym_index }); |
| 594 | sym.n_type = macho.N_SECT; |
| 595 | |
| 596 | const sect_id = self.getSectionByName("__DATA", "__data") orelse try self.initSection("__DATA", "__data", .{}); |
| 597 | sym.n_sect = sect_id + 1; |
| 598 | |
| 599 | self.dyld_private_sym_index = sym_index; |
| 600 | |
| 601 | self.addAtomToSection(atom_index); |
| 602 | } |
| 603 | |
| 604 | fn createStubHelperPreambleAtom(self: *Zld) !void { |
| 605 | if (self.dyld_stub_binder_index == null) return; |
| 606 | |
| 607 | const cpu_arch = self.options.target.cpu.arch; |
| 608 | const size: u64 = switch (cpu_arch) { |
| 609 | .x86_64 => 15, |
| 610 | .aarch64 => 6 * @sizeOf(u32), |
| 611 | else => unreachable, |
| 612 | }; |
| 613 | const alignment: u32 = switch (cpu_arch) { |
| 614 | .x86_64 => 0, |
| 615 | .aarch64 => 2, |
| 616 | else => unreachable, |
| 617 | }; |
| 618 | const sym_index = try self.allocateSymbol(); |
| 619 | const atom_index = try self.createEmptyAtom(sym_index, size, alignment); |
| 620 | const sym = self.getSymbolPtr(.{ .sym_index = sym_index }); |
| 621 | sym.n_type = macho.N_SECT; |
| 622 | |
| 623 | const sect_id = self.getSectionByName("__TEXT", "__stub_helper") orelse |
| 624 | try self.initSection("__TEXT", "__stub_helper", .{ |
| 625 | .flags = macho.S_REGULAR | |
| 626 | macho.S_ATTR_PURE_INSTRUCTIONS | |
| 627 | macho.S_ATTR_SOME_INSTRUCTIONS, |
| 628 | }); |
| 629 | sym.n_sect = sect_id + 1; |
| 630 | |
| 631 | self.stub_helper_preamble_sym_index = sym_index; |
| 632 | |
| 633 | self.addAtomToSection(atom_index); |
| 634 | } |
| 635 | |
| 636 | fn writeStubHelperPreambleCode(self: *Zld, writer: anytype) !void { |
| 637 | const cpu_arch = self.options.target.cpu.arch; |
| 638 | const source_addr = blk: { |
| 639 | const sym = self.getSymbol(.{ .sym_index = self.stub_helper_preamble_sym_index.? }); |
| 640 | break :blk sym.n_value; |
| 641 | }; |
| 642 | const dyld_private_addr = blk: { |
| 643 | const sym = self.getSymbol(.{ .sym_index = self.dyld_private_sym_index.? }); |
| 644 | break :blk sym.n_value; |
| 645 | }; |
| 646 | const dyld_stub_binder_got_addr = blk: { |
| 647 | const index = self.got_table.get(.{ .sym_index = self.dyld_stub_binder_index.? }).?; |
| 648 | const entry = self.got_entries.items[index]; |
| 649 | break :blk entry.getAtomSymbol(self).n_value; |
| 650 | }; |
| 651 | switch (cpu_arch) { |
| 652 | .x86_64 => { |
| 653 | try writer.writeAll(&.{ 0x4c, 0x8d, 0x1d }); |
| 654 | { |
| 655 | const disp = try Atom.calcPcRelativeDisplacementX86(source_addr + 3, dyld_private_addr, 0); |
| 656 | try writer.writeIntLittle(i32, disp); |
| 347 | 657 | } |
| 348 | | } else { |
| 349 | | log.warn("framework not found for '-framework {s}'", .{f_name}); |
| 350 | | framework_not_found = true; |
| 351 | | } |
| 658 | try writer.writeAll(&.{ 0x41, 0x53, 0xff, 0x25 }); |
| 659 | { |
| 660 | const disp = try Atom.calcPcRelativeDisplacementX86(source_addr + 11, dyld_stub_binder_got_addr, 0); |
| 661 | try writer.writeIntLittle(i32, disp); |
| 662 | } |
| 663 | }, |
| 664 | .aarch64 => { |
| 665 | { |
| 666 | const pages = Atom.calcNumberOfPages(source_addr, dyld_private_addr); |
| 667 | try writer.writeIntLittle(u32, aarch64.Instruction.adrp(.x17, pages).toU32()); |
| 668 | } |
| 669 | { |
| 670 | const off = try Atom.calcPageOffset(dyld_private_addr, .arithmetic); |
| 671 | try writer.writeIntLittle(u32, aarch64.Instruction.add(.x17, .x17, off, false).toU32()); |
| 672 | } |
| 673 | try writer.writeIntLittle(u32, aarch64.Instruction.stp( |
| 674 | .x16, |
| 675 | .x17, |
| 676 | aarch64.Register.sp, |
| 677 | aarch64.Instruction.LoadStorePairOffset.pre_index(-16), |
| 678 | ).toU32()); |
| 679 | { |
| 680 | const pages = Atom.calcNumberOfPages(source_addr + 12, dyld_stub_binder_got_addr); |
| 681 | try writer.writeIntLittle(u32, aarch64.Instruction.adrp(.x16, pages).toU32()); |
| 682 | } |
| 683 | { |
| 684 | const off = try Atom.calcPageOffset(dyld_stub_binder_got_addr, .load_store_64); |
| 685 | try writer.writeIntLittle(u32, aarch64.Instruction.ldr( |
| 686 | .x16, |
| 687 | .x16, |
| 688 | aarch64.Instruction.LoadStoreOffset.imm(off), |
| 689 | ).toU32()); |
| 690 | } |
| 691 | try writer.writeIntLittle(u32, aarch64.Instruction.br(.x16).toU32()); |
| 692 | }, |
| 693 | else => unreachable, |
| 352 | 694 | } |
| 695 | } |
| 353 | 696 | |
| 354 | | if (framework_not_found) { |
| 355 | | log.warn("Framework search paths:", .{}); |
| 356 | | for (framework_dirs.items) |dir| { |
| 357 | | log.warn(" {s}", .{dir}); |
| 358 | | } |
| 697 | pub fn createStubHelperAtom(self: *Zld) !AtomIndex { |
| 698 | const cpu_arch = self.options.target.cpu.arch; |
| 699 | const stub_size: u4 = switch (cpu_arch) { |
| 700 | .x86_64 => 10, |
| 701 | .aarch64 => 3 * @sizeOf(u32), |
| 702 | else => unreachable, |
| 703 | }; |
| 704 | const alignment: u2 = switch (cpu_arch) { |
| 705 | .x86_64 => 0, |
| 706 | .aarch64 => 2, |
| 707 | else => unreachable, |
| 708 | }; |
| 709 | |
| 710 | const sym_index = try self.allocateSymbol(); |
| 711 | const atom_index = try self.createEmptyAtom(sym_index, stub_size, alignment); |
| 712 | const sym = self.getSymbolPtr(.{ .sym_index = sym_index }); |
| 713 | sym.n_sect = macho.N_SECT; |
| 714 | |
| 715 | const sect_id = self.getSectionByName("__TEXT", "__stub_helper").?; |
| 716 | sym.n_sect = sect_id + 1; |
| 717 | |
| 718 | self.addAtomToSection(atom_index); |
| 719 | |
| 720 | return atom_index; |
| 721 | } |
| 722 | |
| 723 | fn writeStubHelperCode(self: *Zld, atom_index: AtomIndex, writer: anytype) !void { |
| 724 | const cpu_arch = self.options.target.cpu.arch; |
| 725 | const source_addr = blk: { |
| 726 | const atom = self.getAtom(atom_index); |
| 727 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 728 | break :blk sym.n_value; |
| 729 | }; |
| 730 | const target_addr = blk: { |
| 731 | const sym = self.getSymbol(.{ .sym_index = self.stub_helper_preamble_sym_index.? }); |
| 732 | break :blk sym.n_value; |
| 733 | }; |
| 734 | switch (cpu_arch) { |
| 735 | .x86_64 => { |
| 736 | try writer.writeAll(&.{ 0x68, 0x0, 0x0, 0x0, 0x0, 0xe9 }); |
| 737 | { |
| 738 | const disp = try Atom.calcPcRelativeDisplacementX86(source_addr + 6, target_addr, 0); |
| 739 | try writer.writeIntLittle(i32, disp); |
| 740 | } |
| 741 | }, |
| 742 | .aarch64 => { |
| 743 | const stub_size: u4 = 3 * @sizeOf(u32); |
| 744 | const literal = blk: { |
| 745 | const div_res = try math.divExact(u64, stub_size - @sizeOf(u32), 4); |
| 746 | break :blk math.cast(u18, div_res) orelse return error.Overflow; |
| 747 | }; |
| 748 | try writer.writeIntLittle(u32, aarch64.Instruction.ldrLiteral( |
| 749 | .w16, |
| 750 | literal, |
| 751 | ).toU32()); |
| 752 | { |
| 753 | const disp = try Atom.calcPcRelativeDisplacementArm64(source_addr + 4, target_addr); |
| 754 | try writer.writeIntLittle(u32, aarch64.Instruction.b(disp).toU32()); |
| 755 | } |
| 756 | try writer.writeAll(&.{ 0x0, 0x0, 0x0, 0x0 }); |
| 757 | }, |
| 758 | else => unreachable, |
| 359 | 759 | } |
| 760 | } |
| 360 | 761 | |
| 361 | | if (macho_file.base.options.verbose_link) { |
| 362 | | var argv = std.ArrayList([]const u8).init(arena); |
| 762 | pub fn createLazyPointerAtom(self: *Zld) !AtomIndex { |
| 763 | const sym_index = try self.allocateSymbol(); |
| 764 | const atom_index = try self.createEmptyAtom(sym_index, @sizeOf(u64), 3); |
| 765 | const sym = self.getSymbolPtr(.{ .sym_index = sym_index }); |
| 766 | sym.n_type = macho.N_SECT; |
| 363 | 767 | |
| 364 | | try argv.append("zig"); |
| 365 | | try argv.append("ld"); |
| 768 | const sect_id = self.getSectionByName("__DATA", "__la_symbol_ptr") orelse |
| 769 | try self.initSection("__DATA", "__la_symbol_ptr", .{ |
| 770 | .flags = macho.S_LAZY_SYMBOL_POINTERS, |
| 771 | }); |
| 772 | sym.n_sect = sect_id + 1; |
| 366 | 773 | |
| 367 | | if (is_exe_or_dyn_lib) { |
| 368 | | try argv.append("-dynamic"); |
| 369 | | } |
| 774 | self.addAtomToSection(atom_index); |
| 370 | 775 | |
| 371 | | if (is_dyn_lib) { |
| 372 | | try argv.append("-dylib"); |
| 776 | return atom_index; |
| 777 | } |
| 373 | 778 | |
| 374 | | if (macho_file.base.options.install_name) |install_name| { |
| 375 | | try argv.append("-install_name"); |
| 376 | | try argv.append(install_name); |
| 779 | fn writeLazyPointer(self: *Zld, stub_helper_index: u32, writer: anytype) !void { |
| 780 | const target_addr = blk: { |
| 781 | const sect_id = self.getSectionByName("__TEXT", "__stub_helper").?; |
| 782 | var atom_index = self.sections.items(.first_atom_index)[sect_id]; |
| 783 | var count: u32 = 0; |
| 784 | while (count < stub_helper_index + 1) : (count += 1) { |
| 785 | const atom = self.getAtom(atom_index); |
| 786 | if (atom.next_index) |next_index| { |
| 787 | atom_index = next_index; |
| 377 | 788 | } |
| 378 | 789 | } |
| 790 | const atom = self.getAtom(atom_index); |
| 791 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 792 | break :blk sym.n_value; |
| 793 | }; |
| 794 | try writer.writeIntLittle(u64, target_addr); |
| 795 | } |
| 379 | 796 | |
| 380 | | if (macho_file.base.options.sysroot) |syslibroot| { |
| 381 | | try argv.append("-syslibroot"); |
| 382 | | try argv.append(syslibroot); |
| 383 | | } |
| 797 | pub fn createStubAtom(self: *Zld) !AtomIndex { |
| 798 | const cpu_arch = self.options.target.cpu.arch; |
| 799 | const alignment: u2 = switch (cpu_arch) { |
| 800 | .x86_64 => 0, |
| 801 | .aarch64 => 2, |
| 802 | else => unreachable, // unhandled architecture type |
| 803 | }; |
| 804 | const stub_size: u4 = switch (cpu_arch) { |
| 805 | .x86_64 => 6, |
| 806 | .aarch64 => 3 * @sizeOf(u32), |
| 807 | else => unreachable, // unhandled architecture type |
| 808 | }; |
| 809 | const sym_index = try self.allocateSymbol(); |
| 810 | const atom_index = try self.createEmptyAtom(sym_index, stub_size, alignment); |
| 811 | const sym = self.getSymbolPtr(.{ .sym_index = sym_index }); |
| 812 | sym.n_type = macho.N_SECT; |
| 813 | |
| 814 | const sect_id = self.getSectionByName("__TEXT", "__stubs") orelse |
| 815 | try self.initSection("__TEXT", "__stubs", .{ |
| 816 | .flags = macho.S_SYMBOL_STUBS | |
| 817 | macho.S_ATTR_PURE_INSTRUCTIONS | |
| 818 | macho.S_ATTR_SOME_INSTRUCTIONS, |
| 819 | .reserved2 = stub_size, |
| 820 | }); |
| 821 | sym.n_sect = sect_id + 1; |
| 384 | 822 | |
| 385 | | for (macho_file.base.options.rpath_list) |rpath| { |
| 386 | | try argv.append("-rpath"); |
| 387 | | try argv.append(rpath); |
| 388 | | } |
| 823 | self.addAtomToSection(atom_index); |
| 389 | 824 | |
| 390 | | if (macho_file.base.options.pagezero_size) |pagezero_size| { |
| 391 | | try argv.append("-pagezero_size"); |
| 392 | | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{pagezero_size})); |
| 825 | return atom_index; |
| 826 | } |
| 827 | |
| 828 | fn writeStubCode(self: *Zld, atom_index: AtomIndex, stub_index: u32, writer: anytype) !void { |
| 829 | const cpu_arch = self.options.target.cpu.arch; |
| 830 | const source_addr = blk: { |
| 831 | const atom = self.getAtom(atom_index); |
| 832 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 833 | break :blk sym.n_value; |
| 834 | }; |
| 835 | const target_addr = blk: { |
| 836 | // TODO: cache this at stub atom creation; they always go in pairs anyhow |
| 837 | const la_sect_id = self.getSectionByName("__DATA", "__la_symbol_ptr").?; |
| 838 | var la_atom_index = self.sections.items(.first_atom_index)[la_sect_id]; |
| 839 | var count: u32 = 0; |
| 840 | while (count < stub_index) : (count += 1) { |
| 841 | const la_atom = self.getAtom(la_atom_index); |
| 842 | la_atom_index = la_atom.next_index.?; |
| 393 | 843 | } |
| 844 | const atom = self.getAtom(la_atom_index); |
| 845 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 846 | break :blk sym.n_value; |
| 847 | }; |
| 848 | switch (cpu_arch) { |
| 849 | .x86_64 => { |
| 850 | try writer.writeAll(&.{ 0xff, 0x25 }); |
| 851 | { |
| 852 | const disp = try Atom.calcPcRelativeDisplacementX86(source_addr + 2, target_addr, 0); |
| 853 | try writer.writeIntLittle(i32, disp); |
| 854 | } |
| 855 | }, |
| 856 | .aarch64 => { |
| 857 | { |
| 858 | const pages = Atom.calcNumberOfPages(source_addr, target_addr); |
| 859 | try writer.writeIntLittle(u32, aarch64.Instruction.adrp(.x16, pages).toU32()); |
| 860 | } |
| 861 | { |
| 862 | const off = try Atom.calcPageOffset(target_addr, .load_store_64); |
| 863 | try writer.writeIntLittle(u32, aarch64.Instruction.ldr( |
| 864 | .x16, |
| 865 | .x16, |
| 866 | aarch64.Instruction.LoadStoreOffset.imm(off), |
| 867 | ).toU32()); |
| 868 | } |
| 869 | try writer.writeIntLittle(u32, aarch64.Instruction.br(.x16).toU32()); |
| 870 | }, |
| 871 | else => unreachable, |
| 872 | } |
| 873 | } |
| 394 | 874 | |
| 395 | | if (macho_file.base.options.search_strategy) |strat| switch (strat) { |
| 396 | | .paths_first => try argv.append("-search_paths_first"), |
| 397 | | .dylibs_first => try argv.append("-search_dylibs_first"), |
| 875 | fn createTentativeDefAtoms(self: *Zld) !void { |
| 876 | const gpa = self.gpa; |
| 877 | |
| 878 | for (self.globals.items) |global| { |
| 879 | const sym = self.getSymbolPtr(global); |
| 880 | if (!sym.tentative()) continue; |
| 881 | if (sym.n_desc == N_DEAD) continue; |
| 882 | |
| 883 | log.debug("creating tentative definition for ATOM(%{d}, '{s}') in object({?})", .{ |
| 884 | global.sym_index, self.getSymbolName(global), global.file, |
| 885 | }); |
| 886 | |
| 887 | // Convert any tentative definition into a regular symbol and allocate |
| 888 | // text blocks for each tentative definition. |
| 889 | const size = sym.n_value; |
| 890 | const alignment = (sym.n_desc >> 8) & 0x0f; |
| 891 | const n_sect = (try self.getOutputSection(.{ |
| 892 | .segname = makeStaticString("__DATA"), |
| 893 | .sectname = makeStaticString("__bss"), |
| 894 | .flags = macho.S_ZEROFILL, |
| 895 | })).? + 1; |
| 896 | |
| 897 | sym.* = .{ |
| 898 | .n_strx = sym.n_strx, |
| 899 | .n_type = macho.N_SECT | macho.N_EXT, |
| 900 | .n_sect = n_sect, |
| 901 | .n_desc = 0, |
| 902 | .n_value = 0, |
| 398 | 903 | }; |
| 399 | 904 | |
| 400 | | if (macho_file.base.options.headerpad_size) |headerpad_size| { |
| 401 | | try argv.append("-headerpad_size"); |
| 402 | | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{headerpad_size})); |
| 403 | | } |
| 905 | const atom_index = try self.createEmptyAtom(global.sym_index, size, alignment); |
| 906 | const atom = self.getAtomPtr(atom_index); |
| 907 | atom.file = global.file; |
| 404 | 908 | |
| 405 | | if (macho_file.base.options.headerpad_max_install_names) { |
| 406 | | try argv.append("-headerpad_max_install_names"); |
| 407 | | } |
| 909 | self.addAtomToSection(atom_index); |
| 408 | 910 | |
| 409 | | if (gc_sections) { |
| 410 | | try argv.append("-dead_strip"); |
| 411 | | } |
| 911 | assert(global.getFile() != null); |
| 912 | const object = &self.objects.items[global.getFile().?]; |
| 913 | try object.atoms.append(gpa, atom_index); |
| 914 | object.atom_by_index_table[global.sym_index] = atom_index; |
| 915 | } |
| 916 | } |
| 412 | 917 | |
| 413 | | if (macho_file.base.options.dead_strip_dylibs) { |
| 414 | | try argv.append("-dead_strip_dylibs"); |
| 415 | | } |
| 918 | fn resolveSymbolsInObject(self: *Zld, object_id: u16, resolver: *SymbolResolver) !void { |
| 919 | const object = &self.objects.items[object_id]; |
| 920 | const in_symtab = object.in_symtab orelse return; |
| 416 | 921 | |
| 417 | | if (macho_file.base.options.entry) |entry| { |
| 418 | | try argv.append("-e"); |
| 419 | | try argv.append(entry); |
| 420 | | } |
| 922 | log.debug("resolving symbols in '{s}'", .{object.name}); |
| 421 | 923 | |
| 422 | | for (macho_file.base.options.objects) |obj| { |
| 423 | | try argv.append(obj.path); |
| 424 | | } |
| 924 | var sym_index: u32 = 0; |
| 925 | while (sym_index < in_symtab.len) : (sym_index += 1) { |
| 926 | const sym = &object.symtab[sym_index]; |
| 927 | const sym_name = object.getSymbolName(sym_index); |
| 425 | 928 | |
| 426 | | for (comp.c_object_table.keys()) |key| { |
| 427 | | try argv.append(key.status.success.object_path); |
| 929 | if (sym.stab()) { |
| 930 | log.err("unhandled symbol type: stab", .{}); |
| 931 | log.err(" symbol '{s}'", .{sym_name}); |
| 932 | log.err(" first definition in '{s}'", .{object.name}); |
| 933 | return error.UnhandledSymbolType; |
| 428 | 934 | } |
| 429 | 935 | |
| 430 | | if (module_obj_path) |p| { |
| 431 | | try argv.append(p); |
| 936 | if (sym.indr()) { |
| 937 | log.err("unhandled symbol type: indirect", .{}); |
| 938 | log.err(" symbol '{s}'", .{sym_name}); |
| 939 | log.err(" first definition in '{s}'", .{object.name}); |
| 940 | return error.UnhandledSymbolType; |
| 432 | 941 | } |
| 433 | 942 | |
| 434 | | if (comp.compiler_rt_lib) |lib| { |
| 435 | | try argv.append(lib.full_object_path); |
| 943 | if (sym.abs()) { |
| 944 | log.err("unhandled symbol type: absolute", .{}); |
| 945 | log.err(" symbol '{s}'", .{sym_name}); |
| 946 | log.err(" first definition in '{s}'", .{object.name}); |
| 947 | return error.UnhandledSymbolType; |
| 436 | 948 | } |
| 437 | 949 | |
| 438 | | if (macho_file.base.options.link_libcpp) { |
| 439 | | try argv.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 440 | | try argv.append(comp.libcxx_static_lib.?.full_object_path); |
| 950 | if (sym.sect() and !sym.ext()) { |
| 951 | log.debug("symbol '{s}' local to object {s}; skipping...", .{ |
| 952 | sym_name, |
| 953 | object.name, |
| 954 | }); |
| 955 | continue; |
| 441 | 956 | } |
| 442 | 957 | |
| 443 | | try argv.append("-o"); |
| 444 | | try argv.append(full_out_path); |
| 445 | | |
| 446 | | try argv.append("-lSystem"); |
| 447 | | try argv.append("-lc"); |
| 958 | const sym_loc = SymbolWithLoc{ .sym_index = sym_index, .file = object_id }; |
| 448 | 959 | |
| 449 | | for (macho_file.base.options.system_libs.keys()) |l_name| { |
| 450 | | const info = macho_file.base.options.system_libs.get(l_name).?; |
| 451 | | const arg = if (info.needed) |
| 452 | | try std.fmt.allocPrint(arena, "-needed-l{s}", .{l_name}) |
| 453 | | else if (info.weak) |
| 454 | | try std.fmt.allocPrint(arena, "-weak-l{s}", .{l_name}) |
| 455 | | else |
| 456 | | try std.fmt.allocPrint(arena, "-l{s}", .{l_name}); |
| 457 | | try argv.append(arg); |
| 960 | const global_index = resolver.table.get(sym_name) orelse { |
| 961 | const gpa = self.gpa; |
| 962 | const name = try resolver.arena.dupe(u8, sym_name); |
| 963 | const global_index = @intCast(u32, self.globals.items.len); |
| 964 | try self.globals.append(gpa, sym_loc); |
| 965 | try resolver.table.putNoClobber(name, global_index); |
| 966 | if (sym.undf() and !sym.tentative()) { |
| 967 | try resolver.unresolved.putNoClobber(global_index, {}); |
| 968 | } |
| 969 | continue; |
| 970 | }; |
| 971 | const global = &self.globals.items[global_index]; |
| 972 | const global_sym = self.getSymbol(global.*); |
| 973 | |
| 974 | // Cases to consider: sym vs global_sym |
| 975 | // 1. strong(sym) and strong(global_sym) => error |
| 976 | // 2. strong(sym) and weak(global_sym) => sym |
| 977 | // 3. strong(sym) and tentative(global_sym) => sym |
| 978 | // 4. strong(sym) and undf(global_sym) => sym |
| 979 | // 5. weak(sym) and strong(global_sym) => global_sym |
| 980 | // 6. weak(sym) and tentative(global_sym) => sym |
| 981 | // 7. weak(sym) and undf(global_sym) => sym |
| 982 | // 8. tentative(sym) and strong(global_sym) => global_sym |
| 983 | // 9. tentative(sym) and weak(global_sym) => global_sym |
| 984 | // 10. tentative(sym) and tentative(global_sym) => pick larger |
| 985 | // 11. tentative(sym) and undf(global_sym) => sym |
| 986 | // 12. undf(sym) and * => global_sym |
| 987 | // |
| 988 | // Reduces to: |
| 989 | // 1. strong(sym) and strong(global_sym) => error |
| 990 | // 2. * and strong(global_sym) => global_sym |
| 991 | // 3. weak(sym) and weak(global_sym) => global_sym |
| 992 | // 4. tentative(sym) and tentative(global_sym) => pick larger |
| 993 | // 5. undf(sym) and * => global_sym |
| 994 | // 6. else => sym |
| 995 | |
| 996 | const sym_is_strong = sym.sect() and !(sym.weakDef() or sym.pext()); |
| 997 | const global_is_strong = global_sym.sect() and !(global_sym.weakDef() or global_sym.pext()); |
| 998 | const sym_is_weak = sym.sect() and (sym.weakDef() or sym.pext()); |
| 999 | const global_is_weak = global_sym.sect() and (global_sym.weakDef() or global_sym.pext()); |
| 1000 | |
| 1001 | if (sym_is_strong and global_is_strong) { |
| 1002 | log.err("symbol '{s}' defined multiple times", .{sym_name}); |
| 1003 | if (global.getFile()) |file| { |
| 1004 | log.err(" first definition in '{s}'", .{self.objects.items[file].name}); |
| 1005 | } |
| 1006 | log.err(" next definition in '{s}'", .{self.objects.items[object_id].name}); |
| 1007 | return error.MultipleSymbolDefinitions; |
| 458 | 1008 | } |
| 459 | 1009 | |
| 460 | | for (macho_file.base.options.lib_dirs) |lib_dir| { |
| 461 | | try argv.append(try std.fmt.allocPrint(arena, "-L{s}", .{lib_dir})); |
| 462 | | } |
| 1010 | const update_global = blk: { |
| 1011 | if (global_is_strong) break :blk false; |
| 1012 | if (sym_is_weak and global_is_weak) break :blk false; |
| 1013 | if (sym.tentative() and global_sym.tentative()) { |
| 1014 | if (global_sym.n_value >= sym.n_value) break :blk false; |
| 1015 | } |
| 1016 | if (sym.undf() and !sym.tentative()) break :blk false; |
| 1017 | break :blk true; |
| 1018 | }; |
| 463 | 1019 | |
| 464 | | for (macho_file.base.options.frameworks.keys()) |framework| { |
| 465 | | const info = macho_file.base.options.frameworks.get(framework).?; |
| 466 | | const arg = if (info.needed) |
| 467 | | try std.fmt.allocPrint(arena, "-needed_framework {s}", .{framework}) |
| 468 | | else if (info.weak) |
| 469 | | try std.fmt.allocPrint(arena, "-weak_framework {s}", .{framework}) |
| 470 | | else |
| 471 | | try std.fmt.allocPrint(arena, "-framework {s}", .{framework}); |
| 472 | | try argv.append(arg); |
| 1020 | if (update_global) { |
| 1021 | const global_object = &self.objects.items[global.getFile().?]; |
| 1022 | global_object.globals_lookup[global.sym_index] = global_index; |
| 1023 | _ = resolver.unresolved.swapRemove(resolver.table.get(sym_name).?); |
| 1024 | global.* = sym_loc; |
| 1025 | } else { |
| 1026 | object.globals_lookup[sym_index] = global_index; |
| 473 | 1027 | } |
| 1028 | } |
| 1029 | } |
| 474 | 1030 | |
| 475 | | for (macho_file.base.options.framework_dirs) |framework_dir| { |
| 476 | | try argv.append(try std.fmt.allocPrint(arena, "-F{s}", .{framework_dir})); |
| 1031 | fn resolveSymbolsInArchives(self: *Zld, resolver: *SymbolResolver) !void { |
| 1032 | if (self.archives.items.len == 0) return; |
| 1033 | |
| 1034 | const gpa = self.gpa; |
| 1035 | const cpu_arch = self.options.target.cpu.arch; |
| 1036 | var next_sym: usize = 0; |
| 1037 | loop: while (next_sym < resolver.unresolved.count()) { |
| 1038 | const global = self.globals.items[resolver.unresolved.keys()[next_sym]]; |
| 1039 | const sym_name = self.getSymbolName(global); |
| 1040 | |
| 1041 | for (self.archives.items) |archive| { |
| 1042 | // Check if the entry exists in a static archive. |
| 1043 | const offsets = archive.toc.get(sym_name) orelse { |
| 1044 | // No hit. |
| 1045 | continue; |
| 1046 | }; |
| 1047 | assert(offsets.items.len > 0); |
| 1048 | |
| 1049 | const object_id = @intCast(u16, self.objects.items.len); |
| 1050 | const object = try archive.parseObject(gpa, cpu_arch, offsets.items[0]); |
| 1051 | try self.objects.append(gpa, object); |
| 1052 | try self.resolveSymbolsInObject(object_id, resolver); |
| 1053 | |
| 1054 | continue :loop; |
| 477 | 1055 | } |
| 478 | 1056 | |
| 479 | | if (is_dyn_lib and (macho_file.base.options.allow_shlib_undefined orelse false)) { |
| 480 | | try argv.append("-undefined"); |
| 481 | | try argv.append("dynamic_lookup"); |
| 482 | | } |
| 1057 | next_sym += 1; |
| 1058 | } |
| 1059 | } |
| 483 | 1060 | |
| 484 | | for (must_link_archives.keys()) |lib| { |
| 485 | | try argv.append(try std.fmt.allocPrint(arena, "-force_load {s}", .{lib})); |
| 486 | | } |
| 1061 | fn resolveSymbolsInDylibs(self: *Zld, resolver: *SymbolResolver) !void { |
| 1062 | if (self.dylibs.items.len == 0) return; |
| 487 | 1063 | |
| 488 | | Compilation.dump_argv(argv.items); |
| 489 | | } |
| 1064 | var next_sym: usize = 0; |
| 1065 | loop: while (next_sym < resolver.unresolved.count()) { |
| 1066 | const global_index = resolver.unresolved.keys()[next_sym]; |
| 1067 | const global = self.globals.items[global_index]; |
| 1068 | const sym = self.getSymbolPtr(global); |
| 1069 | const sym_name = self.getSymbolName(global); |
| 490 | 1070 | |
| 491 | | var dependent_libs = std.fifo.LinearFifo(struct { |
| 492 | | id: Dylib.Id, |
| 493 | | parent: u16, |
| 494 | | }, .Dynamic).init(arena); |
| 1071 | for (self.dylibs.items) |dylib, id| { |
| 1072 | if (!dylib.symbols.contains(sym_name)) continue; |
| 495 | 1073 | |
| 496 | | try macho_file.parseInputFiles(positionals.items, macho_file.base.options.sysroot, &dependent_libs); |
| 497 | | try macho_file.parseAndForceLoadStaticArchives(must_link_archives.keys()); |
| 498 | | try macho_file.parseLibs(libs.keys(), libs.values(), macho_file.base.options.sysroot, &dependent_libs); |
| 499 | | try macho_file.parseDependentLibs(macho_file.base.options.sysroot, &dependent_libs); |
| 1074 | const dylib_id = @intCast(u16, id); |
| 1075 | if (!self.referenced_dylibs.contains(dylib_id)) { |
| 1076 | try self.referenced_dylibs.putNoClobber(self.gpa, dylib_id, {}); |
| 1077 | } |
| 500 | 1078 | |
| 501 | | for (macho_file.objects.items) |_, object_id| { |
| 502 | | try macho_file.resolveSymbolsInObject(@intCast(u16, object_id)); |
| 503 | | } |
| 1079 | const ordinal = self.referenced_dylibs.getIndex(dylib_id) orelse unreachable; |
| 1080 | sym.n_type |= macho.N_EXT; |
| 1081 | sym.n_desc = @intCast(u16, ordinal + 1) * macho.N_SYMBOL_RESOLVER; |
| 504 | 1082 | |
| 505 | | try macho_file.resolveSymbolsInArchives(); |
| 506 | | try macho_file.resolveDyldStubBinder(); |
| 507 | | try macho_file.resolveSymbolsInDylibs(); |
| 508 | | try macho_file.createMhExecuteHeaderSymbol(); |
| 509 | | try macho_file.createDsoHandleSymbol(); |
| 510 | | try macho_file.resolveSymbolsAtLoading(); |
| 1083 | if (dylib.weak) { |
| 1084 | sym.n_desc |= macho.N_WEAK_REF; |
| 1085 | } |
| 511 | 1086 | |
| 512 | | if (macho_file.unresolved.count() > 0) { |
| 513 | | return error.UndefinedSymbolReference; |
| 514 | | } |
| 515 | | if (lib_not_found) { |
| 516 | | return error.LibraryNotFound; |
| 517 | | } |
| 518 | | if (framework_not_found) { |
| 519 | | return error.FrameworkNotFound; |
| 520 | | } |
| 1087 | assert(resolver.unresolved.swapRemove(global_index)); |
| 1088 | continue :loop; |
| 1089 | } |
| 521 | 1090 | |
| 522 | | for (macho_file.objects.items) |*object| { |
| 523 | | try object.scanInputSections(macho_file); |
| 1091 | next_sym += 1; |
| 524 | 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | fn resolveSymbolsAtLoading(self: *Zld, resolver: *SymbolResolver) !void { |
| 1096 | const is_lib = self.options.output_mode == .Lib; |
| 1097 | const is_dyn_lib = self.options.link_mode == .Dynamic and is_lib; |
| 1098 | const allow_undef = is_dyn_lib and (self.options.allow_shlib_undefined orelse false); |
| 1099 | |
| 1100 | var next_sym: usize = 0; |
| 1101 | while (next_sym < resolver.unresolved.count()) { |
| 1102 | const global_index = resolver.unresolved.keys()[next_sym]; |
| 1103 | const global = self.globals.items[global_index]; |
| 1104 | const sym = self.getSymbolPtr(global); |
| 1105 | const sym_name = self.getSymbolName(global); |
| 1106 | |
| 1107 | if (sym.discarded()) { |
| 1108 | sym.* = .{ |
| 1109 | .n_strx = 0, |
| 1110 | .n_type = macho.N_UNDF, |
| 1111 | .n_sect = 0, |
| 1112 | .n_desc = 0, |
| 1113 | .n_value = 0, |
| 1114 | }; |
| 1115 | _ = resolver.unresolved.swapRemove(global_index); |
| 1116 | continue; |
| 1117 | } else if (allow_undef) { |
| 1118 | const n_desc = @bitCast( |
| 1119 | u16, |
| 1120 | macho.BIND_SPECIAL_DYLIB_FLAT_LOOKUP * @intCast(i16, macho.N_SYMBOL_RESOLVER), |
| 1121 | ); |
| 1122 | sym.n_type = macho.N_EXT; |
| 1123 | sym.n_desc = n_desc; |
| 1124 | _ = resolver.unresolved.swapRemove(global_index); |
| 1125 | continue; |
| 1126 | } |
| 525 | 1127 | |
| 526 | | try macho_file.createDyldPrivateAtom(); |
| 527 | | try macho_file.createTentativeDefAtoms(); |
| 528 | | try macho_file.createStubHelperPreambleAtom(); |
| 1128 | log.err("undefined reference to symbol '{s}'", .{sym_name}); |
| 1129 | if (global.getFile()) |file| { |
| 1130 | log.err(" first referenced in '{s}'", .{self.objects.items[file].name}); |
| 1131 | } |
| 529 | 1132 | |
| 530 | | for (macho_file.objects.items) |*object, object_id| { |
| 531 | | try object.splitIntoAtoms(macho_file, @intCast(u32, object_id)); |
| 1133 | next_sym += 1; |
| 532 | 1134 | } |
| 1135 | } |
| 533 | 1136 | |
| 534 | | if (gc_sections) { |
| 535 | | try dead_strip.gcAtoms(macho_file); |
| 1137 | fn createMhExecuteHeaderSymbol(self: *Zld, resolver: *SymbolResolver) !void { |
| 1138 | if (self.options.output_mode != .Exe) return; |
| 1139 | if (resolver.table.get("__mh_execute_header")) |global_index| { |
| 1140 | const global = self.globals.items[global_index]; |
| 1141 | const sym = self.getSymbol(global); |
| 1142 | self.mh_execute_header_index = global_index; |
| 1143 | if (!sym.undf() and !(sym.pext() or sym.weakDef())) return; |
| 536 | 1144 | } |
| 537 | 1145 | |
| 538 | | try allocateSegments(macho_file); |
| 539 | | try allocateSymbols(macho_file); |
| 1146 | const gpa = self.gpa; |
| 1147 | const sym_index = try self.allocateSymbol(); |
| 1148 | const sym_loc = SymbolWithLoc{ .sym_index = sym_index }; |
| 1149 | const sym = self.getSymbolPtr(sym_loc); |
| 1150 | sym.n_strx = try self.strtab.insert(gpa, "__mh_execute_header"); |
| 1151 | sym.n_type = macho.N_SECT | macho.N_EXT; |
| 1152 | sym.n_desc = macho.REFERENCED_DYNAMICALLY; |
| 1153 | |
| 1154 | if (resolver.table.get("__mh_execute_header")) |global_index| { |
| 1155 | const global = &self.globals.items[global_index]; |
| 1156 | const global_object = &self.objects.items[global.getFile().?]; |
| 1157 | global_object.globals_lookup[global.sym_index] = global_index; |
| 1158 | global.* = sym_loc; |
| 1159 | self.mh_execute_header_index = global_index; |
| 1160 | } else { |
| 1161 | const global_index = @intCast(u32, self.globals.items.len); |
| 1162 | try self.globals.append(gpa, sym_loc); |
| 1163 | self.mh_execute_header_index = global_index; |
| 1164 | } |
| 1165 | } |
| 540 | 1166 | |
| 541 | | try macho_file.allocateSpecialSymbols(); |
| 1167 | fn createDsoHandleSymbol(self: *Zld, resolver: *SymbolResolver) !void { |
| 1168 | const global_index = resolver.table.get("___dso_handle") orelse return; |
| 1169 | const global = &self.globals.items[global_index]; |
| 1170 | self.dso_handle_index = global_index; |
| 1171 | if (!self.getSymbol(global.*).undf()) return; |
| 1172 | |
| 1173 | const gpa = self.gpa; |
| 1174 | const sym_index = try self.allocateSymbol(); |
| 1175 | const sym_loc = SymbolWithLoc{ .sym_index = sym_index }; |
| 1176 | const sym = self.getSymbolPtr(sym_loc); |
| 1177 | sym.n_strx = try self.strtab.insert(gpa, "___dso_handle"); |
| 1178 | sym.n_type = macho.N_SECT | macho.N_EXT; |
| 1179 | sym.n_desc = macho.N_WEAK_DEF; |
| 1180 | |
| 1181 | const global_object = &self.objects.items[global.getFile().?]; |
| 1182 | global_object.globals_lookup[global.sym_index] = global_index; |
| 1183 | _ = resolver.unresolved.swapRemove(resolver.table.get("___dso_handle").?); |
| 1184 | global.* = sym_loc; |
| 1185 | } |
| 542 | 1186 | |
| 543 | | if (build_options.enable_logging or true) { |
| 544 | | macho_file.logSymtab(); |
| 545 | | macho_file.logSections(); |
| 546 | | macho_file.logAtoms(); |
| 547 | | } |
| 1187 | fn resolveDyldStubBinder(self: *Zld, resolver: *SymbolResolver) !void { |
| 1188 | if (self.dyld_stub_binder_index != null) return; |
| 1189 | if (resolver.unresolved.count() == 0) return; // no need for a stub binder if we don't have any imports |
| 548 | 1190 | |
| 549 | | try writeAtoms(macho_file); |
| 1191 | const gpa = self.gpa; |
| 1192 | const sym_name = "dyld_stub_binder"; |
| 1193 | const sym_index = try self.allocateSymbol(); |
| 1194 | const sym_loc = SymbolWithLoc{ .sym_index = sym_index }; |
| 1195 | const sym = self.getSymbolPtr(sym_loc); |
| 1196 | sym.n_strx = try self.strtab.insert(gpa, sym_name); |
| 1197 | sym.n_type = macho.N_UNDF; |
| 550 | 1198 | |
| 551 | | var lc_buffer = std.ArrayList(u8).init(arena); |
| 552 | | const lc_writer = lc_buffer.writer(); |
| 553 | | var ncmds: u32 = 0; |
| 1199 | const global = SymbolWithLoc{ .sym_index = sym_index }; |
| 1200 | try self.globals.append(gpa, global); |
| 554 | 1201 | |
| 555 | | try writeLinkeditSegmentData(macho_file, &ncmds, lc_writer); |
| 1202 | for (self.dylibs.items) |dylib, id| { |
| 1203 | if (!dylib.symbols.contains(sym_name)) continue; |
| 556 | 1204 | |
| 557 | | // If the last section of __DATA segment is zerofill section, we need to ensure |
| 558 | | // that the free space between the end of the last non-zerofill section of __DATA |
| 559 | | // segment and the beginning of __LINKEDIT segment is zerofilled as the loader will |
| 560 | | // copy-paste this space into memory for quicker zerofill operation. |
| 561 | | if (macho_file.data_segment_cmd_index) |data_seg_id| blk: { |
| 562 | | var physical_zerofill_start: u64 = 0; |
| 563 | | const section_indexes = macho_file.getSectionIndexes(data_seg_id); |
| 564 | | for (macho_file.sections.items(.header)[section_indexes.start..section_indexes.end]) |header| { |
| 565 | | if (header.isZerofill() and header.size > 0) break; |
| 566 | | physical_zerofill_start = header.offset + header.size; |
| 567 | | } else break :blk; |
| 568 | | const linkedit = macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 569 | | const physical_zerofill_size = math.cast(usize, linkedit.fileoff - physical_zerofill_start) orelse |
| 570 | | return error.Overflow; |
| 571 | | if (physical_zerofill_size > 0) { |
| 572 | | var padding = try macho_file.base.allocator.alloc(u8, physical_zerofill_size); |
| 573 | | defer macho_file.base.allocator.free(padding); |
| 574 | | mem.set(u8, padding, 0); |
| 575 | | try macho_file.base.file.?.pwriteAll(padding, physical_zerofill_start); |
| 1205 | const dylib_id = @intCast(u16, id); |
| 1206 | if (!self.referenced_dylibs.contains(dylib_id)) { |
| 1207 | try self.referenced_dylibs.putNoClobber(gpa, dylib_id, {}); |
| 576 | 1208 | } |
| 577 | | } |
| 578 | 1209 | |
| 579 | | try MachO.writeDylinkerLC(&ncmds, lc_writer); |
| 580 | | try macho_file.writeMainLC(&ncmds, lc_writer); |
| 581 | | try macho_file.writeDylibIdLC(&ncmds, lc_writer); |
| 582 | | try macho_file.writeRpathLCs(&ncmds, lc_writer); |
| 1210 | const ordinal = self.referenced_dylibs.getIndex(dylib_id) orelse unreachable; |
| 1211 | sym.n_type |= macho.N_EXT; |
| 1212 | sym.n_desc = @intCast(u16, ordinal + 1) * macho.N_SYMBOL_RESOLVER; |
| 1213 | self.dyld_stub_binder_index = sym_index; |
| 583 | 1214 | |
| 584 | | { |
| 585 | | try lc_writer.writeStruct(macho.source_version_command{ |
| 586 | | .cmdsize = @sizeOf(macho.source_version_command), |
| 587 | | .version = 0x0, |
| 588 | | }); |
| 589 | | ncmds += 1; |
| 1215 | break; |
| 590 | 1216 | } |
| 591 | 1217 | |
| 592 | | try macho_file.writeBuildVersionLC(&ncmds, lc_writer); |
| 593 | | |
| 594 | | { |
| 595 | | var uuid_lc = macho.uuid_command{ |
| 596 | | .cmdsize = @sizeOf(macho.uuid_command), |
| 597 | | .uuid = undefined, |
| 598 | | }; |
| 599 | | std.crypto.random.bytes(&uuid_lc.uuid); |
| 600 | | try lc_writer.writeStruct(uuid_lc); |
| 601 | | ncmds += 1; |
| 1218 | if (self.dyld_stub_binder_index == null) { |
| 1219 | log.err("undefined reference to symbol '{s}'", .{sym_name}); |
| 1220 | return error.UndefinedSymbolReference; |
| 602 | 1221 | } |
| 1222 | } |
| 603 | 1223 | |
| 604 | | try macho_file.writeLoadDylibLCs(&ncmds, lc_writer); |
| 605 | | |
| 606 | | const requires_codesig = blk: { |
| 607 | | if (macho_file.base.options.entitlements) |_| break :blk true; |
| 608 | | if (cpu_arch == .aarch64 and (os_tag == .macos or abi == .simulator)) break :blk true; |
| 609 | | break :blk false; |
| 610 | | }; |
| 611 | | var codesig_offset: ?u32 = null; |
| 612 | | var codesig: ?CodeSignature = if (requires_codesig) blk: { |
| 613 | | // Preallocate space for the code signature. |
| 614 | | // We need to do this at this stage so that we have the load commands with proper values |
| 615 | | // written out to the file. |
| 616 | | // The most important here is to have the correct vm and filesize of the __LINKEDIT segment |
| 617 | | // where the code signature goes into. |
| 618 | | var codesig = CodeSignature.init(macho_file.page_size); |
| 619 | | codesig.code_directory.ident = macho_file.base.options.emit.?.sub_path; |
| 620 | | if (macho_file.base.options.entitlements) |path| { |
| 621 | | try codesig.addEntitlements(arena, path); |
| 622 | | } |
| 623 | | codesig_offset = try writeCodeSignaturePadding(macho_file, &codesig, &ncmds, lc_writer); |
| 624 | | break :blk codesig; |
| 625 | | } else null; |
| 626 | | |
| 627 | | var headers_buf = std.ArrayList(u8).init(arena); |
| 628 | | try writeSegmentHeaders(macho_file, &ncmds, headers_buf.writer()); |
| 1224 | fn writeDylinkerLC(ncmds: *u32, lc_writer: anytype) !void { |
| 1225 | const name_len = mem.sliceTo(MachO.default_dyld_path, 0).len; |
| 1226 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( |
| 1227 | u64, |
| 1228 | @sizeOf(macho.dylinker_command) + name_len, |
| 1229 | @sizeOf(u64), |
| 1230 | )); |
| 1231 | try lc_writer.writeStruct(macho.dylinker_command{ |
| 1232 | .cmd = .LOAD_DYLINKER, |
| 1233 | .cmdsize = cmdsize, |
| 1234 | .name = @sizeOf(macho.dylinker_command), |
| 1235 | }); |
| 1236 | try lc_writer.writeAll(mem.sliceTo(MachO.default_dyld_path, 0)); |
| 1237 | const padding = cmdsize - @sizeOf(macho.dylinker_command) - name_len; |
| 1238 | if (padding > 0) { |
| 1239 | try lc_writer.writeByteNTimes(0, padding); |
| 1240 | } |
| 1241 | ncmds.* += 1; |
| 1242 | } |
| 629 | 1243 | |
| 630 | | try macho_file.base.file.?.pwriteAll(headers_buf.items, @sizeOf(macho.mach_header_64)); |
| 631 | | try macho_file.base.file.?.pwriteAll(lc_buffer.items, @sizeOf(macho.mach_header_64) + headers_buf.items.len); |
| 1244 | fn writeMainLC(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 1245 | if (self.options.output_mode != .Exe) return; |
| 1246 | const seg_id = self.getSegmentByName("__TEXT").?; |
| 1247 | const seg = self.segments.items[seg_id]; |
| 1248 | const global = self.getEntryPoint(); |
| 1249 | const sym = self.getSymbol(global); |
| 1250 | try lc_writer.writeStruct(macho.entry_point_command{ |
| 1251 | .cmd = .MAIN, |
| 1252 | .cmdsize = @sizeOf(macho.entry_point_command), |
| 1253 | .entryoff = @intCast(u32, sym.n_value - seg.vmaddr), |
| 1254 | .stacksize = self.options.stack_size_override orelse 0, |
| 1255 | }); |
| 1256 | ncmds.* += 1; |
| 1257 | } |
| 632 | 1258 | |
| 633 | | try writeHeader(macho_file, ncmds, @intCast(u32, lc_buffer.items.len + headers_buf.items.len)); |
| 1259 | const WriteDylibLCCtx = struct { |
| 1260 | cmd: macho.LC, |
| 1261 | name: []const u8, |
| 1262 | timestamp: u32 = 2, |
| 1263 | current_version: u32 = 0x10000, |
| 1264 | compatibility_version: u32 = 0x10000, |
| 1265 | }; |
| 634 | 1266 | |
| 635 | | if (codesig) |*csig| { |
| 636 | | try writeCodeSignature(macho_file, csig, codesig_offset.?); // code signing always comes last |
| 1267 | fn writeDylibLC(ctx: WriteDylibLCCtx, ncmds: *u32, lc_writer: anytype) !void { |
| 1268 | const name_len = ctx.name.len + 1; |
| 1269 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( |
| 1270 | u64, |
| 1271 | @sizeOf(macho.dylib_command) + name_len, |
| 1272 | @sizeOf(u64), |
| 1273 | )); |
| 1274 | try lc_writer.writeStruct(macho.dylib_command{ |
| 1275 | .cmd = ctx.cmd, |
| 1276 | .cmdsize = cmdsize, |
| 1277 | .dylib = .{ |
| 1278 | .name = @sizeOf(macho.dylib_command), |
| 1279 | .timestamp = ctx.timestamp, |
| 1280 | .current_version = ctx.current_version, |
| 1281 | .compatibility_version = ctx.compatibility_version, |
| 1282 | }, |
| 1283 | }); |
| 1284 | try lc_writer.writeAll(ctx.name); |
| 1285 | try lc_writer.writeByte(0); |
| 1286 | const padding = cmdsize - @sizeOf(macho.dylib_command) - name_len; |
| 1287 | if (padding > 0) { |
| 1288 | try lc_writer.writeByteNTimes(0, padding); |
| 637 | 1289 | } |
| 1290 | ncmds.* += 1; |
| 638 | 1291 | } |
| 639 | 1292 | |
| 640 | | if (!macho_file.base.options.disable_lld_caching) { |
| 641 | | // Update the file with the digest. If it fails we can continue; it only |
| 642 | | // means that the next invocation will have an unnecessary cache miss. |
| 643 | | Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { |
| 644 | | log.debug("failed to save linking hash digest file: {s}", .{@errorName(err)}); |
| 1293 | fn writeDylibIdLC(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 1294 | if (self.options.output_mode != .Lib) return; |
| 1295 | const install_name = self.options.install_name orelse self.options.emit.?.sub_path; |
| 1296 | const curr = self.options.version orelse std.builtin.Version{ |
| 1297 | .major = 1, |
| 1298 | .minor = 0, |
| 1299 | .patch = 0, |
| 645 | 1300 | }; |
| 646 | | // Again failure here only means an unnecessary cache miss. |
| 647 | | man.writeManifest() catch |err| { |
| 648 | | log.debug("failed to write cache manifest when linking: {s}", .{@errorName(err)}); |
| 1301 | const compat = self.options.compatibility_version orelse std.builtin.Version{ |
| 1302 | .major = 1, |
| 1303 | .minor = 0, |
| 1304 | .patch = 0, |
| 649 | 1305 | }; |
| 650 | | // We hang on to this lock so that the output file path can be used without |
| 651 | | // other processes clobbering it. |
| 652 | | macho_file.base.lock = man.toOwnedLock(); |
| 1306 | try writeDylibLC(.{ |
| 1307 | .cmd = .ID_DYLIB, |
| 1308 | .name = install_name, |
| 1309 | .current_version = curr.major << 16 | curr.minor << 8 | curr.patch, |
| 1310 | .compatibility_version = compat.major << 16 | compat.minor << 8 | compat.patch, |
| 1311 | }, ncmds, lc_writer); |
| 653 | 1312 | } |
| 654 | | } |
| 655 | 1313 | |
| 656 | | fn initSections(macho_file: *MachO) !void { |
| 657 | | const gpa = macho_file.base.allocator; |
| 658 | | const cpu_arch = macho_file.base.options.target.cpu.arch; |
| 659 | | const pagezero_vmsize = macho_file.calcPagezeroSize(); |
| 660 | | |
| 661 | | if (macho_file.pagezero_segment_cmd_index == null) { |
| 662 | | if (pagezero_vmsize > 0) { |
| 663 | | macho_file.pagezero_segment_cmd_index = @intCast(u8, macho_file.segments.items.len); |
| 664 | | try macho_file.segments.append(gpa, .{ |
| 665 | | .segname = MachO.makeStaticString("__PAGEZERO"), |
| 666 | | .vmsize = pagezero_vmsize, |
| 667 | | .cmdsize = @sizeOf(macho.segment_command_64), |
| 668 | | }); |
| 1314 | const RpathIterator = struct { |
| 1315 | buffer: []const []const u8, |
| 1316 | table: std.StringHashMap(void), |
| 1317 | count: usize = 0, |
| 1318 | |
| 1319 | fn init(gpa: Allocator, rpaths: []const []const u8) RpathIterator { |
| 1320 | return .{ .buffer = rpaths, .table = std.StringHashMap(void).init(gpa) }; |
| 669 | 1321 | } |
| 670 | | } |
| 671 | 1322 | |
| 672 | | if (macho_file.text_segment_cmd_index == null) { |
| 673 | | macho_file.text_segment_cmd_index = @intCast(u8, macho_file.segments.items.len); |
| 674 | | try macho_file.segments.append(gpa, .{ |
| 675 | | .segname = MachO.makeStaticString("__TEXT"), |
| 676 | | .vmaddr = pagezero_vmsize, |
| 677 | | .vmsize = 0, |
| 678 | | .filesize = 0, |
| 679 | | .maxprot = macho.PROT.READ | macho.PROT.EXEC, |
| 680 | | .initprot = macho.PROT.READ | macho.PROT.EXEC, |
| 681 | | .cmdsize = @sizeOf(macho.segment_command_64), |
| 682 | | }); |
| 683 | | } |
| 1323 | fn deinit(it: *RpathIterator) void { |
| 1324 | it.table.deinit(); |
| 1325 | } |
| 684 | 1326 | |
| 685 | | if (macho_file.text_section_index == null) { |
| 686 | | macho_file.text_section_index = try macho_file.initSection("__TEXT", "__text", .{ |
| 687 | | .flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS, |
| 688 | | }); |
| 1327 | fn next(it: *RpathIterator) !?[]const u8 { |
| 1328 | while (true) { |
| 1329 | if (it.count >= it.buffer.len) return null; |
| 1330 | const rpath = it.buffer[it.count]; |
| 1331 | it.count += 1; |
| 1332 | const gop = try it.table.getOrPut(rpath); |
| 1333 | if (gop.found_existing) continue; |
| 1334 | return rpath; |
| 1335 | } |
| 1336 | } |
| 1337 | }; |
| 1338 | |
| 1339 | fn writeRpathLCs(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 1340 | const gpa = self.gpa; |
| 1341 | |
| 1342 | var it = RpathIterator.init(gpa, self.options.rpath_list); |
| 1343 | defer it.deinit(); |
| 1344 | |
| 1345 | while (try it.next()) |rpath| { |
| 1346 | const rpath_len = rpath.len + 1; |
| 1347 | const cmdsize = @intCast(u32, mem.alignForwardGeneric( |
| 1348 | u64, |
| 1349 | @sizeOf(macho.rpath_command) + rpath_len, |
| 1350 | @sizeOf(u64), |
| 1351 | )); |
| 1352 | try lc_writer.writeStruct(macho.rpath_command{ |
| 1353 | .cmdsize = cmdsize, |
| 1354 | .path = @sizeOf(macho.rpath_command), |
| 1355 | }); |
| 1356 | try lc_writer.writeAll(rpath); |
| 1357 | try lc_writer.writeByte(0); |
| 1358 | const padding = cmdsize - @sizeOf(macho.rpath_command) - rpath_len; |
| 1359 | if (padding > 0) { |
| 1360 | try lc_writer.writeByteNTimes(0, padding); |
| 1361 | } |
| 1362 | ncmds.* += 1; |
| 1363 | } |
| 689 | 1364 | } |
| 690 | 1365 | |
| 691 | | if (macho_file.stubs_section_index == null) { |
| 692 | | const stub_size: u4 = switch (cpu_arch) { |
| 693 | | .x86_64 => 6, |
| 694 | | .aarch64 => 3 * @sizeOf(u32), |
| 695 | | else => unreachable, // unhandled architecture type |
| 1366 | fn writeBuildVersionLC(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 1367 | const cmdsize = @sizeOf(macho.build_version_command) + @sizeOf(macho.build_tool_version); |
| 1368 | const platform_version = blk: { |
| 1369 | const ver = self.options.target.os.version_range.semver.min; |
| 1370 | const platform_version = ver.major << 16 | ver.minor << 8; |
| 1371 | break :blk platform_version; |
| 696 | 1372 | }; |
| 697 | | macho_file.stubs_section_index = try macho_file.initSection("__TEXT", "__stubs", .{ |
| 698 | | .flags = macho.S_SYMBOL_STUBS | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS, |
| 699 | | .reserved2 = stub_size, |
| 1373 | const sdk_version = if (self.options.native_darwin_sdk) |sdk| blk: { |
| 1374 | const ver = sdk.version; |
| 1375 | const sdk_version = ver.major << 16 | ver.minor << 8; |
| 1376 | break :blk sdk_version; |
| 1377 | } else platform_version; |
| 1378 | const is_simulator_abi = self.options.target.abi == .simulator; |
| 1379 | try lc_writer.writeStruct(macho.build_version_command{ |
| 1380 | .cmdsize = cmdsize, |
| 1381 | .platform = switch (self.options.target.os.tag) { |
| 1382 | .macos => .MACOS, |
| 1383 | .ios => if (is_simulator_abi) macho.PLATFORM.IOSSIMULATOR else macho.PLATFORM.IOS, |
| 1384 | .watchos => if (is_simulator_abi) macho.PLATFORM.WATCHOSSIMULATOR else macho.PLATFORM.WATCHOS, |
| 1385 | .tvos => if (is_simulator_abi) macho.PLATFORM.TVOSSIMULATOR else macho.PLATFORM.TVOS, |
| 1386 | else => unreachable, |
| 1387 | }, |
| 1388 | .minos = platform_version, |
| 1389 | .sdk = sdk_version, |
| 1390 | .ntools = 1, |
| 700 | 1391 | }); |
| 1392 | try lc_writer.writeAll(mem.asBytes(&macho.build_tool_version{ |
| 1393 | .tool = .LD, |
| 1394 | .version = 0x0, |
| 1395 | })); |
| 1396 | ncmds.* += 1; |
| 701 | 1397 | } |
| 702 | 1398 | |
| 703 | | if (macho_file.stub_helper_section_index == null) { |
| 704 | | macho_file.stub_helper_section_index = try macho_file.initSection("__TEXT", "__stub_helper", .{ |
| 705 | | .flags = macho.S_REGULAR | macho.S_ATTR_PURE_INSTRUCTIONS | macho.S_ATTR_SOME_INSTRUCTIONS, |
| 706 | | }); |
| 1399 | fn writeLoadDylibLCs(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 1400 | for (self.referenced_dylibs.keys()) |id| { |
| 1401 | const dylib = self.dylibs.items[id]; |
| 1402 | const dylib_id = dylib.id orelse unreachable; |
| 1403 | try writeDylibLC(.{ |
| 1404 | .cmd = if (dylib.weak) .LOAD_WEAK_DYLIB else .LOAD_DYLIB, |
| 1405 | .name = dylib_id.name, |
| 1406 | .timestamp = dylib_id.timestamp, |
| 1407 | .current_version = dylib_id.current_version, |
| 1408 | .compatibility_version = dylib_id.compatibility_version, |
| 1409 | }, ncmds, lc_writer); |
| 1410 | } |
| 707 | 1411 | } |
| 708 | 1412 | |
| 709 | | if (macho_file.data_const_segment_cmd_index == null) { |
| 710 | | macho_file.data_const_segment_cmd_index = @intCast(u8, macho_file.segments.items.len); |
| 711 | | try macho_file.segments.append(gpa, .{ |
| 712 | | .segname = MachO.makeStaticString("__DATA_CONST"), |
| 713 | | .vmaddr = 0, |
| 714 | | .vmsize = 0, |
| 715 | | .fileoff = 0, |
| 716 | | .filesize = 0, |
| 717 | | .maxprot = macho.PROT.READ | macho.PROT.WRITE, |
| 718 | | .initprot = macho.PROT.READ | macho.PROT.WRITE, |
| 719 | | .cmdsize = @sizeOf(macho.segment_command_64), |
| 720 | | }); |
| 721 | | } |
| 1413 | pub fn deinit(self: *Zld) void { |
| 1414 | const gpa = self.gpa; |
| 722 | 1415 | |
| 723 | | if (macho_file.got_section_index == null) { |
| 724 | | macho_file.got_section_index = try macho_file.initSection("__DATA_CONST", "__got", .{ |
| 725 | | .flags = macho.S_NON_LAZY_SYMBOL_POINTERS, |
| 726 | | }); |
| 727 | | } |
| 1416 | for (self.archives.items) |archive| { |
| 1417 | archive.file.close(); |
| 1418 | } |
| 728 | 1419 | |
| 729 | | if (macho_file.data_segment_cmd_index == null) { |
| 730 | | macho_file.data_segment_cmd_index = @intCast(u8, macho_file.segments.items.len); |
| 731 | | try macho_file.segments.append(gpa, .{ |
| 732 | | .segname = MachO.makeStaticString("__DATA"), |
| 733 | | .vmaddr = 0, |
| 734 | | .vmsize = 0, |
| 735 | | .fileoff = 0, |
| 736 | | .filesize = 0, |
| 737 | | .maxprot = macho.PROT.READ | macho.PROT.WRITE, |
| 738 | | .initprot = macho.PROT.READ | macho.PROT.WRITE, |
| 739 | | .cmdsize = @sizeOf(macho.segment_command_64), |
| 740 | | }); |
| 741 | | } |
| 1420 | self.tlv_ptr_entries.deinit(gpa); |
| 1421 | self.tlv_ptr_table.deinit(gpa); |
| 1422 | self.got_entries.deinit(gpa); |
| 1423 | self.got_table.deinit(gpa); |
| 1424 | self.stubs.deinit(gpa); |
| 1425 | self.stubs_table.deinit(gpa); |
| 1426 | self.thunk_table.deinit(gpa); |
| 742 | 1427 | |
| 743 | | if (macho_file.la_symbol_ptr_section_index == null) { |
| 744 | | macho_file.la_symbol_ptr_section_index = try macho_file.initSection("__DATA", "__la_symbol_ptr", .{ |
| 745 | | .flags = macho.S_LAZY_SYMBOL_POINTERS, |
| 746 | | }); |
| 747 | | } |
| 1428 | for (self.thunks.items) |*thunk| { |
| 1429 | thunk.deinit(gpa); |
| 1430 | } |
| 1431 | self.thunks.deinit(gpa); |
| 748 | 1432 | |
| 749 | | if (macho_file.data_section_index == null) { |
| 750 | | macho_file.data_section_index = try macho_file.initSection("__DATA", "__data", .{}); |
| 751 | | } |
| 1433 | self.strtab.deinit(gpa); |
| 1434 | self.locals.deinit(gpa); |
| 1435 | self.globals.deinit(gpa); |
| 752 | 1436 | |
| 753 | | if (macho_file.linkedit_segment_cmd_index == null) { |
| 754 | | macho_file.linkedit_segment_cmd_index = @intCast(u8, macho_file.segments.items.len); |
| 755 | | try macho_file.segments.append(gpa, .{ |
| 756 | | .segname = MachO.makeStaticString("__LINKEDIT"), |
| 757 | | .vmaddr = 0, |
| 758 | | .fileoff = 0, |
| 759 | | .maxprot = macho.PROT.READ, |
| 760 | | .initprot = macho.PROT.READ, |
| 761 | | .cmdsize = @sizeOf(macho.segment_command_64), |
| 762 | | }); |
| 763 | | } |
| 764 | | } |
| 1437 | for (self.objects.items) |*object| { |
| 1438 | object.deinit(gpa); |
| 1439 | } |
| 1440 | self.objects.deinit(gpa); |
| 1441 | for (self.archives.items) |*archive| { |
| 1442 | archive.deinit(gpa); |
| 1443 | } |
| 1444 | self.archives.deinit(gpa); |
| 1445 | for (self.dylibs.items) |*dylib| { |
| 1446 | dylib.deinit(gpa); |
| 1447 | } |
| 1448 | self.dylibs.deinit(gpa); |
| 1449 | self.dylibs_map.deinit(gpa); |
| 1450 | self.referenced_dylibs.deinit(gpa); |
| 765 | 1451 | |
| 766 | | fn writeAtoms(macho_file: *MachO) !void { |
| 767 | | assert(macho_file.mode == .one_shot); |
| 1452 | self.segments.deinit(gpa); |
| 1453 | self.sections.deinit(gpa); |
| 1454 | self.atoms.deinit(gpa); |
| 1455 | } |
| 768 | 1456 | |
| 769 | | const gpa = macho_file.base.allocator; |
| 770 | | const slice = macho_file.sections.slice(); |
| 1457 | fn createSegments(self: *Zld) !void { |
| 1458 | const pagezero_vmsize = self.options.pagezero_size orelse MachO.default_pagezero_vmsize; |
| 1459 | const aligned_pagezero_vmsize = mem.alignBackwardGeneric(u64, pagezero_vmsize, self.page_size); |
| 1460 | if (self.options.output_mode != .Lib and aligned_pagezero_vmsize > 0) { |
| 1461 | if (aligned_pagezero_vmsize != pagezero_vmsize) { |
| 1462 | log.warn("requested __PAGEZERO size (0x{x}) is not page aligned", .{pagezero_vmsize}); |
| 1463 | log.warn(" rounding down to 0x{x}", .{aligned_pagezero_vmsize}); |
| 1464 | } |
| 1465 | try self.segments.append(self.gpa, .{ |
| 1466 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 1467 | .segname = makeStaticString("__PAGEZERO"), |
| 1468 | .vmsize = aligned_pagezero_vmsize, |
| 1469 | }); |
| 1470 | } |
| 771 | 1471 | |
| 772 | | for (slice.items(.last_atom)) |last_atom, sect_id| { |
| 773 | | const header = slice.items(.header)[sect_id]; |
| 774 | | if (header.size == 0) continue; |
| 775 | | var atom = last_atom.?; |
| 1472 | for (self.sections.items(.header)) |header, sect_id| { |
| 1473 | if (header.size == 0) continue; // empty section |
| 1474 | |
| 1475 | const segname = header.segName(); |
| 1476 | const segment_id = self.getSegmentByName(segname) orelse blk: { |
| 1477 | log.debug("creating segment '{s}'", .{segname}); |
| 1478 | const segment_id = @intCast(u8, self.segments.items.len); |
| 1479 | const protection = getSegmentMemoryProtection(segname); |
| 1480 | try self.segments.append(self.gpa, .{ |
| 1481 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 1482 | .segname = makeStaticString(segname), |
| 1483 | .maxprot = protection, |
| 1484 | .initprot = protection, |
| 1485 | }); |
| 1486 | break :blk segment_id; |
| 1487 | }; |
| 1488 | const segment = &self.segments.items[segment_id]; |
| 1489 | segment.cmdsize += @sizeOf(macho.section_64); |
| 1490 | segment.nsects += 1; |
| 1491 | self.sections.items(.segment_index)[sect_id] = segment_id; |
| 1492 | } |
| 776 | 1493 | |
| 777 | | if (header.isZerofill()) continue; |
| 1494 | { |
| 1495 | const protection = getSegmentMemoryProtection("__LINKEDIT"); |
| 1496 | const base = self.getSegmentAllocBase(@intCast(u8, self.segments.items.len)); |
| 1497 | try self.segments.append(self.gpa, .{ |
| 1498 | .cmdsize = @sizeOf(macho.segment_command_64), |
| 1499 | .segname = makeStaticString("__LINKEDIT"), |
| 1500 | .vmaddr = base.vmaddr, |
| 1501 | .fileoff = base.fileoff, |
| 1502 | .maxprot = protection, |
| 1503 | .initprot = protection, |
| 1504 | }); |
| 1505 | } |
| 1506 | } |
| 778 | 1507 | |
| 779 | | var buffer = std.ArrayList(u8).init(gpa); |
| 780 | | defer buffer.deinit(); |
| 781 | | try buffer.ensureTotalCapacity(math.cast(usize, header.size) orelse return error.Overflow); |
| 1508 | inline fn calcInstallNameLen(cmd_size: u64, name: []const u8, assume_max_path_len: bool) u64 { |
| 1509 | const name_len = if (assume_max_path_len) std.os.PATH_MAX else std.mem.len(name) + 1; |
| 1510 | return mem.alignForwardGeneric(u64, cmd_size + name_len, @alignOf(u64)); |
| 1511 | } |
| 782 | 1512 | |
| 783 | | log.debug("writing atoms in {s},{s}", .{ header.segName(), header.sectName() }); |
| 1513 | fn calcLCsSize(self: *Zld, assume_max_path_len: bool) !u32 { |
| 1514 | const gpa = self.gpa; |
| 784 | 1515 | |
| 785 | | while (atom.prev) |prev| { |
| 786 | | atom = prev; |
| 1516 | var sizeofcmds: u64 = 0; |
| 1517 | for (self.segments.items) |seg| { |
| 1518 | sizeofcmds += seg.nsects * @sizeOf(macho.section_64) + @sizeOf(macho.segment_command_64); |
| 787 | 1519 | } |
| 788 | 1520 | |
| 789 | | while (true) { |
| 790 | | const this_sym = atom.getSymbol(macho_file); |
| 791 | | const padding_size: usize = if (atom.next) |next| blk: { |
| 792 | | const next_sym = next.getSymbol(macho_file); |
| 793 | | const size = next_sym.n_value - (this_sym.n_value + atom.size); |
| 794 | | break :blk math.cast(usize, size) orelse return error.Overflow; |
| 795 | | } else 0; |
| 796 | | |
| 797 | | log.debug(" (adding ATOM(%{d}, '{s}') from object({?d}) to buffer)", .{ |
| 798 | | atom.sym_index, |
| 799 | | atom.getName(macho_file), |
| 800 | | atom.file, |
| 801 | | }); |
| 802 | | if (padding_size > 0) { |
| 803 | | log.debug(" (with padding {x})", .{padding_size}); |
| 804 | | } |
| 805 | | |
| 806 | | try atom.resolveRelocs(macho_file); |
| 807 | | buffer.appendSliceAssumeCapacity(atom.code.items); |
| 808 | | |
| 809 | | var i: usize = 0; |
| 810 | | while (i < padding_size) : (i += 1) { |
| 811 | | // TODO with NOPs |
| 812 | | buffer.appendAssumeCapacity(0); |
| 1521 | // LC_DYLD_INFO_ONLY |
| 1522 | sizeofcmds += @sizeOf(macho.dyld_info_command); |
| 1523 | // LC_FUNCTION_STARTS |
| 1524 | if (self.getSectionByName("__TEXT", "__text")) |_| { |
| 1525 | sizeofcmds += @sizeOf(macho.linkedit_data_command); |
| 1526 | } |
| 1527 | // LC_DATA_IN_CODE |
| 1528 | sizeofcmds += @sizeOf(macho.linkedit_data_command); |
| 1529 | // LC_SYMTAB |
| 1530 | sizeofcmds += @sizeOf(macho.symtab_command); |
| 1531 | // LC_DYSYMTAB |
| 1532 | sizeofcmds += @sizeOf(macho.dysymtab_command); |
| 1533 | // LC_LOAD_DYLINKER |
| 1534 | sizeofcmds += calcInstallNameLen( |
| 1535 | @sizeOf(macho.dylinker_command), |
| 1536 | mem.sliceTo(MachO.default_dyld_path, 0), |
| 1537 | false, |
| 1538 | ); |
| 1539 | // LC_MAIN |
| 1540 | if (self.options.output_mode == .Exe) { |
| 1541 | sizeofcmds += @sizeOf(macho.entry_point_command); |
| 1542 | } |
| 1543 | // LC_ID_DYLIB |
| 1544 | if (self.options.output_mode == .Lib) { |
| 1545 | sizeofcmds += blk: { |
| 1546 | const install_name = self.options.install_name orelse self.options.emit.?.sub_path; |
| 1547 | break :blk calcInstallNameLen( |
| 1548 | @sizeOf(macho.dylib_command), |
| 1549 | install_name, |
| 1550 | assume_max_path_len, |
| 1551 | ); |
| 1552 | }; |
| 1553 | } |
| 1554 | // LC_RPATH |
| 1555 | { |
| 1556 | var it = RpathIterator.init(gpa, self.options.rpath_list); |
| 1557 | defer it.deinit(); |
| 1558 | while (try it.next()) |rpath| { |
| 1559 | sizeofcmds += calcInstallNameLen( |
| 1560 | @sizeOf(macho.rpath_command), |
| 1561 | rpath, |
| 1562 | assume_max_path_len, |
| 1563 | ); |
| 813 | 1564 | } |
| 814 | | |
| 815 | | if (atom.next) |next| { |
| 816 | | atom = next; |
| 817 | | } else { |
| 818 | | assert(buffer.items.len == header.size); |
| 819 | | log.debug(" (writing at file offset 0x{x})", .{header.offset}); |
| 820 | | try macho_file.base.file.?.pwriteAll(buffer.items, header.offset); |
| 821 | | break; |
| 1565 | } |
| 1566 | // LC_SOURCE_VERSION |
| 1567 | sizeofcmds += @sizeOf(macho.source_version_command); |
| 1568 | // LC_BUILD_VERSION |
| 1569 | sizeofcmds += @sizeOf(macho.build_version_command) + @sizeOf(macho.build_tool_version); |
| 1570 | // LC_UUID |
| 1571 | sizeofcmds += @sizeOf(macho.uuid_command); |
| 1572 | // LC_LOAD_DYLIB |
| 1573 | for (self.referenced_dylibs.keys()) |id| { |
| 1574 | const dylib = self.dylibs.items[id]; |
| 1575 | const dylib_id = dylib.id orelse unreachable; |
| 1576 | sizeofcmds += calcInstallNameLen( |
| 1577 | @sizeOf(macho.dylib_command), |
| 1578 | dylib_id.name, |
| 1579 | assume_max_path_len, |
| 1580 | ); |
| 1581 | } |
| 1582 | // LC_CODE_SIGNATURE |
| 1583 | { |
| 1584 | const target = self.options.target; |
| 1585 | const requires_codesig = blk: { |
| 1586 | if (self.options.entitlements) |_| break :blk true; |
| 1587 | if (target.cpu.arch == .aarch64 and (target.os.tag == .macos or target.abi == .simulator)) |
| 1588 | break :blk true; |
| 1589 | break :blk false; |
| 1590 | }; |
| 1591 | if (requires_codesig) { |
| 1592 | sizeofcmds += @sizeOf(macho.linkedit_data_command); |
| 822 | 1593 | } |
| 823 | 1594 | } |
| 824 | | } |
| 825 | | } |
| 826 | 1595 | |
| 827 | | fn allocateSegments(macho_file: *MachO) !void { |
| 828 | | try allocateSegment(macho_file, macho_file.text_segment_cmd_index, &.{ |
| 829 | | macho_file.pagezero_segment_cmd_index, |
| 830 | | }, try macho_file.calcMinHeaderPad()); |
| 1596 | return @intCast(u32, sizeofcmds); |
| 1597 | } |
| 831 | 1598 | |
| 832 | | if (macho_file.text_segment_cmd_index) |index| blk: { |
| 833 | | const indexes = macho_file.getSectionIndexes(index); |
| 834 | | if (indexes.start == indexes.end) break :blk; |
| 835 | | const seg = macho_file.segments.items[index]; |
| 1599 | fn calcMinHeaderPad(self: *Zld) !u64 { |
| 1600 | var padding: u32 = (try self.calcLCsSize(false)) + (self.options.headerpad_size orelse 0); |
| 1601 | log.debug("minimum requested headerpad size 0x{x}", .{padding + @sizeOf(macho.mach_header_64)}); |
| 836 | 1602 | |
| 837 | | // Shift all sections to the back to minimize jump size between __TEXT and __DATA segments. |
| 838 | | var min_alignment: u32 = 0; |
| 839 | | for (macho_file.sections.items(.header)[indexes.start..indexes.end]) |header| { |
| 840 | | const alignment = try math.powi(u32, 2, header.@"align"); |
| 841 | | min_alignment = math.max(min_alignment, alignment); |
| 1603 | if (self.options.headerpad_max_install_names) { |
| 1604 | var min_headerpad_size: u32 = try self.calcLCsSize(true); |
| 1605 | log.debug("headerpad_max_install_names minimum headerpad size 0x{x}", .{ |
| 1606 | min_headerpad_size + @sizeOf(macho.mach_header_64), |
| 1607 | }); |
| 1608 | padding = @max(padding, min_headerpad_size); |
| 842 | 1609 | } |
| 843 | 1610 | |
| 844 | | assert(min_alignment > 0); |
| 845 | | const last_header = macho_file.sections.items(.header)[indexes.end - 1]; |
| 846 | | const shift: u32 = shift: { |
| 847 | | const diff = seg.filesize - last_header.offset - last_header.size; |
| 848 | | const factor = @divTrunc(diff, min_alignment); |
| 849 | | break :shift @intCast(u32, factor * min_alignment); |
| 1611 | const offset = @sizeOf(macho.mach_header_64) + padding; |
| 1612 | log.debug("actual headerpad size 0x{x}", .{offset}); |
| 1613 | |
| 1614 | return offset; |
| 1615 | } |
| 1616 | |
| 1617 | pub fn allocateSymbol(self: *Zld) !u32 { |
| 1618 | try self.locals.ensureUnusedCapacity(self.gpa, 1); |
| 1619 | log.debug(" (allocating symbol index {d})", .{self.locals.items.len}); |
| 1620 | const index = @intCast(u32, self.locals.items.len); |
| 1621 | _ = self.locals.addOneAssumeCapacity(); |
| 1622 | self.locals.items[index] = .{ |
| 1623 | .n_strx = 0, |
| 1624 | .n_type = 0, |
| 1625 | .n_sect = 0, |
| 1626 | .n_desc = 0, |
| 1627 | .n_value = 0, |
| 850 | 1628 | }; |
| 1629 | return index; |
| 1630 | } |
| 851 | 1631 | |
| 852 | | if (shift > 0) { |
| 853 | | for (macho_file.sections.items(.header)[indexes.start..indexes.end]) |*header| { |
| 854 | | header.offset += shift; |
| 855 | | header.addr += shift; |
| 856 | | } |
| 1632 | fn allocateSpecialSymbols(self: *Zld) !void { |
| 1633 | for (&[_]?u32{ |
| 1634 | self.dso_handle_index, |
| 1635 | self.mh_execute_header_index, |
| 1636 | }) |maybe_index| { |
| 1637 | const global_index = maybe_index orelse continue; |
| 1638 | const global = self.globals.items[global_index]; |
| 1639 | if (global.getFile() != null) continue; |
| 1640 | const name = self.getSymbolName(global); |
| 1641 | const sym = self.getSymbolPtr(global); |
| 1642 | const segment_index = self.getSegmentByName("__TEXT").?; |
| 1643 | const seg = self.segments.items[segment_index]; |
| 1644 | sym.n_sect = 1; |
| 1645 | sym.n_value = seg.vmaddr; |
| 1646 | log.debug("allocating {s} at the start of {s}", .{ |
| 1647 | name, |
| 1648 | seg.segName(), |
| 1649 | }); |
| 857 | 1650 | } |
| 858 | 1651 | } |
| 859 | 1652 | |
| 860 | | try allocateSegment(macho_file, macho_file.data_const_segment_cmd_index, &.{ |
| 861 | | macho_file.text_segment_cmd_index, |
| 862 | | macho_file.pagezero_segment_cmd_index, |
| 863 | | }, 0); |
| 1653 | fn writeAtoms(self: *Zld, reverse_lookups: [][]u32) !void { |
| 1654 | const gpa = self.gpa; |
| 1655 | const slice = self.sections.slice(); |
| 864 | 1656 | |
| 865 | | try allocateSegment(macho_file, macho_file.data_segment_cmd_index, &.{ |
| 866 | | macho_file.data_const_segment_cmd_index, |
| 867 | | macho_file.text_segment_cmd_index, |
| 868 | | macho_file.pagezero_segment_cmd_index, |
| 869 | | }, 0); |
| 1657 | for (slice.items(.first_atom_index)) |first_atom_index, sect_id| { |
| 1658 | const header = slice.items(.header)[sect_id]; |
| 1659 | var atom_index = first_atom_index; |
| 870 | 1660 | |
| 871 | | try allocateSegment(macho_file, macho_file.linkedit_segment_cmd_index, &.{ |
| 872 | | macho_file.data_segment_cmd_index, |
| 873 | | macho_file.data_const_segment_cmd_index, |
| 874 | | macho_file.text_segment_cmd_index, |
| 875 | | macho_file.pagezero_segment_cmd_index, |
| 876 | | }, 0); |
| 877 | | } |
| 1661 | if (header.isZerofill()) continue; |
| 878 | 1662 | |
| 879 | | fn getSegmentAllocBase(macho_file: *MachO, indices: []const ?u8) struct { vmaddr: u64, fileoff: u64 } { |
| 880 | | for (indices) |maybe_prev_id| { |
| 881 | | const prev_id = maybe_prev_id orelse continue; |
| 882 | | const prev = macho_file.segments.items[prev_id]; |
| 883 | | return .{ |
| 884 | | .vmaddr = prev.vmaddr + prev.vmsize, |
| 885 | | .fileoff = prev.fileoff + prev.filesize, |
| 886 | | }; |
| 887 | | } |
| 888 | | return .{ .vmaddr = 0, .fileoff = 0 }; |
| 889 | | } |
| 1663 | var buffer = std.ArrayList(u8).init(gpa); |
| 1664 | defer buffer.deinit(); |
| 1665 | try buffer.ensureTotalCapacity(math.cast(usize, header.size) orelse return error.Overflow); |
| 1666 | |
| 1667 | log.debug("writing atoms in {s},{s}", .{ header.segName(), header.sectName() }); |
| 890 | 1668 | |
| 891 | | fn allocateSegment(macho_file: *MachO, maybe_index: ?u8, indices: []const ?u8, init_size: u64) !void { |
| 892 | | const index = maybe_index orelse return; |
| 893 | | const seg = &macho_file.segments.items[index]; |
| 1669 | var count: u32 = 0; |
| 1670 | while (true) : (count += 1) { |
| 1671 | const atom = self.getAtom(atom_index); |
| 1672 | const this_sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 1673 | const padding_size: usize = if (atom.next_index) |next_index| blk: { |
| 1674 | const next_sym = self.getSymbol(self.getAtom(next_index).getSymbolWithLoc()); |
| 1675 | const size = next_sym.n_value - (this_sym.n_value + atom.size); |
| 1676 | break :blk math.cast(usize, size) orelse return error.Overflow; |
| 1677 | } else 0; |
| 894 | 1678 | |
| 895 | | const base = getSegmentAllocBase(macho_file, indices); |
| 896 | | seg.vmaddr = base.vmaddr; |
| 897 | | seg.fileoff = base.fileoff; |
| 898 | | seg.filesize = init_size; |
| 899 | | seg.vmsize = init_size; |
| 1679 | log.debug(" (adding ATOM(%{d}, '{s}') from object({?}) to buffer)", .{ |
| 1680 | atom.sym_index, |
| 1681 | self.getSymbolName(atom.getSymbolWithLoc()), |
| 1682 | atom.file, |
| 1683 | }); |
| 1684 | if (padding_size > 0) { |
| 1685 | log.debug(" (with padding {x})", .{padding_size}); |
| 1686 | } |
| 900 | 1687 | |
| 901 | | // Allocate the sections according to their alignment at the beginning of the segment. |
| 902 | | const indexes = macho_file.getSectionIndexes(index); |
| 903 | | var start = init_size; |
| 904 | | const slice = macho_file.sections.slice(); |
| 905 | | for (slice.items(.header)[indexes.start..indexes.end]) |*header| { |
| 906 | | const alignment = try math.powi(u32, 2, header.@"align"); |
| 907 | | const start_aligned = mem.alignForwardGeneric(u64, start, alignment); |
| 1688 | const offset = buffer.items.len; |
| 908 | 1689 | |
| 909 | | header.offset = if (header.isZerofill()) |
| 910 | | 0 |
| 911 | | else |
| 912 | | @intCast(u32, seg.fileoff + start_aligned); |
| 913 | | header.addr = seg.vmaddr + start_aligned; |
| 1690 | // TODO: move writing synthetic sections into a separate function |
| 1691 | if (atom.getFile() == null) outer: { |
| 1692 | if (self.dyld_private_sym_index) |sym_index| { |
| 1693 | if (atom.sym_index == sym_index) { |
| 1694 | buffer.appendSliceAssumeCapacity(&[_]u8{0} ** @sizeOf(u64)); |
| 1695 | break :outer; |
| 1696 | } |
| 1697 | } |
| 1698 | switch (header.@"type"()) { |
| 1699 | macho.S_NON_LAZY_SYMBOL_POINTERS => { |
| 1700 | try self.writeGotPointer(count, buffer.writer()); |
| 1701 | }, |
| 1702 | macho.S_LAZY_SYMBOL_POINTERS => { |
| 1703 | try self.writeLazyPointer(count, buffer.writer()); |
| 1704 | }, |
| 1705 | macho.S_THREAD_LOCAL_VARIABLE_POINTERS => { |
| 1706 | buffer.appendSliceAssumeCapacity(&[_]u8{0} ** @sizeOf(u64)); |
| 1707 | }, |
| 1708 | else => { |
| 1709 | if (self.stub_helper_preamble_sym_index) |sym_index| { |
| 1710 | if (sym_index == atom.sym_index) { |
| 1711 | try self.writeStubHelperPreambleCode(buffer.writer()); |
| 1712 | break :outer; |
| 1713 | } |
| 1714 | } |
| 1715 | if (header.@"type"() == macho.S_SYMBOL_STUBS) { |
| 1716 | try self.writeStubCode(atom_index, count, buffer.writer()); |
| 1717 | } else if (mem.eql(u8, header.sectName(), "__stub_helper")) { |
| 1718 | try self.writeStubHelperCode(atom_index, buffer.writer()); |
| 1719 | } else if (header.isCode()) { |
| 1720 | // A thunk |
| 1721 | try thunks.writeThunkCode(self, atom_index, buffer.writer()); |
| 1722 | } else unreachable; |
| 1723 | }, |
| 1724 | } |
| 1725 | } else { |
| 1726 | const code = Atom.getAtomCode(self, atom_index); |
| 1727 | const relocs = Atom.getAtomRelocs(self, atom_index); |
| 1728 | buffer.appendSliceAssumeCapacity(code); |
| 1729 | try Atom.resolveRelocs( |
| 1730 | self, |
| 1731 | atom_index, |
| 1732 | buffer.items[offset..][0..atom.size], |
| 1733 | relocs, |
| 1734 | reverse_lookups[atom.getFile().?], |
| 1735 | ); |
| 1736 | } |
| 914 | 1737 | |
| 915 | | start = start_aligned + header.size; |
| 1738 | var i: usize = 0; |
| 1739 | while (i < padding_size) : (i += 1) { |
| 1740 | // TODO with NOPs |
| 1741 | buffer.appendAssumeCapacity(0); |
| 1742 | } |
| 916 | 1743 | |
| 917 | | if (!header.isZerofill()) { |
| 918 | | seg.filesize = start; |
| 1744 | if (atom.next_index) |next_index| { |
| 1745 | atom_index = next_index; |
| 1746 | } else { |
| 1747 | assert(buffer.items.len == header.size); |
| 1748 | log.debug(" (writing at file offset 0x{x})", .{header.offset}); |
| 1749 | try self.file.pwriteAll(buffer.items, header.offset); |
| 1750 | break; |
| 1751 | } |
| 1752 | } |
| 919 | 1753 | } |
| 920 | | seg.vmsize = start; |
| 921 | 1754 | } |
| 922 | 1755 | |
| 923 | | seg.filesize = mem.alignForwardGeneric(u64, seg.filesize, macho_file.page_size); |
| 924 | | seg.vmsize = mem.alignForwardGeneric(u64, seg.vmsize, macho_file.page_size); |
| 925 | | } |
| 1756 | fn pruneAndSortSections(self: *Zld) !void { |
| 1757 | const gpa = self.gpa; |
| 1758 | |
| 1759 | const SortSection = struct { |
| 1760 | pub fn lessThan(_: void, lhs: Section, rhs: Section) bool { |
| 1761 | return getSectionPrecedence(lhs.header) < getSectionPrecedence(rhs.header); |
| 1762 | } |
| 1763 | }; |
| 926 | 1764 | |
| 927 | | fn allocateSymbols(macho_file: *MachO) !void { |
| 928 | | const slice = macho_file.sections.slice(); |
| 929 | | for (slice.items(.last_atom)) |last_atom, sect_id| { |
| 930 | | const header = slice.items(.header)[sect_id]; |
| 931 | | var atom = last_atom orelse continue; |
| 1765 | const slice = self.sections.slice(); |
| 1766 | var sections = std.ArrayList(Section).init(gpa); |
| 1767 | defer sections.deinit(); |
| 1768 | try sections.ensureTotalCapacity(slice.len); |
| 932 | 1769 | |
| 933 | | while (atom.prev) |prev| { |
| 934 | | atom = prev; |
| 1770 | { |
| 1771 | var i: u8 = 0; |
| 1772 | while (i < slice.len) : (i += 1) { |
| 1773 | const section = self.sections.get(i); |
| 1774 | if (section.header.size == 0) { |
| 1775 | log.debug("pruning section {s},{s}", .{ |
| 1776 | section.header.segName(), |
| 1777 | section.header.sectName(), |
| 1778 | }); |
| 1779 | continue; |
| 1780 | } |
| 1781 | sections.appendAssumeCapacity(section); |
| 1782 | } |
| 935 | 1783 | } |
| 936 | 1784 | |
| 937 | | const n_sect = @intCast(u8, sect_id + 1); |
| 938 | | var base_vaddr = header.addr; |
| 1785 | std.sort.sort(Section, sections.items, {}, SortSection.lessThan); |
| 939 | 1786 | |
| 940 | | log.debug("allocating local symbols in sect({d}, '{s},{s}')", .{ |
| 941 | | n_sect, |
| 942 | | header.segName(), |
| 943 | | header.sectName(), |
| 944 | | }); |
| 1787 | self.sections.shrinkRetainingCapacity(0); |
| 1788 | for (sections.items) |out| { |
| 1789 | self.sections.appendAssumeCapacity(out); |
| 1790 | } |
| 1791 | } |
| 945 | 1792 | |
| 946 | | while (true) { |
| 947 | | const alignment = try math.powi(u32, 2, atom.alignment); |
| 948 | | base_vaddr = mem.alignForwardGeneric(u64, base_vaddr, alignment); |
| 1793 | fn calcSectionSizes(self: *Zld, reverse_lookups: [][]u32) !void { |
| 1794 | const slice = self.sections.slice(); |
| 1795 | for (slice.items(.header)) |*header, sect_id| { |
| 1796 | if (header.size == 0) continue; |
| 1797 | if (self.requiresThunks()) { |
| 1798 | if (header.isCode() and !(header.@"type"() == macho.S_SYMBOL_STUBS) and !mem.eql(u8, header.sectName(), "__stub_helper")) continue; |
| 1799 | } |
| 949 | 1800 | |
| 950 | | const sym = atom.getSymbolPtr(macho_file); |
| 951 | | sym.n_value = base_vaddr; |
| 952 | | sym.n_sect = n_sect; |
| 1801 | var atom_index = slice.items(.first_atom_index)[sect_id]; |
| 1802 | header.size = 0; |
| 1803 | header.@"align" = 0; |
| 953 | 1804 | |
| 954 | | log.debug(" ATOM(%{d}, '{s}') @{x}", .{ atom.sym_index, atom.getName(macho_file), base_vaddr }); |
| 1805 | while (true) { |
| 1806 | const atom = self.getAtom(atom_index); |
| 1807 | const atom_alignment = try math.powi(u32, 2, atom.alignment); |
| 1808 | const atom_offset = mem.alignForwardGeneric(u64, header.size, atom_alignment); |
| 1809 | const padding = atom_offset - header.size; |
| 955 | 1810 | |
| 956 | | // Update each symbol contained within the atom |
| 957 | | for (atom.contained.items) |sym_at_off| { |
| 958 | | const contained_sym = macho_file.getSymbolPtr(.{ |
| 959 | | .sym_index = sym_at_off.sym_index, |
| 960 | | .file = atom.file, |
| 961 | | }); |
| 962 | | contained_sym.n_value = base_vaddr + sym_at_off.offset; |
| 963 | | contained_sym.n_sect = n_sect; |
| 964 | | } |
| 1811 | const sym = self.getSymbolPtr(atom.getSymbolWithLoc()); |
| 1812 | sym.n_value = atom_offset; |
| 965 | 1813 | |
| 966 | | base_vaddr += atom.size; |
| 1814 | header.size += padding + atom.size; |
| 1815 | header.@"align" = @max(header.@"align", atom.alignment); |
| 967 | 1816 | |
| 968 | | if (atom.next) |next| { |
| 969 | | atom = next; |
| 970 | | } else break; |
| 1817 | if (atom.next_index) |next_index| { |
| 1818 | atom_index = next_index; |
| 1819 | } else break; |
| 1820 | } |
| 971 | 1821 | } |
| 972 | | } |
| 973 | | } |
| 974 | 1822 | |
| 975 | | fn writeLinkeditSegmentData(macho_file: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 976 | | const seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 977 | | seg.filesize = 0; |
| 978 | | seg.vmsize = 0; |
| 1823 | if (self.requiresThunks()) { |
| 1824 | for (slice.items(.header)) |header, sect_id| { |
| 1825 | if (!header.isCode()) continue; |
| 1826 | if (header.@"type"() == macho.S_SYMBOL_STUBS) continue; |
| 1827 | if (mem.eql(u8, header.sectName(), "__stub_helper")) continue; |
| 979 | 1828 | |
| 980 | | try writeDyldInfoData(macho_file, ncmds, lc_writer); |
| 981 | | try writeFunctionStarts(macho_file, ncmds, lc_writer); |
| 982 | | try writeDataInCode(macho_file, ncmds, lc_writer); |
| 983 | | try writeSymtabs(macho_file, ncmds, lc_writer); |
| 1829 | // Create jump/branch range extenders if needed. |
| 1830 | try thunks.createThunks(self, @intCast(u8, sect_id), reverse_lookups); |
| 1831 | } |
| 1832 | } |
| 1833 | } |
| 984 | 1834 | |
| 985 | | seg.vmsize = mem.alignForwardGeneric(u64, seg.filesize, macho_file.page_size); |
| 986 | | } |
| 1835 | fn allocateSegments(self: *Zld) !void { |
| 1836 | for (self.segments.items) |*segment, segment_index| { |
| 1837 | const is_text_segment = mem.eql(u8, segment.segName(), "__TEXT"); |
| 1838 | const base_size = if (is_text_segment) try self.calcMinHeaderPad() else 0; |
| 1839 | try self.allocateSegment(@intCast(u8, segment_index), base_size); |
| 1840 | } |
| 1841 | } |
| 987 | 1842 | |
| 988 | | fn writeDyldInfoData(macho_file: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 989 | | const tracy = trace(@src()); |
| 990 | | defer tracy.end(); |
| 1843 | fn getSegmentAllocBase(self: Zld, segment_index: u8) struct { vmaddr: u64, fileoff: u64 } { |
| 1844 | if (segment_index > 0) { |
| 1845 | const prev_segment = self.segments.items[segment_index - 1]; |
| 1846 | return .{ |
| 1847 | .vmaddr = prev_segment.vmaddr + prev_segment.vmsize, |
| 1848 | .fileoff = prev_segment.fileoff + prev_segment.filesize, |
| 1849 | }; |
| 1850 | } |
| 1851 | return .{ .vmaddr = 0, .fileoff = 0 }; |
| 1852 | } |
| 991 | 1853 | |
| 992 | | const gpa = macho_file.base.allocator; |
| 1854 | fn allocateSegment(self: *Zld, segment_index: u8, init_size: u64) !void { |
| 1855 | const segment = &self.segments.items[segment_index]; |
| 993 | 1856 | |
| 994 | | var rebase_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 995 | | defer rebase_pointers.deinit(); |
| 996 | | var bind_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 997 | | defer bind_pointers.deinit(); |
| 998 | | var lazy_bind_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 999 | | defer lazy_bind_pointers.deinit(); |
| 1857 | if (mem.eql(u8, segment.segName(), "__PAGEZERO")) return; // allocated upon creation |
| 1000 | 1858 | |
| 1001 | | const slice = macho_file.sections.slice(); |
| 1002 | | for (slice.items(.last_atom)) |last_atom, sect_id| { |
| 1003 | | var atom = last_atom orelse continue; |
| 1004 | | const segment_index = slice.items(.segment_index)[sect_id]; |
| 1005 | | const header = slice.items(.header)[sect_id]; |
| 1859 | const base = self.getSegmentAllocBase(segment_index); |
| 1860 | segment.vmaddr = base.vmaddr; |
| 1861 | segment.fileoff = base.fileoff; |
| 1862 | segment.filesize = init_size; |
| 1863 | segment.vmsize = init_size; |
| 1006 | 1864 | |
| 1007 | | if (mem.eql(u8, header.segName(), "__TEXT")) continue; // __TEXT is non-writable |
| 1865 | // Allocate the sections according to their alignment at the beginning of the segment. |
| 1866 | const indexes = self.getSectionIndexes(segment_index); |
| 1867 | var start = init_size; |
| 1008 | 1868 | |
| 1009 | | log.debug("dyld info for {s},{s}", .{ header.segName(), header.sectName() }); |
| 1869 | const slice = self.sections.slice(); |
| 1870 | for (slice.items(.header)[indexes.start..indexes.end]) |*header, sect_id| { |
| 1871 | var atom_index = slice.items(.first_atom_index)[indexes.start + sect_id]; |
| 1010 | 1872 | |
| 1011 | | const seg = macho_file.segments.items[segment_index]; |
| 1873 | const alignment = try math.powi(u32, 2, header.@"align"); |
| 1874 | const start_aligned = mem.alignForwardGeneric(u64, start, alignment); |
| 1875 | const n_sect = @intCast(u8, indexes.start + sect_id + 1); |
| 1876 | |
| 1877 | header.offset = if (header.isZerofill()) |
| 1878 | 0 |
| 1879 | else |
| 1880 | @intCast(u32, segment.fileoff + start_aligned); |
| 1881 | header.addr = segment.vmaddr + start_aligned; |
| 1882 | |
| 1883 | log.debug("allocating local symbols in sect({d}, '{s},{s}')", .{ |
| 1884 | n_sect, |
| 1885 | header.segName(), |
| 1886 | header.sectName(), |
| 1887 | }); |
| 1012 | 1888 | |
| 1013 | | while (true) { |
| 1014 | | log.debug(" ATOM(%{d}, '{s}')", .{ atom.sym_index, atom.getName(macho_file) }); |
| 1015 | | const sym = atom.getSymbol(macho_file); |
| 1016 | | const base_offset = sym.n_value - seg.vmaddr; |
| 1889 | while (true) { |
| 1890 | const atom = self.getAtom(atom_index); |
| 1891 | const sym = self.getSymbolPtr(atom.getSymbolWithLoc()); |
| 1892 | sym.n_value += header.addr; |
| 1893 | sym.n_sect = n_sect; |
| 1017 | 1894 | |
| 1018 | | for (atom.rebases.items) |offset| { |
| 1019 | | log.debug(" | rebase at {x}", .{base_offset + offset}); |
| 1020 | | try rebase_pointers.append(.{ |
| 1021 | | .offset = base_offset + offset, |
| 1022 | | .segment_id = segment_index, |
| 1895 | log.debug(" ATOM(%{d}, '{s}') @{x}", .{ |
| 1896 | atom.sym_index, |
| 1897 | self.getSymbolName(atom.getSymbolWithLoc()), |
| 1898 | sym.n_value, |
| 1023 | 1899 | }); |
| 1024 | | } |
| 1025 | 1900 | |
| 1026 | | for (atom.bindings.items) |binding| { |
| 1027 | | const bind_sym = macho_file.getSymbol(binding.target); |
| 1028 | | const bind_sym_name = macho_file.getSymbolName(binding.target); |
| 1029 | | const dylib_ordinal = @divTrunc( |
| 1030 | | @bitCast(i16, bind_sym.n_desc), |
| 1031 | | macho.N_SYMBOL_RESOLVER, |
| 1032 | | ); |
| 1033 | | var flags: u4 = 0; |
| 1034 | | log.debug(" | bind at {x}, import('{s}') in dylib({d})", .{ |
| 1035 | | binding.offset + base_offset, |
| 1036 | | bind_sym_name, |
| 1037 | | dylib_ordinal, |
| 1038 | | }); |
| 1039 | | if (bind_sym.weakRef()) { |
| 1040 | | log.debug(" | marking as weak ref ", .{}); |
| 1041 | | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 1042 | | } |
| 1043 | | try bind_pointers.append(.{ |
| 1044 | | .offset = binding.offset + base_offset, |
| 1045 | | .segment_id = segment_index, |
| 1046 | | .dylib_ordinal = dylib_ordinal, |
| 1047 | | .name = bind_sym_name, |
| 1048 | | .bind_flags = flags, |
| 1049 | | }); |
| 1050 | | } |
| 1901 | if (atom.getFile()) |_| { |
| 1902 | // Update each symbol contained within the atom |
| 1903 | var it = Atom.getInnerSymbolsIterator(self, atom_index); |
| 1904 | while (it.next()) |sym_loc| { |
| 1905 | const inner_sym = self.getSymbolPtr(sym_loc); |
| 1906 | inner_sym.n_value = sym.n_value + Atom.calcInnerSymbolOffset( |
| 1907 | self, |
| 1908 | atom_index, |
| 1909 | sym_loc.sym_index, |
| 1910 | ); |
| 1911 | inner_sym.n_sect = n_sect; |
| 1912 | } |
| 1051 | 1913 | |
| 1052 | | for (atom.lazy_bindings.items) |binding| { |
| 1053 | | const bind_sym = macho_file.getSymbol(binding.target); |
| 1054 | | const bind_sym_name = macho_file.getSymbolName(binding.target); |
| 1055 | | const dylib_ordinal = @divTrunc( |
| 1056 | | @bitCast(i16, bind_sym.n_desc), |
| 1057 | | macho.N_SYMBOL_RESOLVER, |
| 1058 | | ); |
| 1059 | | var flags: u4 = 0; |
| 1060 | | log.debug(" | lazy bind at {x} import('{s}') ord({d})", .{ |
| 1061 | | binding.offset + base_offset, |
| 1062 | | bind_sym_name, |
| 1063 | | dylib_ordinal, |
| 1064 | | }); |
| 1065 | | if (bind_sym.weakRef()) { |
| 1066 | | log.debug(" | marking as weak ref ", .{}); |
| 1067 | | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 1914 | // If there is a section alias, update it now too |
| 1915 | if (Atom.getSectionAlias(self, atom_index)) |sym_loc| { |
| 1916 | const alias = self.getSymbolPtr(sym_loc); |
| 1917 | alias.n_value = sym.n_value; |
| 1918 | alias.n_sect = n_sect; |
| 1919 | } |
| 1068 | 1920 | } |
| 1069 | | try lazy_bind_pointers.append(.{ |
| 1070 | | .offset = binding.offset + base_offset, |
| 1071 | | .segment_id = segment_index, |
| 1072 | | .dylib_ordinal = dylib_ordinal, |
| 1073 | | .name = bind_sym_name, |
| 1074 | | .bind_flags = flags, |
| 1075 | | }); |
| 1921 | |
| 1922 | if (atom.next_index) |next_index| { |
| 1923 | atom_index = next_index; |
| 1924 | } else break; |
| 1076 | 1925 | } |
| 1077 | 1926 | |
| 1078 | | if (atom.prev) |prev| { |
| 1079 | | atom = prev; |
| 1080 | | } else break; |
| 1927 | start = start_aligned + header.size; |
| 1928 | |
| 1929 | if (!header.isZerofill()) { |
| 1930 | segment.filesize = start; |
| 1931 | } |
| 1932 | segment.vmsize = start; |
| 1081 | 1933 | } |
| 1934 | |
| 1935 | segment.filesize = mem.alignForwardGeneric(u64, segment.filesize, self.page_size); |
| 1936 | segment.vmsize = mem.alignForwardGeneric(u64, segment.vmsize, self.page_size); |
| 1082 | 1937 | } |
| 1083 | 1938 | |
| 1084 | | var trie: Trie = .{}; |
| 1085 | | defer trie.deinit(gpa); |
| 1939 | const InitSectionOpts = struct { |
| 1940 | flags: u32 = macho.S_REGULAR, |
| 1941 | reserved1: u32 = 0, |
| 1942 | reserved2: u32 = 0, |
| 1943 | }; |
| 1086 | 1944 | |
| 1087 | | { |
| 1088 | | // TODO handle macho.EXPORT_SYMBOL_FLAGS_REEXPORT and macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER. |
| 1089 | | log.debug("generating export trie", .{}); |
| 1945 | fn initSection( |
| 1946 | self: *Zld, |
| 1947 | segname: []const u8, |
| 1948 | sectname: []const u8, |
| 1949 | opts: InitSectionOpts, |
| 1950 | ) !u8 { |
| 1951 | const gpa = self.gpa; |
| 1952 | log.debug("creating section '{s},{s}'", .{ segname, sectname }); |
| 1953 | const index = @intCast(u8, self.sections.slice().len); |
| 1954 | try self.sections.append(gpa, .{ |
| 1955 | .segment_index = undefined, |
| 1956 | .header = .{ |
| 1957 | .sectname = makeStaticString(sectname), |
| 1958 | .segname = makeStaticString(segname), |
| 1959 | .flags = opts.flags, |
| 1960 | .reserved1 = opts.reserved1, |
| 1961 | .reserved2 = opts.reserved2, |
| 1962 | }, |
| 1963 | .first_atom_index = undefined, |
| 1964 | .last_atom_index = undefined, |
| 1965 | }); |
| 1966 | return index; |
| 1967 | } |
| 1090 | 1968 | |
| 1091 | | const text_segment = macho_file.segments.items[macho_file.text_segment_cmd_index.?]; |
| 1092 | | const base_address = text_segment.vmaddr; |
| 1969 | inline fn getSegmentPrecedence(segname: []const u8) u4 { |
| 1970 | if (mem.eql(u8, segname, "__PAGEZERO")) return 0x0; |
| 1971 | if (mem.eql(u8, segname, "__TEXT")) return 0x1; |
| 1972 | if (mem.eql(u8, segname, "__DATA_CONST")) return 0x2; |
| 1973 | if (mem.eql(u8, segname, "__DATA")) return 0x3; |
| 1974 | if (mem.eql(u8, segname, "__LINKEDIT")) return 0x5; |
| 1975 | return 0x4; |
| 1976 | } |
| 1093 | 1977 | |
| 1094 | | if (macho_file.base.options.output_mode == .Exe) { |
| 1095 | | for (&[_]SymbolWithLoc{ |
| 1096 | | try macho_file.getEntryPoint(), |
| 1097 | | macho_file.getGlobal("__mh_execute_header").?, |
| 1098 | | }) |global| { |
| 1099 | | const sym = macho_file.getSymbol(global); |
| 1100 | | const sym_name = macho_file.getSymbolName(global); |
| 1101 | | log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value }); |
| 1102 | | try trie.put(gpa, .{ |
| 1103 | | .name = sym_name, |
| 1104 | | .vmaddr_offset = sym.n_value - base_address, |
| 1105 | | .export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR, |
| 1106 | | }); |
| 1978 | inline fn getSegmentMemoryProtection(segname: []const u8) macho.vm_prot_t { |
| 1979 | if (mem.eql(u8, segname, "__PAGEZERO")) return macho.PROT.NONE; |
| 1980 | if (mem.eql(u8, segname, "__TEXT")) return macho.PROT.READ | macho.PROT.EXEC; |
| 1981 | if (mem.eql(u8, segname, "__LINKEDIT")) return macho.PROT.READ; |
| 1982 | return macho.PROT.READ | macho.PROT.WRITE; |
| 1983 | } |
| 1984 | |
| 1985 | inline fn getSectionPrecedence(header: macho.section_64) u8 { |
| 1986 | const segment_precedence: u4 = getSegmentPrecedence(header.segName()); |
| 1987 | const section_precedence: u4 = blk: { |
| 1988 | if (header.isCode()) { |
| 1989 | if (mem.eql(u8, "__text", header.sectName())) break :blk 0x0; |
| 1990 | if (header.@"type"() == macho.S_SYMBOL_STUBS) break :blk 0x1; |
| 1991 | break :blk 0x2; |
| 1107 | 1992 | } |
| 1108 | | } else { |
| 1109 | | assert(macho_file.base.options.output_mode == .Lib); |
| 1110 | | for (macho_file.globals.items) |global| { |
| 1111 | | const sym = macho_file.getSymbol(global); |
| 1993 | switch (header.@"type"()) { |
| 1994 | macho.S_NON_LAZY_SYMBOL_POINTERS, |
| 1995 | macho.S_LAZY_SYMBOL_POINTERS, |
| 1996 | => break :blk 0x0, |
| 1997 | macho.S_MOD_INIT_FUNC_POINTERS => break :blk 0x1, |
| 1998 | macho.S_MOD_TERM_FUNC_POINTERS => break :blk 0x2, |
| 1999 | macho.S_ZEROFILL => break :blk 0xf, |
| 2000 | macho.S_THREAD_LOCAL_REGULAR => break :blk 0xd, |
| 2001 | macho.S_THREAD_LOCAL_ZEROFILL => break :blk 0xe, |
| 2002 | else => if (mem.eql(u8, "__eh_frame", header.sectName())) |
| 2003 | break :blk 0xf |
| 2004 | else |
| 2005 | break :blk 0x3, |
| 2006 | } |
| 2007 | }; |
| 2008 | return (@intCast(u8, segment_precedence) << 4) + section_precedence; |
| 2009 | } |
| 1112 | 2010 | |
| 1113 | | if (sym.undf()) continue; |
| 1114 | | if (!sym.ext()) continue; |
| 1115 | | if (sym.n_desc == MachO.N_DESC_GCED) continue; |
| 2011 | fn writeSegmentHeaders(self: *Zld, ncmds: *u32, writer: anytype) !void { |
| 2012 | for (self.segments.items) |seg, i| { |
| 2013 | const indexes = self.getSectionIndexes(@intCast(u8, i)); |
| 2014 | var out_seg = seg; |
| 2015 | out_seg.cmdsize = @sizeOf(macho.segment_command_64); |
| 2016 | out_seg.nsects = 0; |
| 2017 | |
| 2018 | // Update section headers count; any section with size of 0 is excluded |
| 2019 | // since it doesn't have any data in the final binary file. |
| 2020 | for (self.sections.items(.header)[indexes.start..indexes.end]) |header| { |
| 2021 | if (header.size == 0) continue; |
| 2022 | out_seg.cmdsize += @sizeOf(macho.section_64); |
| 2023 | out_seg.nsects += 1; |
| 2024 | } |
| 1116 | 2025 | |
| 1117 | | const sym_name = macho_file.getSymbolName(global); |
| 1118 | | log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value }); |
| 1119 | | try trie.put(gpa, .{ |
| 1120 | | .name = sym_name, |
| 1121 | | .vmaddr_offset = sym.n_value - base_address, |
| 1122 | | .export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR, |
| 1123 | | }); |
| 2026 | if (out_seg.nsects == 0 and |
| 2027 | (mem.eql(u8, out_seg.segName(), "__DATA_CONST") or |
| 2028 | mem.eql(u8, out_seg.segName(), "__DATA"))) continue; |
| 2029 | |
| 2030 | try writer.writeStruct(out_seg); |
| 2031 | for (self.sections.items(.header)[indexes.start..indexes.end]) |header| { |
| 2032 | if (header.size == 0) continue; |
| 2033 | try writer.writeStruct(header); |
| 1124 | 2034 | } |
| 1125 | | } |
| 1126 | 2035 | |
| 1127 | | try trie.finalize(gpa); |
| 2036 | ncmds.* += 1; |
| 2037 | } |
| 1128 | 2038 | } |
| 1129 | 2039 | |
| 1130 | | const link_seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 1131 | | const rebase_off = mem.alignForwardGeneric(u64, link_seg.fileoff, @alignOf(u64)); |
| 1132 | | assert(rebase_off == link_seg.fileoff); |
| 1133 | | const rebase_size = try bind.rebaseInfoSize(rebase_pointers.items); |
| 1134 | | log.debug("writing rebase info from 0x{x} to 0x{x}", .{ rebase_off, rebase_off + rebase_size }); |
| 1135 | | |
| 1136 | | const bind_off = mem.alignForwardGeneric(u64, rebase_off + rebase_size, @alignOf(u64)); |
| 1137 | | const bind_size = try bind.bindInfoSize(bind_pointers.items); |
| 1138 | | log.debug("writing bind info from 0x{x} to 0x{x}", .{ bind_off, bind_off + bind_size }); |
| 1139 | | |
| 1140 | | const lazy_bind_off = mem.alignForwardGeneric(u64, bind_off + bind_size, @alignOf(u64)); |
| 1141 | | const lazy_bind_size = try bind.lazyBindInfoSize(lazy_bind_pointers.items); |
| 1142 | | log.debug("writing lazy bind info from 0x{x} to 0x{x}", .{ lazy_bind_off, lazy_bind_off + lazy_bind_size }); |
| 1143 | | |
| 1144 | | const export_off = mem.alignForwardGeneric(u64, lazy_bind_off + lazy_bind_size, @alignOf(u64)); |
| 1145 | | const export_size = trie.size; |
| 1146 | | log.debug("writing export trie from 0x{x} to 0x{x}", .{ export_off, export_off + export_size }); |
| 1147 | | |
| 1148 | | const needed_size = export_off + export_size - rebase_off; |
| 1149 | | link_seg.filesize = needed_size; |
| 1150 | | |
| 1151 | | var buffer = try gpa.alloc(u8, math.cast(usize, needed_size) orelse return error.Overflow); |
| 1152 | | defer gpa.free(buffer); |
| 1153 | | mem.set(u8, buffer, 0); |
| 1154 | | |
| 1155 | | var stream = std.io.fixedBufferStream(buffer); |
| 1156 | | const writer = stream.writer(); |
| 1157 | | |
| 1158 | | try bind.writeRebaseInfo(rebase_pointers.items, writer); |
| 1159 | | try stream.seekTo(bind_off - rebase_off); |
| 1160 | | |
| 1161 | | try bind.writeBindInfo(bind_pointers.items, writer); |
| 1162 | | try stream.seekTo(lazy_bind_off - rebase_off); |
| 1163 | | |
| 1164 | | try bind.writeLazyBindInfo(lazy_bind_pointers.items, writer); |
| 1165 | | try stream.seekTo(export_off - rebase_off); |
| 1166 | | |
| 1167 | | _ = try trie.write(writer); |
| 1168 | | |
| 1169 | | log.debug("writing dyld info from 0x{x} to 0x{x}", .{ |
| 1170 | | rebase_off, |
| 1171 | | rebase_off + needed_size, |
| 1172 | | }); |
| 1173 | | |
| 1174 | | try macho_file.base.file.?.pwriteAll(buffer, rebase_off); |
| 1175 | | const start = math.cast(usize, lazy_bind_off - rebase_off) orelse return error.Overflow; |
| 1176 | | const end = start + (math.cast(usize, lazy_bind_size) orelse return error.Overflow); |
| 1177 | | try populateLazyBindOffsetsInStubHelper(macho_file, buffer[start..end]); |
| 1178 | | |
| 1179 | | try lc_writer.writeStruct(macho.dyld_info_command{ |
| 1180 | | .cmd = .DYLD_INFO_ONLY, |
| 1181 | | .cmdsize = @sizeOf(macho.dyld_info_command), |
| 1182 | | .rebase_off = @intCast(u32, rebase_off), |
| 1183 | | .rebase_size = @intCast(u32, rebase_size), |
| 1184 | | .bind_off = @intCast(u32, bind_off), |
| 1185 | | .bind_size = @intCast(u32, bind_size), |
| 1186 | | .weak_bind_off = 0, |
| 1187 | | .weak_bind_size = 0, |
| 1188 | | .lazy_bind_off = @intCast(u32, lazy_bind_off), |
| 1189 | | .lazy_bind_size = @intCast(u32, lazy_bind_size), |
| 1190 | | .export_off = @intCast(u32, export_off), |
| 1191 | | .export_size = @intCast(u32, export_size), |
| 1192 | | }); |
| 1193 | | ncmds.* += 1; |
| 1194 | | } |
| 2040 | fn writeLinkeditSegmentData(self: *Zld, ncmds: *u32, lc_writer: anytype, reverse_lookups: [][]u32) !void { |
| 2041 | try self.writeDyldInfoData(ncmds, lc_writer, reverse_lookups); |
| 2042 | try self.writeFunctionStarts(ncmds, lc_writer); |
| 2043 | try self.writeDataInCode(ncmds, lc_writer); |
| 2044 | try self.writeSymtabs(ncmds, lc_writer); |
| 1195 | 2045 | |
| 1196 | | fn populateLazyBindOffsetsInStubHelper(macho_file: *MachO, buffer: []const u8) !void { |
| 1197 | | const gpa = macho_file.base.allocator; |
| 2046 | const seg = self.getLinkeditSegmentPtr(); |
| 2047 | seg.vmsize = mem.alignForwardGeneric(u64, seg.filesize, self.page_size); |
| 2048 | } |
| 1198 | 2049 | |
| 1199 | | const stub_helper_section_index = macho_file.stub_helper_section_index orelse return; |
| 1200 | | if (macho_file.stub_helper_preamble_atom == null) return; |
| 2050 | fn collectRebaseDataFromContainer( |
| 2051 | self: *Zld, |
| 2052 | sect_id: u8, |
| 2053 | pointers: *std.ArrayList(bind.Pointer), |
| 2054 | container: anytype, |
| 2055 | ) !void { |
| 2056 | const slice = self.sections.slice(); |
| 2057 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 2058 | const seg = self.getSegment(sect_id); |
| 1201 | 2059 | |
| 1202 | | const section = macho_file.sections.get(stub_helper_section_index); |
| 1203 | | const last_atom = section.last_atom orelse return; |
| 1204 | | if (last_atom == macho_file.stub_helper_preamble_atom.?) return; // TODO is this a redundant check? |
| 2060 | try pointers.ensureUnusedCapacity(container.items.len); |
| 1205 | 2061 | |
| 1206 | | var table = std.AutoHashMap(i64, *Atom).init(gpa); |
| 1207 | | defer table.deinit(); |
| 2062 | for (container.items) |entry| { |
| 2063 | const target_sym = entry.getTargetSymbol(self); |
| 2064 | if (target_sym.undf()) continue; |
| 1208 | 2065 | |
| 1209 | | { |
| 1210 | | var stub_atom = last_atom; |
| 1211 | | var laptr_atom = macho_file.sections.items(.last_atom)[macho_file.la_symbol_ptr_section_index.?].?; |
| 1212 | | const base_addr = blk: { |
| 1213 | | const seg = macho_file.segments.items[macho_file.data_segment_cmd_index.?]; |
| 1214 | | break :blk seg.vmaddr; |
| 1215 | | }; |
| 2066 | const atom_sym = entry.getAtomSymbol(self); |
| 2067 | const base_offset = atom_sym.n_value - seg.vmaddr; |
| 1216 | 2068 | |
| 1217 | | while (true) { |
| 1218 | | const laptr_off = blk: { |
| 1219 | | const sym = laptr_atom.getSymbol(macho_file); |
| 1220 | | break :blk @intCast(i64, sym.n_value - base_addr); |
| 1221 | | }; |
| 1222 | | try table.putNoClobber(laptr_off, stub_atom); |
| 1223 | | if (laptr_atom.prev) |prev| { |
| 1224 | | laptr_atom = prev; |
| 1225 | | stub_atom = stub_atom.prev.?; |
| 1226 | | } else break; |
| 2069 | log.debug(" | rebase at {x}", .{base_offset}); |
| 2070 | |
| 2071 | pointers.appendAssumeCapacity(.{ |
| 2072 | .offset = base_offset, |
| 2073 | .segment_id = segment_index, |
| 2074 | }); |
| 1227 | 2075 | } |
| 1228 | 2076 | } |
| 1229 | 2077 | |
| 1230 | | var stream = std.io.fixedBufferStream(buffer); |
| 1231 | | var reader = stream.reader(); |
| 1232 | | var offsets = std.ArrayList(struct { sym_offset: i64, offset: u32 }).init(gpa); |
| 1233 | | try offsets.append(.{ .sym_offset = undefined, .offset = 0 }); |
| 1234 | | defer offsets.deinit(); |
| 1235 | | var valid_block = false; |
| 2078 | fn collectRebaseData(self: *Zld, pointers: *std.ArrayList(bind.Pointer)) !void { |
| 2079 | log.debug("collecting rebase data", .{}); |
| 1236 | 2080 | |
| 1237 | | while (true) { |
| 1238 | | const inst = reader.readByte() catch |err| switch (err) { |
| 1239 | | error.EndOfStream => break, |
| 1240 | | }; |
| 1241 | | const opcode: u8 = inst & macho.BIND_OPCODE_MASK; |
| 2081 | // First, unpack GOT entries |
| 2082 | if (self.getSectionByName("__DATA_CONST", "__got")) |sect_id| { |
| 2083 | try self.collectRebaseDataFromContainer(sect_id, pointers, self.got_entries); |
| 2084 | } |
| 1242 | 2085 | |
| 1243 | | switch (opcode) { |
| 1244 | | macho.BIND_OPCODE_DO_BIND => { |
| 1245 | | valid_block = true; |
| 1246 | | }, |
| 1247 | | macho.BIND_OPCODE_DONE => { |
| 1248 | | if (valid_block) { |
| 1249 | | const offset = try stream.getPos(); |
| 1250 | | try offsets.append(.{ .sym_offset = undefined, .offset = @intCast(u32, offset) }); |
| 1251 | | } |
| 1252 | | valid_block = false; |
| 1253 | | }, |
| 1254 | | macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => { |
| 1255 | | var next = try reader.readByte(); |
| 1256 | | while (next != @as(u8, 0)) { |
| 1257 | | next = try reader.readByte(); |
| 1258 | | } |
| 1259 | | }, |
| 1260 | | macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => { |
| 1261 | | var inserted = offsets.pop(); |
| 1262 | | inserted.sym_offset = try std.leb.readILEB128(i64, reader); |
| 1263 | | try offsets.append(inserted); |
| 1264 | | }, |
| 1265 | | macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => { |
| 1266 | | _ = try std.leb.readULEB128(u64, reader); |
| 1267 | | }, |
| 1268 | | macho.BIND_OPCODE_SET_ADDEND_SLEB => { |
| 1269 | | _ = try std.leb.readILEB128(i64, reader); |
| 1270 | | }, |
| 1271 | | else => {}, |
| 2086 | const slice = self.sections.slice(); |
| 2087 | |
| 2088 | // Next, unpact lazy pointers |
| 2089 | // TODO: save la_ptr in a container so that we can re-use the helper |
| 2090 | if (self.getSectionByName("__DATA", "__la_symbol_ptr")) |sect_id| { |
| 2091 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 2092 | const seg = self.getSegment(sect_id); |
| 2093 | var atom_index = slice.items(.first_atom_index)[sect_id]; |
| 2094 | |
| 2095 | try pointers.ensureUnusedCapacity(self.stubs.items.len); |
| 2096 | |
| 2097 | while (true) { |
| 2098 | const atom = self.getAtom(atom_index); |
| 2099 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 2100 | const base_offset = sym.n_value - seg.vmaddr; |
| 2101 | |
| 2102 | log.debug(" | rebase at {x}", .{base_offset}); |
| 2103 | |
| 2104 | pointers.appendAssumeCapacity(.{ |
| 2105 | .offset = base_offset, |
| 2106 | .segment_id = segment_index, |
| 2107 | }); |
| 2108 | |
| 2109 | if (atom.next_index) |next_index| { |
| 2110 | atom_index = next_index; |
| 2111 | } else break; |
| 2112 | } |
| 2113 | } |
| 2114 | |
| 2115 | // Finally, unpack the rest. |
| 2116 | for (slice.items(.header)) |header, sect_id| { |
| 2117 | switch (header.@"type"()) { |
| 2118 | macho.S_LITERAL_POINTERS, |
| 2119 | macho.S_REGULAR, |
| 2120 | macho.S_MOD_INIT_FUNC_POINTERS, |
| 2121 | macho.S_MOD_TERM_FUNC_POINTERS, |
| 2122 | => {}, |
| 2123 | else => continue, |
| 2124 | } |
| 2125 | |
| 2126 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 2127 | const segment = self.getSegment(@intCast(u8, sect_id)); |
| 2128 | if (segment.maxprot & macho.PROT.WRITE == 0) continue; |
| 2129 | |
| 2130 | const cpu_arch = self.options.target.cpu.arch; |
| 2131 | var atom_index = slice.items(.first_atom_index)[sect_id]; |
| 2132 | |
| 2133 | while (true) { |
| 2134 | const atom = self.getAtom(atom_index); |
| 2135 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 2136 | |
| 2137 | const should_rebase = blk: { |
| 2138 | if (self.dyld_private_sym_index) |sym_index| { |
| 2139 | if (atom.sym_index == sym_index) break :blk false; |
| 2140 | } |
| 2141 | break :blk !sym.undf(); |
| 2142 | }; |
| 2143 | |
| 2144 | if (should_rebase) { |
| 2145 | log.debug(" ATOM(%{d}, '{s}')", .{ atom.sym_index, self.getSymbolName(atom.getSymbolWithLoc()) }); |
| 2146 | |
| 2147 | const object = self.objects.items[atom.getFile().?]; |
| 2148 | const source_sym = object.getSourceSymbol(atom.sym_index).?; |
| 2149 | const source_sect = object.getSourceSection(source_sym.n_sect - 1); |
| 2150 | const relocs = Atom.getAtomRelocs(self, atom_index); |
| 2151 | |
| 2152 | for (relocs) |rel| { |
| 2153 | switch (cpu_arch) { |
| 2154 | .aarch64 => { |
| 2155 | const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); |
| 2156 | if (rel_type != .ARM64_RELOC_UNSIGNED) continue; |
| 2157 | if (rel.r_length != 3) continue; |
| 2158 | }, |
| 2159 | .x86_64 => { |
| 2160 | const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); |
| 2161 | if (rel_type != .X86_64_RELOC_UNSIGNED) continue; |
| 2162 | if (rel.r_length != 3) continue; |
| 2163 | }, |
| 2164 | else => unreachable, |
| 2165 | } |
| 2166 | |
| 2167 | const base_offset = @intCast(i32, sym.n_value - segment.vmaddr); |
| 2168 | const rel_offset = rel.r_address - @intCast(i32, source_sym.n_value - source_sect.addr); |
| 2169 | const offset = @intCast(u64, base_offset + rel_offset); |
| 2170 | log.debug(" | rebase at {x}", .{offset}); |
| 2171 | |
| 2172 | try pointers.append(.{ |
| 2173 | .offset = offset, |
| 2174 | .segment_id = segment_index, |
| 2175 | }); |
| 2176 | } |
| 2177 | } |
| 2178 | |
| 2179 | if (atom.next_index) |next_index| { |
| 2180 | atom_index = next_index; |
| 2181 | } else break; |
| 2182 | } |
| 1272 | 2183 | } |
| 1273 | 2184 | } |
| 1274 | 2185 | |
| 1275 | | const header = macho_file.sections.items(.header)[stub_helper_section_index]; |
| 1276 | | const stub_offset: u4 = switch (macho_file.base.options.target.cpu.arch) { |
| 1277 | | .x86_64 => 1, |
| 1278 | | .aarch64 => 2 * @sizeOf(u32), |
| 1279 | | else => unreachable, |
| 1280 | | }; |
| 1281 | | var buf: [@sizeOf(u32)]u8 = undefined; |
| 1282 | | _ = offsets.pop(); |
| 1283 | | |
| 1284 | | while (offsets.popOrNull()) |bind_offset| { |
| 1285 | | const atom = table.get(bind_offset.sym_offset).?; |
| 1286 | | const sym = atom.getSymbol(macho_file); |
| 1287 | | const file_offset = header.offset + sym.n_value - header.addr + stub_offset; |
| 1288 | | mem.writeIntLittle(u32, &buf, bind_offset.offset); |
| 1289 | | log.debug("writing lazy bind offset in stub helper of 0x{x} for symbol {s} at offset 0x{x}", .{ |
| 1290 | | bind_offset.offset, |
| 1291 | | atom.getName(macho_file), |
| 1292 | | file_offset, |
| 2186 | fn collectBindDataFromContainer( |
| 2187 | self: *Zld, |
| 2188 | sect_id: u8, |
| 2189 | pointers: *std.ArrayList(bind.Pointer), |
| 2190 | container: anytype, |
| 2191 | ) !void { |
| 2192 | const slice = self.sections.slice(); |
| 2193 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 2194 | const seg = self.getSegment(sect_id); |
| 2195 | |
| 2196 | try pointers.ensureUnusedCapacity(container.items.len); |
| 2197 | |
| 2198 | for (container.items) |entry| { |
| 2199 | const bind_sym_name = entry.getTargetSymbolName(self); |
| 2200 | const bind_sym = entry.getTargetSymbol(self); |
| 2201 | if (bind_sym.sect()) continue; |
| 2202 | |
| 2203 | const sym = entry.getAtomSymbol(self); |
| 2204 | const base_offset = sym.n_value - seg.vmaddr; |
| 2205 | |
| 2206 | const dylib_ordinal = @divTrunc(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER); |
| 2207 | var flags: u4 = 0; |
| 2208 | log.debug(" | bind at {x}, import('{s}') in dylib({d})", .{ |
| 2209 | base_offset, |
| 2210 | bind_sym_name, |
| 2211 | dylib_ordinal, |
| 2212 | }); |
| 2213 | if (bind_sym.weakRef()) { |
| 2214 | log.debug(" | marking as weak ref ", .{}); |
| 2215 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 2216 | } |
| 2217 | pointers.appendAssumeCapacity(.{ |
| 2218 | .offset = base_offset, |
| 2219 | .segment_id = segment_index, |
| 2220 | .dylib_ordinal = dylib_ordinal, |
| 2221 | .name = bind_sym_name, |
| 2222 | .bind_flags = flags, |
| 2223 | }); |
| 2224 | } |
| 2225 | } |
| 2226 | |
| 2227 | fn collectBindData(self: *Zld, pointers: *std.ArrayList(bind.Pointer), reverse_lookups: [][]u32) !void { |
| 2228 | log.debug("collecting bind data", .{}); |
| 2229 | |
| 2230 | // First, unpack GOT section |
| 2231 | if (self.getSectionByName("__DATA_CONST", "__got")) |sect_id| { |
| 2232 | try self.collectBindDataFromContainer(sect_id, pointers, self.got_entries); |
| 2233 | } |
| 2234 | |
| 2235 | // Next, unpack TLV pointers section |
| 2236 | if (self.getSectionByName("__DATA", "__thread_ptrs")) |sect_id| { |
| 2237 | try self.collectBindDataFromContainer(sect_id, pointers, self.tlv_ptr_entries); |
| 2238 | } |
| 2239 | |
| 2240 | // Finally, unpack the rest. |
| 2241 | const slice = self.sections.slice(); |
| 2242 | for (slice.items(.header)) |header, sect_id| { |
| 2243 | switch (header.@"type"()) { |
| 2244 | macho.S_LITERAL_POINTERS, |
| 2245 | macho.S_REGULAR, |
| 2246 | macho.S_MOD_INIT_FUNC_POINTERS, |
| 2247 | macho.S_MOD_TERM_FUNC_POINTERS, |
| 2248 | => {}, |
| 2249 | else => continue, |
| 2250 | } |
| 2251 | |
| 2252 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 2253 | const segment = self.getSegment(@intCast(u8, sect_id)); |
| 2254 | if (segment.maxprot & macho.PROT.WRITE == 0) continue; |
| 2255 | |
| 2256 | const cpu_arch = self.options.target.cpu.arch; |
| 2257 | var atom_index = slice.items(.first_atom_index)[sect_id]; |
| 2258 | |
| 2259 | while (true) { |
| 2260 | const atom = self.getAtom(atom_index); |
| 2261 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 2262 | |
| 2263 | log.debug(" ATOM(%{d}, '{s}')", .{ atom.sym_index, self.getSymbolName(atom.getSymbolWithLoc()) }); |
| 2264 | |
| 2265 | const should_bind = blk: { |
| 2266 | if (self.dyld_private_sym_index) |sym_index| { |
| 2267 | if (atom.sym_index == sym_index) break :blk false; |
| 2268 | } |
| 2269 | break :blk true; |
| 2270 | }; |
| 2271 | |
| 2272 | if (should_bind) { |
| 2273 | const object = self.objects.items[atom.getFile().?]; |
| 2274 | const source_sym = object.getSourceSymbol(atom.sym_index).?; |
| 2275 | const source_sect = object.getSourceSection(source_sym.n_sect - 1); |
| 2276 | const relocs = Atom.getAtomRelocs(self, atom_index); |
| 2277 | |
| 2278 | for (relocs) |rel| { |
| 2279 | switch (cpu_arch) { |
| 2280 | .aarch64 => { |
| 2281 | const rel_type = @intToEnum(macho.reloc_type_arm64, rel.r_type); |
| 2282 | if (rel_type != .ARM64_RELOC_UNSIGNED) continue; |
| 2283 | if (rel.r_length != 3) continue; |
| 2284 | }, |
| 2285 | .x86_64 => { |
| 2286 | const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); |
| 2287 | if (rel_type != .X86_64_RELOC_UNSIGNED) continue; |
| 2288 | if (rel.r_length != 3) continue; |
| 2289 | }, |
| 2290 | else => unreachable, |
| 2291 | } |
| 2292 | |
| 2293 | const global = try Atom.parseRelocTarget(self, atom_index, rel, reverse_lookups[atom.getFile().?]); |
| 2294 | const bind_sym_name = self.getSymbolName(global); |
| 2295 | const bind_sym = self.getSymbol(global); |
| 2296 | if (!bind_sym.undf()) continue; |
| 2297 | |
| 2298 | const base_offset = @intCast(i32, sym.n_value - segment.vmaddr); |
| 2299 | const rel_offset = rel.r_address - @intCast(i32, source_sym.n_value - source_sect.addr); |
| 2300 | const offset = @intCast(u64, base_offset + rel_offset); |
| 2301 | |
| 2302 | const dylib_ordinal = @divTrunc(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER); |
| 2303 | var flags: u4 = 0; |
| 2304 | log.debug(" | bind at {x}, import('{s}') in dylib({d})", .{ |
| 2305 | base_offset, |
| 2306 | bind_sym_name, |
| 2307 | dylib_ordinal, |
| 2308 | }); |
| 2309 | if (bind_sym.weakRef()) { |
| 2310 | log.debug(" | marking as weak ref ", .{}); |
| 2311 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 2312 | } |
| 2313 | try pointers.append(.{ |
| 2314 | .offset = offset, |
| 2315 | .segment_id = segment_index, |
| 2316 | .dylib_ordinal = dylib_ordinal, |
| 2317 | .name = bind_sym_name, |
| 2318 | .bind_flags = flags, |
| 2319 | }); |
| 2320 | } |
| 2321 | } |
| 2322 | if (atom.next_index) |next_index| { |
| 2323 | atom_index = next_index; |
| 2324 | } else break; |
| 2325 | } |
| 2326 | } |
| 2327 | } |
| 2328 | |
| 2329 | fn collectLazyBindData(self: *Zld, pointers: *std.ArrayList(bind.Pointer)) !void { |
| 2330 | const sect_id = self.getSectionByName("__DATA", "__la_symbol_ptr") orelse return; |
| 2331 | |
| 2332 | log.debug("collecting lazy bind data", .{}); |
| 2333 | |
| 2334 | const slice = self.sections.slice(); |
| 2335 | const segment_index = slice.items(.segment_index)[sect_id]; |
| 2336 | const seg = self.getSegment(sect_id); |
| 2337 | var atom_index = slice.items(.first_atom_index)[sect_id]; |
| 2338 | |
| 2339 | // TODO: we actually don't need to store lazy pointer atoms as they are synthetically generated by the linker |
| 2340 | try pointers.ensureUnusedCapacity(self.stubs.items.len); |
| 2341 | |
| 2342 | var count: u32 = 0; |
| 2343 | while (true) : (count += 1) { |
| 2344 | const atom = self.getAtom(atom_index); |
| 2345 | |
| 2346 | log.debug(" ATOM(%{d}, '{s}')", .{ atom.sym_index, self.getSymbolName(atom.getSymbolWithLoc()) }); |
| 2347 | |
| 2348 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 2349 | const base_offset = sym.n_value - seg.vmaddr; |
| 2350 | |
| 2351 | const stub_entry = self.stubs.items[count]; |
| 2352 | const bind_sym = stub_entry.getTargetSymbol(self); |
| 2353 | const bind_sym_name = stub_entry.getTargetSymbolName(self); |
| 2354 | const dylib_ordinal = @divTrunc(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER); |
| 2355 | var flags: u4 = 0; |
| 2356 | log.debug(" | lazy bind at {x}, import('{s}') in dylib({d})", .{ |
| 2357 | base_offset, |
| 2358 | bind_sym_name, |
| 2359 | dylib_ordinal, |
| 2360 | }); |
| 2361 | if (bind_sym.weakRef()) { |
| 2362 | log.debug(" | marking as weak ref ", .{}); |
| 2363 | flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT); |
| 2364 | } |
| 2365 | pointers.appendAssumeCapacity(.{ |
| 2366 | .offset = base_offset, |
| 2367 | .segment_id = segment_index, |
| 2368 | .dylib_ordinal = dylib_ordinal, |
| 2369 | .name = bind_sym_name, |
| 2370 | .bind_flags = flags, |
| 2371 | }); |
| 2372 | |
| 2373 | if (atom.next_index) |next_index| { |
| 2374 | atom_index = next_index; |
| 2375 | } else break; |
| 2376 | } |
| 2377 | } |
| 2378 | |
| 2379 | fn collectExportData(self: *Zld, trie: *Trie) !void { |
| 2380 | const gpa = self.gpa; |
| 2381 | |
| 2382 | // TODO handle macho.EXPORT_SYMBOL_FLAGS_REEXPORT and macho.EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER. |
| 2383 | log.debug("collecting export data", .{}); |
| 2384 | |
| 2385 | const segment_index = self.getSegmentByName("__TEXT").?; |
| 2386 | const exec_segment = self.segments.items[segment_index]; |
| 2387 | const base_address = exec_segment.vmaddr; |
| 2388 | |
| 2389 | if (self.options.output_mode == .Exe) { |
| 2390 | for (&[_]SymbolWithLoc{ |
| 2391 | self.getEntryPoint(), |
| 2392 | self.globals.items[self.mh_execute_header_index.?], |
| 2393 | }) |global| { |
| 2394 | const sym = self.getSymbol(global); |
| 2395 | const sym_name = self.getSymbolName(global); |
| 2396 | log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value }); |
| 2397 | try trie.put(gpa, .{ |
| 2398 | .name = sym_name, |
| 2399 | .vmaddr_offset = sym.n_value - base_address, |
| 2400 | .export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR, |
| 2401 | }); |
| 2402 | } |
| 2403 | } else { |
| 2404 | assert(self.options.output_mode == .Lib); |
| 2405 | for (self.globals.items) |global| { |
| 2406 | const sym = self.getSymbol(global); |
| 2407 | if (sym.undf()) continue; |
| 2408 | if (sym.n_desc == N_DEAD) continue; |
| 2409 | |
| 2410 | const sym_name = self.getSymbolName(global); |
| 2411 | log.debug(" (putting '{s}' defined at 0x{x})", .{ sym_name, sym.n_value }); |
| 2412 | try trie.put(gpa, .{ |
| 2413 | .name = sym_name, |
| 2414 | .vmaddr_offset = sym.n_value - base_address, |
| 2415 | .export_flags = macho.EXPORT_SYMBOL_FLAGS_KIND_REGULAR, |
| 2416 | }); |
| 2417 | } |
| 2418 | } |
| 2419 | |
| 2420 | try trie.finalize(gpa); |
| 2421 | } |
| 2422 | |
| 2423 | fn writeDyldInfoData(self: *Zld, ncmds: *u32, lc_writer: anytype, reverse_lookups: [][]u32) !void { |
| 2424 | const gpa = self.gpa; |
| 2425 | |
| 2426 | var rebase_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 2427 | defer rebase_pointers.deinit(); |
| 2428 | try self.collectRebaseData(&rebase_pointers); |
| 2429 | |
| 2430 | var bind_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 2431 | defer bind_pointers.deinit(); |
| 2432 | try self.collectBindData(&bind_pointers, reverse_lookups); |
| 2433 | |
| 2434 | var lazy_bind_pointers = std.ArrayList(bind.Pointer).init(gpa); |
| 2435 | defer lazy_bind_pointers.deinit(); |
| 2436 | try self.collectLazyBindData(&lazy_bind_pointers); |
| 2437 | |
| 2438 | var trie = Trie{}; |
| 2439 | defer trie.deinit(gpa); |
| 2440 | try self.collectExportData(&trie); |
| 2441 | |
| 2442 | const link_seg = self.getLinkeditSegmentPtr(); |
| 2443 | const rebase_off = mem.alignForwardGeneric(u64, link_seg.fileoff, @alignOf(u64)); |
| 2444 | assert(rebase_off == link_seg.fileoff); |
| 2445 | const rebase_size = try bind.rebaseInfoSize(rebase_pointers.items); |
| 2446 | log.debug("writing rebase info from 0x{x} to 0x{x}", .{ rebase_off, rebase_off + rebase_size }); |
| 2447 | |
| 2448 | const bind_off = mem.alignForwardGeneric(u64, rebase_off + rebase_size, @alignOf(u64)); |
| 2449 | const bind_size = try bind.bindInfoSize(bind_pointers.items); |
| 2450 | log.debug("writing bind info from 0x{x} to 0x{x}", .{ bind_off, bind_off + bind_size }); |
| 2451 | |
| 2452 | const lazy_bind_off = mem.alignForwardGeneric(u64, bind_off + bind_size, @alignOf(u64)); |
| 2453 | const lazy_bind_size = try bind.lazyBindInfoSize(lazy_bind_pointers.items); |
| 2454 | log.debug("writing lazy bind info from 0x{x} to 0x{x}", .{ lazy_bind_off, lazy_bind_off + lazy_bind_size }); |
| 2455 | |
| 2456 | const export_off = mem.alignForwardGeneric(u64, lazy_bind_off + lazy_bind_size, @alignOf(u64)); |
| 2457 | const export_size = trie.size; |
| 2458 | log.debug("writing export trie from 0x{x} to 0x{x}", .{ export_off, export_off + export_size }); |
| 2459 | |
| 2460 | const needed_size = export_off + export_size - rebase_off; |
| 2461 | link_seg.filesize = needed_size; |
| 2462 | |
| 2463 | var buffer = try gpa.alloc(u8, needed_size); |
| 2464 | defer gpa.free(buffer); |
| 2465 | mem.set(u8, buffer, 0); |
| 2466 | |
| 2467 | var stream = std.io.fixedBufferStream(buffer); |
| 2468 | const writer = stream.writer(); |
| 2469 | |
| 2470 | try bind.writeRebaseInfo(rebase_pointers.items, writer); |
| 2471 | try stream.seekTo(bind_off - rebase_off); |
| 2472 | |
| 2473 | try bind.writeBindInfo(bind_pointers.items, writer); |
| 2474 | try stream.seekTo(lazy_bind_off - rebase_off); |
| 2475 | |
| 2476 | try bind.writeLazyBindInfo(lazy_bind_pointers.items, writer); |
| 2477 | try stream.seekTo(export_off - rebase_off); |
| 2478 | |
| 2479 | _ = try trie.write(writer); |
| 2480 | |
| 2481 | log.debug("writing dyld info from 0x{x} to 0x{x}", .{ |
| 2482 | rebase_off, |
| 2483 | rebase_off + needed_size, |
| 1293 | 2484 | }); |
| 1294 | | try macho_file.base.file.?.pwriteAll(&buf, file_offset); |
| 2485 | |
| 2486 | try self.file.pwriteAll(buffer, rebase_off); |
| 2487 | try self.populateLazyBindOffsetsInStubHelper(buffer[lazy_bind_off - rebase_off ..][0..lazy_bind_size]); |
| 2488 | |
| 2489 | try lc_writer.writeStruct(macho.dyld_info_command{ |
| 2490 | .cmd = .DYLD_INFO_ONLY, |
| 2491 | .cmdsize = @sizeOf(macho.dyld_info_command), |
| 2492 | .rebase_off = @intCast(u32, rebase_off), |
| 2493 | .rebase_size = @intCast(u32, rebase_size), |
| 2494 | .bind_off = @intCast(u32, bind_off), |
| 2495 | .bind_size = @intCast(u32, bind_size), |
| 2496 | .weak_bind_off = 0, |
| 2497 | .weak_bind_size = 0, |
| 2498 | .lazy_bind_off = @intCast(u32, lazy_bind_off), |
| 2499 | .lazy_bind_size = @intCast(u32, lazy_bind_size), |
| 2500 | .export_off = @intCast(u32, export_off), |
| 2501 | .export_size = @intCast(u32, export_size), |
| 2502 | }); |
| 2503 | ncmds.* += 1; |
| 1295 | 2504 | } |
| 1296 | | } |
| 1297 | 2505 | |
| 1298 | | const asc_u64 = std.sort.asc(u64); |
| 2506 | fn populateLazyBindOffsetsInStubHelper(self: *Zld, buffer: []const u8) !void { |
| 2507 | const gpa = self.gpa; |
| 1299 | 2508 | |
| 1300 | | fn writeFunctionStarts(macho_file: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 1301 | | const tracy = trace(@src()); |
| 1302 | | defer tracy.end(); |
| 2509 | const stub_helper_section_index = self.getSectionByName("__TEXT", "__stub_helper") orelse return; |
| 2510 | if (self.stub_helper_preamble_sym_index == null) return; |
| 1303 | 2511 | |
| 1304 | | const text_seg_index = macho_file.text_segment_cmd_index orelse return; |
| 1305 | | const text_sect_index = macho_file.text_section_index orelse return; |
| 1306 | | const text_seg = macho_file.segments.items[text_seg_index]; |
| 2512 | const section = self.sections.get(stub_helper_section_index); |
| 2513 | const last_atom_index = section.last_atom_index; |
| 1307 | 2514 | |
| 1308 | | const gpa = macho_file.base.allocator; |
| 2515 | var table = std.AutoHashMap(i64, AtomIndex).init(gpa); |
| 2516 | defer table.deinit(); |
| 2517 | |
| 2518 | { |
| 2519 | var stub_atom_index = last_atom_index; |
| 2520 | const la_symbol_ptr_section_index = self.getSectionByName("__DATA", "__la_symbol_ptr").?; |
| 2521 | var laptr_atom_index = self.sections.items(.last_atom_index)[la_symbol_ptr_section_index]; |
| 2522 | |
| 2523 | const base_addr = blk: { |
| 2524 | const segment_index = self.getSegmentByName("__DATA").?; |
| 2525 | const seg = self.segments.items[segment_index]; |
| 2526 | break :blk seg.vmaddr; |
| 2527 | }; |
| 2528 | |
| 2529 | while (true) { |
| 2530 | const stub_atom = self.getAtom(stub_atom_index); |
| 2531 | const laptr_atom = self.getAtom(laptr_atom_index); |
| 2532 | const laptr_off = blk: { |
| 2533 | const sym = self.getSymbolPtr(laptr_atom.getSymbolWithLoc()); |
| 2534 | break :blk @intCast(i64, sym.n_value - base_addr); |
| 2535 | }; |
| 2536 | |
| 2537 | try table.putNoClobber(laptr_off, stub_atom_index); |
| 2538 | |
| 2539 | if (laptr_atom.prev_index) |prev_index| { |
| 2540 | laptr_atom_index = prev_index; |
| 2541 | stub_atom_index = stub_atom.prev_index.?; |
| 2542 | } else break; |
| 2543 | } |
| 2544 | } |
| 2545 | |
| 2546 | var stream = std.io.fixedBufferStream(buffer); |
| 2547 | var reader = stream.reader(); |
| 2548 | var offsets = std.ArrayList(struct { sym_offset: i64, offset: u32 }).init(gpa); |
| 2549 | try offsets.append(.{ .sym_offset = undefined, .offset = 0 }); |
| 2550 | defer offsets.deinit(); |
| 2551 | var valid_block = false; |
| 2552 | |
| 2553 | while (true) { |
| 2554 | const inst = reader.readByte() catch |err| switch (err) { |
| 2555 | error.EndOfStream => break, |
| 2556 | }; |
| 2557 | const opcode: u8 = inst & macho.BIND_OPCODE_MASK; |
| 2558 | |
| 2559 | switch (opcode) { |
| 2560 | macho.BIND_OPCODE_DO_BIND => { |
| 2561 | valid_block = true; |
| 2562 | }, |
| 2563 | macho.BIND_OPCODE_DONE => { |
| 2564 | if (valid_block) { |
| 2565 | const offset = try stream.getPos(); |
| 2566 | try offsets.append(.{ .sym_offset = undefined, .offset = @intCast(u32, offset) }); |
| 2567 | } |
| 2568 | valid_block = false; |
| 2569 | }, |
| 2570 | macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => { |
| 2571 | var next = try reader.readByte(); |
| 2572 | while (next != @as(u8, 0)) { |
| 2573 | next = try reader.readByte(); |
| 2574 | } |
| 2575 | }, |
| 2576 | macho.BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => { |
| 2577 | var inserted = offsets.pop(); |
| 2578 | inserted.sym_offset = try std.leb.readILEB128(i64, reader); |
| 2579 | try offsets.append(inserted); |
| 2580 | }, |
| 2581 | macho.BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => { |
| 2582 | _ = try std.leb.readULEB128(u64, reader); |
| 2583 | }, |
| 2584 | macho.BIND_OPCODE_SET_ADDEND_SLEB => { |
| 2585 | _ = try std.leb.readILEB128(i64, reader); |
| 2586 | }, |
| 2587 | else => {}, |
| 2588 | } |
| 2589 | } |
| 2590 | |
| 2591 | const header = self.sections.items(.header)[stub_helper_section_index]; |
| 2592 | const stub_offset: u4 = switch (self.options.target.cpu.arch) { |
| 2593 | .x86_64 => 1, |
| 2594 | .aarch64 => 2 * @sizeOf(u32), |
| 2595 | else => unreachable, |
| 2596 | }; |
| 2597 | var buf: [@sizeOf(u32)]u8 = undefined; |
| 2598 | _ = offsets.pop(); |
| 2599 | |
| 2600 | while (offsets.popOrNull()) |bind_offset| { |
| 2601 | const atom_index = table.get(bind_offset.sym_offset).?; |
| 2602 | const atom = self.getAtom(atom_index); |
| 2603 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 2604 | |
| 2605 | const file_offset = header.offset + sym.n_value - header.addr + stub_offset; |
| 2606 | mem.writeIntLittle(u32, &buf, bind_offset.offset); |
| 2607 | |
| 2608 | log.debug("writing lazy bind offset in stub helper of 0x{x} for symbol {s} at offset 0x{x}", .{ |
| 2609 | bind_offset.offset, |
| 2610 | self.getSymbolName(atom.getSymbolWithLoc()), |
| 2611 | file_offset, |
| 2612 | }); |
| 2613 | |
| 2614 | try self.file.pwriteAll(&buf, file_offset); |
| 2615 | } |
| 2616 | } |
| 2617 | |
| 2618 | const asc_u64 = std.sort.asc(u64); |
| 2619 | |
| 2620 | fn writeFunctionStarts(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 2621 | const text_seg_index = self.getSegmentByName("__TEXT") orelse return; |
| 2622 | const text_sect_index = self.getSectionByName("__TEXT", "__text") orelse return; |
| 2623 | const text_seg = self.segments.items[text_seg_index]; |
| 2624 | |
| 2625 | const gpa = self.gpa; |
| 2626 | |
| 2627 | // We need to sort by address first |
| 2628 | var addresses = std.ArrayList(u64).init(gpa); |
| 2629 | defer addresses.deinit(); |
| 2630 | try addresses.ensureTotalCapacityPrecise(self.globals.items.len); |
| 2631 | |
| 2632 | for (self.globals.items) |global| { |
| 2633 | const sym = self.getSymbol(global); |
| 2634 | if (sym.undf()) continue; |
| 2635 | if (sym.n_desc == N_DEAD) continue; |
| 2636 | |
| 2637 | const sect_id = sym.n_sect - 1; |
| 2638 | if (sect_id != text_sect_index) continue; |
| 2639 | |
| 2640 | addresses.appendAssumeCapacity(sym.n_value); |
| 2641 | } |
| 2642 | |
| 2643 | std.sort.sort(u64, addresses.items, {}, asc_u64); |
| 2644 | |
| 2645 | var offsets = std.ArrayList(u32).init(gpa); |
| 2646 | defer offsets.deinit(); |
| 2647 | try offsets.ensureTotalCapacityPrecise(addresses.items.len); |
| 2648 | |
| 2649 | var last_off: u32 = 0; |
| 2650 | for (addresses.items) |addr| { |
| 2651 | const offset = @intCast(u32, addr - text_seg.vmaddr); |
| 2652 | const diff = offset - last_off; |
| 2653 | |
| 2654 | if (diff == 0) continue; |
| 2655 | |
| 2656 | offsets.appendAssumeCapacity(diff); |
| 2657 | last_off = offset; |
| 2658 | } |
| 2659 | |
| 2660 | var buffer = std.ArrayList(u8).init(gpa); |
| 2661 | defer buffer.deinit(); |
| 2662 | |
| 2663 | const max_size = @intCast(usize, offsets.items.len * @sizeOf(u64)); |
| 2664 | try buffer.ensureTotalCapacity(max_size); |
| 2665 | |
| 2666 | for (offsets.items) |offset| { |
| 2667 | try std.leb.writeULEB128(buffer.writer(), offset); |
| 2668 | } |
| 2669 | |
| 2670 | const link_seg = self.getLinkeditSegmentPtr(); |
| 2671 | const offset = mem.alignForwardGeneric(u64, link_seg.fileoff + link_seg.filesize, @alignOf(u64)); |
| 2672 | const needed_size = buffer.items.len; |
| 2673 | link_seg.filesize = offset + needed_size - link_seg.fileoff; |
| 2674 | |
| 2675 | log.debug("writing function starts info from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 2676 | |
| 2677 | try self.file.pwriteAll(buffer.items, offset); |
| 2678 | |
| 2679 | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 2680 | .cmd = .FUNCTION_STARTS, |
| 2681 | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| 2682 | .dataoff = @intCast(u32, offset), |
| 2683 | .datasize = @intCast(u32, needed_size), |
| 2684 | }); |
| 2685 | ncmds.* += 1; |
| 2686 | } |
| 2687 | |
| 2688 | fn filterDataInCode( |
| 2689 | dices: []const macho.data_in_code_entry, |
| 2690 | start_addr: u64, |
| 2691 | end_addr: u64, |
| 2692 | ) []const macho.data_in_code_entry { |
| 2693 | const Predicate = struct { |
| 2694 | addr: u64, |
| 1309 | 2695 | |
| 1310 | | // We need to sort by address first |
| 1311 | | var addresses = std.ArrayList(u64).init(gpa); |
| 1312 | | defer addresses.deinit(); |
| 1313 | | try addresses.ensureTotalCapacityPrecise(macho_file.globals.items.len); |
| 2696 | pub fn predicate(self: @This(), dice: macho.data_in_code_entry) bool { |
| 2697 | return dice.offset >= self.addr; |
| 2698 | } |
| 2699 | }; |
| 2700 | |
| 2701 | const start = lsearch(macho.data_in_code_entry, dices, Predicate{ .addr = start_addr }); |
| 2702 | const end = lsearch(macho.data_in_code_entry, dices[start..], Predicate{ .addr = end_addr }) + start; |
| 2703 | |
| 2704 | return dices[start..end]; |
| 2705 | } |
| 2706 | |
| 2707 | fn writeDataInCode(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 2708 | var out_dice = std.ArrayList(macho.data_in_code_entry).init(self.gpa); |
| 2709 | defer out_dice.deinit(); |
| 2710 | |
| 2711 | const text_sect_id = self.getSectionByName("__TEXT", "__text") orelse return; |
| 2712 | const text_sect_header = self.sections.items(.header)[text_sect_id]; |
| 2713 | |
| 2714 | for (self.objects.items) |object| { |
| 2715 | const dice = object.parseDataInCode() orelse continue; |
| 2716 | try out_dice.ensureUnusedCapacity(dice.len); |
| 2717 | |
| 2718 | for (object.atoms.items) |atom_index| { |
| 2719 | const atom = self.getAtom(atom_index); |
| 2720 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 2721 | const sect_id = sym.n_sect - 1; |
| 2722 | if (sect_id != text_sect_id) { |
| 2723 | continue; |
| 2724 | } |
| 2725 | |
| 2726 | const source_sym = object.getSourceSymbol(atom.sym_index) orelse continue; |
| 2727 | const source_addr = math.cast(u32, source_sym.n_value) orelse return error.Overflow; |
| 2728 | const filtered_dice = filterDataInCode(dice, source_addr, source_addr + atom.size); |
| 2729 | const base = math.cast(u32, sym.n_value - text_sect_header.addr + text_sect_header.offset) orelse |
| 2730 | return error.Overflow; |
| 2731 | |
| 2732 | for (filtered_dice) |single| { |
| 2733 | const offset = single.offset - source_addr + base; |
| 2734 | out_dice.appendAssumeCapacity(.{ |
| 2735 | .offset = offset, |
| 2736 | .length = single.length, |
| 2737 | .kind = single.kind, |
| 2738 | }); |
| 2739 | } |
| 2740 | } |
| 2741 | } |
| 2742 | |
| 2743 | const seg = self.getLinkeditSegmentPtr(); |
| 2744 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 2745 | const needed_size = out_dice.items.len * @sizeOf(macho.data_in_code_entry); |
| 2746 | seg.filesize = offset + needed_size - seg.fileoff; |
| 2747 | |
| 2748 | log.debug("writing data-in-code from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 2749 | |
| 2750 | try self.file.pwriteAll(mem.sliceAsBytes(out_dice.items), offset); |
| 2751 | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 2752 | .cmd = .DATA_IN_CODE, |
| 2753 | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| 2754 | .dataoff = @intCast(u32, offset), |
| 2755 | .datasize = @intCast(u32, needed_size), |
| 2756 | }); |
| 2757 | ncmds.* += 1; |
| 2758 | } |
| 2759 | |
| 2760 | fn writeSymtabs(self: *Zld, ncmds: *u32, lc_writer: anytype) !void { |
| 2761 | var symtab_cmd = macho.symtab_command{ |
| 2762 | .cmdsize = @sizeOf(macho.symtab_command), |
| 2763 | .symoff = 0, |
| 2764 | .nsyms = 0, |
| 2765 | .stroff = 0, |
| 2766 | .strsize = 0, |
| 2767 | }; |
| 2768 | var dysymtab_cmd = macho.dysymtab_command{ |
| 2769 | .cmdsize = @sizeOf(macho.dysymtab_command), |
| 2770 | .ilocalsym = 0, |
| 2771 | .nlocalsym = 0, |
| 2772 | .iextdefsym = 0, |
| 2773 | .nextdefsym = 0, |
| 2774 | .iundefsym = 0, |
| 2775 | .nundefsym = 0, |
| 2776 | .tocoff = 0, |
| 2777 | .ntoc = 0, |
| 2778 | .modtaboff = 0, |
| 2779 | .nmodtab = 0, |
| 2780 | .extrefsymoff = 0, |
| 2781 | .nextrefsyms = 0, |
| 2782 | .indirectsymoff = 0, |
| 2783 | .nindirectsyms = 0, |
| 2784 | .extreloff = 0, |
| 2785 | .nextrel = 0, |
| 2786 | .locreloff = 0, |
| 2787 | .nlocrel = 0, |
| 2788 | }; |
| 2789 | var ctx = try self.writeSymtab(&symtab_cmd); |
| 2790 | defer ctx.imports_table.deinit(); |
| 2791 | try self.writeDysymtab(ctx, &dysymtab_cmd); |
| 2792 | try self.writeStrtab(&symtab_cmd); |
| 2793 | try lc_writer.writeStruct(symtab_cmd); |
| 2794 | try lc_writer.writeStruct(dysymtab_cmd); |
| 2795 | ncmds.* += 2; |
| 2796 | } |
| 2797 | |
| 2798 | fn writeSymtab(self: *Zld, lc: *macho.symtab_command) !SymtabCtx { |
| 2799 | const gpa = self.gpa; |
| 2800 | |
| 2801 | var locals = std.ArrayList(macho.nlist_64).init(gpa); |
| 2802 | defer locals.deinit(); |
| 2803 | |
| 2804 | for (self.objects.items) |object| { |
| 2805 | for (object.atoms.items) |atom_index| { |
| 2806 | const atom = self.getAtom(atom_index); |
| 2807 | const sym_loc = atom.getSymbolWithLoc(); |
| 2808 | const sym = self.getSymbol(sym_loc); |
| 2809 | if (sym.n_strx == 0) continue; // no name, skip |
| 2810 | if (sym.ext()) continue; // an export lands in its own symtab section, skip |
| 2811 | if (self.symbolIsTemp(sym_loc)) continue; // local temp symbol, skip |
| 2812 | |
| 2813 | var out_sym = sym; |
| 2814 | out_sym.n_strx = try self.strtab.insert(gpa, self.getSymbolName(sym_loc)); |
| 2815 | try locals.append(out_sym); |
| 2816 | } |
| 2817 | } |
| 2818 | |
| 2819 | if (!self.options.strip) { |
| 2820 | for (self.objects.items) |object| { |
| 2821 | try self.generateSymbolStabs(object, &locals); |
| 2822 | } |
| 2823 | } |
| 2824 | |
| 2825 | var exports = std.ArrayList(macho.nlist_64).init(gpa); |
| 2826 | defer exports.deinit(); |
| 2827 | |
| 2828 | for (self.globals.items) |global| { |
| 2829 | const sym = self.getSymbol(global); |
| 2830 | if (sym.undf()) continue; // import, skip |
| 2831 | if (sym.n_desc == N_DEAD) continue; |
| 2832 | |
| 2833 | var out_sym = sym; |
| 2834 | out_sym.n_strx = try self.strtab.insert(gpa, self.getSymbolName(global)); |
| 2835 | try exports.append(out_sym); |
| 2836 | } |
| 2837 | |
| 2838 | var imports = std.ArrayList(macho.nlist_64).init(gpa); |
| 2839 | defer imports.deinit(); |
| 2840 | |
| 2841 | var imports_table = std.AutoHashMap(SymbolWithLoc, u32).init(gpa); |
| 2842 | |
| 2843 | for (self.globals.items) |global| { |
| 2844 | const sym = self.getSymbol(global); |
| 2845 | if (!sym.undf()) continue; // not an import, skip |
| 2846 | if (sym.n_desc == N_DEAD) continue; |
| 2847 | |
| 2848 | const new_index = @intCast(u32, imports.items.len); |
| 2849 | var out_sym = sym; |
| 2850 | out_sym.n_strx = try self.strtab.insert(gpa, self.getSymbolName(global)); |
| 2851 | try imports.append(out_sym); |
| 2852 | try imports_table.putNoClobber(global, new_index); |
| 2853 | } |
| 2854 | |
| 2855 | const nlocals = @intCast(u32, locals.items.len); |
| 2856 | const nexports = @intCast(u32, exports.items.len); |
| 2857 | const nimports = @intCast(u32, imports.items.len); |
| 2858 | const nsyms = nlocals + nexports + nimports; |
| 2859 | |
| 2860 | const seg = self.getLinkeditSegmentPtr(); |
| 2861 | const offset = mem.alignForwardGeneric( |
| 2862 | u64, |
| 2863 | seg.fileoff + seg.filesize, |
| 2864 | @alignOf(macho.nlist_64), |
| 2865 | ); |
| 2866 | const needed_size = nsyms * @sizeOf(macho.nlist_64); |
| 2867 | seg.filesize = offset + needed_size - seg.fileoff; |
| 2868 | |
| 2869 | var buffer = std.ArrayList(u8).init(gpa); |
| 2870 | defer buffer.deinit(); |
| 2871 | try buffer.ensureTotalCapacityPrecise(needed_size); |
| 2872 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(locals.items)); |
| 2873 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(exports.items)); |
| 2874 | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(imports.items)); |
| 2875 | |
| 2876 | log.debug("writing symtab from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 2877 | try self.file.pwriteAll(buffer.items, offset); |
| 2878 | |
| 2879 | lc.symoff = @intCast(u32, offset); |
| 2880 | lc.nsyms = nsyms; |
| 2881 | |
| 2882 | return SymtabCtx{ |
| 2883 | .nlocalsym = nlocals, |
| 2884 | .nextdefsym = nexports, |
| 2885 | .nundefsym = nimports, |
| 2886 | .imports_table = imports_table, |
| 2887 | }; |
| 2888 | } |
| 1314 | 2889 | |
| 1315 | | for (macho_file.globals.items) |global| { |
| 1316 | | const sym = macho_file.getSymbol(global); |
| 1317 | | if (sym.undf()) continue; |
| 1318 | | if (sym.n_desc == MachO.N_DESC_GCED) continue; |
| 1319 | | const sect_id = sym.n_sect - 1; |
| 1320 | | if (sect_id != text_sect_index) continue; |
| 2890 | fn writeStrtab(self: *Zld, lc: *macho.symtab_command) !void { |
| 2891 | const seg = self.getLinkeditSegmentPtr(); |
| 2892 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 2893 | const needed_size = self.strtab.buffer.items.len; |
| 2894 | seg.filesize = offset + needed_size - seg.fileoff; |
| 1321 | 2895 | |
| 1322 | | addresses.appendAssumeCapacity(sym.n_value); |
| 2896 | log.debug("writing string table from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 2897 | |
| 2898 | try self.file.pwriteAll(self.strtab.buffer.items, offset); |
| 2899 | |
| 2900 | lc.stroff = @intCast(u32, offset); |
| 2901 | lc.strsize = @intCast(u32, needed_size); |
| 1323 | 2902 | } |
| 1324 | 2903 | |
| 1325 | | std.sort.sort(u64, addresses.items, {}, asc_u64); |
| 2904 | const SymtabCtx = struct { |
| 2905 | nlocalsym: u32, |
| 2906 | nextdefsym: u32, |
| 2907 | nundefsym: u32, |
| 2908 | imports_table: std.AutoHashMap(SymbolWithLoc, u32), |
| 2909 | }; |
| 2910 | |
| 2911 | fn writeDysymtab(self: *Zld, ctx: SymtabCtx, lc: *macho.dysymtab_command) !void { |
| 2912 | const gpa = self.gpa; |
| 2913 | const nstubs = @intCast(u32, self.stubs.items.len); |
| 2914 | const ngot_entries = @intCast(u32, self.got_entries.items.len); |
| 2915 | const nindirectsyms = nstubs * 2 + ngot_entries; |
| 2916 | const iextdefsym = ctx.nlocalsym; |
| 2917 | const iundefsym = iextdefsym + ctx.nextdefsym; |
| 2918 | |
| 2919 | const seg = self.getLinkeditSegmentPtr(); |
| 2920 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 2921 | const needed_size = nindirectsyms * @sizeOf(u32); |
| 2922 | seg.filesize = offset + needed_size - seg.fileoff; |
| 2923 | |
| 2924 | log.debug("writing indirect symbol table from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 2925 | |
| 2926 | var buf = std.ArrayList(u8).init(gpa); |
| 2927 | defer buf.deinit(); |
| 2928 | try buf.ensureTotalCapacity(needed_size); |
| 2929 | const writer = buf.writer(); |
| 2930 | |
| 2931 | if (self.getSectionByName("__TEXT", "__stubs")) |sect_id| { |
| 2932 | const stubs = &self.sections.items(.header)[sect_id]; |
| 2933 | stubs.reserved1 = 0; |
| 2934 | for (self.stubs.items) |entry| { |
| 2935 | const target_sym = entry.getTargetSymbol(self); |
| 2936 | assert(target_sym.undf()); |
| 2937 | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 2938 | } |
| 2939 | } |
| 2940 | |
| 2941 | if (self.getSectionByName("__DATA_CONST", "__got")) |sect_id| { |
| 2942 | const got = &self.sections.items(.header)[sect_id]; |
| 2943 | got.reserved1 = nstubs; |
| 2944 | for (self.got_entries.items) |entry| { |
| 2945 | const target_sym = entry.getTargetSymbol(self); |
| 2946 | if (target_sym.undf()) { |
| 2947 | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 2948 | } else { |
| 2949 | try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL); |
| 2950 | } |
| 2951 | } |
| 2952 | } |
| 2953 | |
| 2954 | if (self.getSectionByName("__DATA", "__la_symbol_ptr")) |sect_id| { |
| 2955 | const la_symbol_ptr = &self.sections.items(.header)[sect_id]; |
| 2956 | la_symbol_ptr.reserved1 = nstubs + ngot_entries; |
| 2957 | for (self.stubs.items) |entry| { |
| 2958 | const target_sym = entry.getTargetSymbol(self); |
| 2959 | assert(target_sym.undf()); |
| 2960 | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 2961 | } |
| 2962 | } |
| 2963 | |
| 2964 | assert(buf.items.len == needed_size); |
| 2965 | try self.file.pwriteAll(buf.items, offset); |
| 2966 | |
| 2967 | lc.nlocalsym = ctx.nlocalsym; |
| 2968 | lc.iextdefsym = iextdefsym; |
| 2969 | lc.nextdefsym = ctx.nextdefsym; |
| 2970 | lc.iundefsym = iundefsym; |
| 2971 | lc.nundefsym = ctx.nundefsym; |
| 2972 | lc.indirectsymoff = @intCast(u32, offset); |
| 2973 | lc.nindirectsyms = nindirectsyms; |
| 2974 | } |
| 2975 | |
| 2976 | fn writeCodeSignaturePadding( |
| 2977 | self: *Zld, |
| 2978 | code_sig: *CodeSignature, |
| 2979 | ncmds: *u32, |
| 2980 | lc_writer: anytype, |
| 2981 | ) !u32 { |
| 2982 | const seg = self.getLinkeditSegmentPtr(); |
| 2983 | // Code signature data has to be 16-bytes aligned for Apple tools to recognize the file |
| 2984 | // https://github.com/opensource-apple/cctools/blob/fdb4825f303fd5c0751be524babd32958181b3ed/libstuff/checkout.c#L271 |
| 2985 | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, 16); |
| 2986 | const needed_size = code_sig.estimateSize(offset); |
| 2987 | seg.filesize = offset + needed_size - seg.fileoff; |
| 2988 | seg.vmsize = mem.alignForwardGeneric(u64, seg.filesize, self.page_size); |
| 2989 | log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 2990 | // Pad out the space. We need to do this to calculate valid hashes for everything in the file |
| 2991 | // except for code signature data. |
| 2992 | try self.file.pwriteAll(&[_]u8{0}, offset + needed_size - 1); |
| 2993 | |
| 2994 | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 2995 | .cmd = .CODE_SIGNATURE, |
| 2996 | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| 2997 | .dataoff = @intCast(u32, offset), |
| 2998 | .datasize = @intCast(u32, needed_size), |
| 2999 | }); |
| 3000 | ncmds.* += 1; |
| 3001 | |
| 3002 | return @intCast(u32, offset); |
| 3003 | } |
| 3004 | |
| 3005 | fn writeCodeSignature(self: *Zld, code_sig: *CodeSignature, offset: u32) !void { |
| 3006 | const seg_id = self.getSegmentByName("__TEXT").?; |
| 3007 | const seg = self.segments.items[seg_id]; |
| 3008 | |
| 3009 | var buffer = std.ArrayList(u8).init(self.gpa); |
| 3010 | defer buffer.deinit(); |
| 3011 | try buffer.ensureTotalCapacityPrecise(code_sig.size()); |
| 3012 | try code_sig.writeAdhocSignature(self.gpa, .{ |
| 3013 | .file = self.file, |
| 3014 | .exec_seg_base = seg.fileoff, |
| 3015 | .exec_seg_limit = seg.filesize, |
| 3016 | .file_size = offset, |
| 3017 | .output_mode = self.options.output_mode, |
| 3018 | }, buffer.writer()); |
| 3019 | assert(buffer.items.len == code_sig.size()); |
| 3020 | |
| 3021 | log.debug("writing code signature from 0x{x} to 0x{x}", .{ |
| 3022 | offset, |
| 3023 | offset + buffer.items.len, |
| 3024 | }); |
| 3025 | |
| 3026 | try self.file.pwriteAll(buffer.items, offset); |
| 3027 | } |
| 3028 | |
| 3029 | /// Writes Mach-O file header. |
| 3030 | fn writeHeader(self: *Zld, ncmds: u32, sizeofcmds: u32) !void { |
| 3031 | var header: macho.mach_header_64 = .{}; |
| 3032 | header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE | macho.MH_TWOLEVEL; |
| 3033 | |
| 3034 | switch (self.options.target.cpu.arch) { |
| 3035 | .aarch64 => { |
| 3036 | header.cputype = macho.CPU_TYPE_ARM64; |
| 3037 | header.cpusubtype = macho.CPU_SUBTYPE_ARM_ALL; |
| 3038 | }, |
| 3039 | .x86_64 => { |
| 3040 | header.cputype = macho.CPU_TYPE_X86_64; |
| 3041 | header.cpusubtype = macho.CPU_SUBTYPE_X86_64_ALL; |
| 3042 | }, |
| 3043 | else => return error.UnsupportedCpuArchitecture, |
| 3044 | } |
| 3045 | |
| 3046 | switch (self.options.output_mode) { |
| 3047 | .Exe => { |
| 3048 | header.filetype = macho.MH_EXECUTE; |
| 3049 | }, |
| 3050 | .Lib => { |
| 3051 | // By this point, it can only be a dylib. |
| 3052 | header.filetype = macho.MH_DYLIB; |
| 3053 | header.flags |= macho.MH_NO_REEXPORTED_DYLIBS; |
| 3054 | }, |
| 3055 | else => unreachable, |
| 3056 | } |
| 3057 | |
| 3058 | if (self.getSectionByName("__DATA", "__thread_vars")) |sect_id| { |
| 3059 | header.flags |= macho.MH_HAS_TLV_DESCRIPTORS; |
| 3060 | if (self.sections.items(.header)[sect_id].size > 0) { |
| 3061 | header.flags |= macho.MH_HAS_TLV_DESCRIPTORS; |
| 3062 | } |
| 3063 | } |
| 3064 | |
| 3065 | header.ncmds = ncmds; |
| 3066 | header.sizeofcmds = sizeofcmds; |
| 3067 | |
| 3068 | log.debug("writing Mach-O header {}", .{header}); |
| 3069 | |
| 3070 | try self.file.pwriteAll(mem.asBytes(&header), 0); |
| 3071 | } |
| 3072 | |
| 3073 | pub fn makeStaticString(bytes: []const u8) [16]u8 { |
| 3074 | var buf = [_]u8{0} ** 16; |
| 3075 | assert(bytes.len <= buf.len); |
| 3076 | mem.copy(u8, &buf, bytes); |
| 3077 | return buf; |
| 3078 | } |
| 3079 | |
| 3080 | pub inline fn getAtomPtr(self: *Zld, atom_index: AtomIndex) *Atom { |
| 3081 | assert(atom_index < self.atoms.items.len); |
| 3082 | return &self.atoms.items[atom_index]; |
| 3083 | } |
| 3084 | |
| 3085 | pub inline fn getAtom(self: Zld, atom_index: AtomIndex) Atom { |
| 3086 | assert(atom_index < self.atoms.items.len); |
| 3087 | return self.atoms.items[atom_index]; |
| 3088 | } |
| 3089 | |
| 3090 | fn getSegmentByName(self: Zld, segname: []const u8) ?u8 { |
| 3091 | for (self.segments.items) |seg, i| { |
| 3092 | if (mem.eql(u8, segname, seg.segName())) return @intCast(u8, i); |
| 3093 | } else return null; |
| 3094 | } |
| 3095 | |
| 3096 | pub inline fn getSegment(self: Zld, sect_id: u8) macho.segment_command_64 { |
| 3097 | const index = self.sections.items(.segment_index)[sect_id]; |
| 3098 | return self.segments.items[index]; |
| 3099 | } |
| 3100 | |
| 3101 | pub inline fn getSegmentPtr(self: *Zld, sect_id: u8) *macho.segment_command_64 { |
| 3102 | const index = self.sections.items(.segment_index)[sect_id]; |
| 3103 | return &self.segments.items[index]; |
| 3104 | } |
| 3105 | |
| 3106 | pub inline fn getLinkeditSegmentPtr(self: *Zld) *macho.segment_command_64 { |
| 3107 | assert(self.segments.items.len > 0); |
| 3108 | const seg = &self.segments.items[self.segments.items.len - 1]; |
| 3109 | assert(mem.eql(u8, seg.segName(), "__LINKEDIT")); |
| 3110 | return seg; |
| 3111 | } |
| 3112 | |
| 3113 | pub fn getSectionByName(self: Zld, segname: []const u8, sectname: []const u8) ?u8 { |
| 3114 | // TODO investigate caching with a hashmap |
| 3115 | for (self.sections.items(.header)) |header, i| { |
| 3116 | if (mem.eql(u8, header.segName(), segname) and mem.eql(u8, header.sectName(), sectname)) |
| 3117 | return @intCast(u8, i); |
| 3118 | } else return null; |
| 3119 | } |
| 3120 | |
| 3121 | pub fn getSectionIndexes(self: Zld, segment_index: u8) struct { start: u8, end: u8 } { |
| 3122 | var start: u8 = 0; |
| 3123 | const nsects = for (self.segments.items) |seg, i| { |
| 3124 | if (i == segment_index) break @intCast(u8, seg.nsects); |
| 3125 | start += @intCast(u8, seg.nsects); |
| 3126 | } else 0; |
| 3127 | return .{ .start = start, .end = start + nsects }; |
| 3128 | } |
| 3129 | |
| 3130 | pub fn symbolIsTemp(self: *Zld, sym_with_loc: SymbolWithLoc) bool { |
| 3131 | const sym = self.getSymbol(sym_with_loc); |
| 3132 | if (!sym.sect()) return false; |
| 3133 | if (sym.ext()) return false; |
| 3134 | const sym_name = self.getSymbolName(sym_with_loc); |
| 3135 | return mem.startsWith(u8, sym_name, "l") or mem.startsWith(u8, sym_name, "L"); |
| 3136 | } |
| 3137 | |
| 3138 | /// Returns pointer-to-symbol described by `sym_with_loc` descriptor. |
| 3139 | pub fn getSymbolPtr(self: *Zld, sym_with_loc: SymbolWithLoc) *macho.nlist_64 { |
| 3140 | if (sym_with_loc.getFile()) |file| { |
| 3141 | const object = &self.objects.items[file]; |
| 3142 | return &object.symtab[sym_with_loc.sym_index]; |
| 3143 | } else { |
| 3144 | return &self.locals.items[sym_with_loc.sym_index]; |
| 3145 | } |
| 3146 | } |
| 3147 | |
| 3148 | /// Returns symbol described by `sym_with_loc` descriptor. |
| 3149 | pub fn getSymbol(self: *Zld, sym_with_loc: SymbolWithLoc) macho.nlist_64 { |
| 3150 | return self.getSymbolPtr(sym_with_loc).*; |
| 3151 | } |
| 3152 | |
| 3153 | /// Returns name of the symbol described by `sym_with_loc` descriptor. |
| 3154 | pub fn getSymbolName(self: *Zld, sym_with_loc: SymbolWithLoc) []const u8 { |
| 3155 | if (sym_with_loc.getFile()) |file| { |
| 3156 | const object = self.objects.items[file]; |
| 3157 | return object.getSymbolName(sym_with_loc.sym_index); |
| 3158 | } else { |
| 3159 | const sym = self.locals.items[sym_with_loc.sym_index]; |
| 3160 | return self.strtab.get(sym.n_strx).?; |
| 3161 | } |
| 3162 | } |
| 3163 | |
| 3164 | /// Returns GOT atom that references `sym_with_loc` if one exists. |
| 3165 | /// Returns null otherwise. |
| 3166 | pub fn getGotAtomIndexForSymbol(self: *Zld, sym_with_loc: SymbolWithLoc) ?AtomIndex { |
| 3167 | const index = self.got_table.get(sym_with_loc) orelse return null; |
| 3168 | const entry = self.got_entries.items[index]; |
| 3169 | return entry.atom_index; |
| 3170 | } |
| 3171 | |
| 3172 | /// Returns stubs atom that references `sym_with_loc` if one exists. |
| 3173 | /// Returns null otherwise. |
| 3174 | pub fn getStubsAtomIndexForSymbol(self: *Zld, sym_with_loc: SymbolWithLoc) ?AtomIndex { |
| 3175 | const index = self.stubs_table.get(sym_with_loc) orelse return null; |
| 3176 | const entry = self.stubs.items[index]; |
| 3177 | return entry.atom_index; |
| 3178 | } |
| 3179 | |
| 3180 | /// Returns TLV pointer atom that references `sym_with_loc` if one exists. |
| 3181 | /// Returns null otherwise. |
| 3182 | pub fn getTlvPtrAtomIndexForSymbol(self: *Zld, sym_with_loc: SymbolWithLoc) ?AtomIndex { |
| 3183 | const index = self.tlv_ptr_table.get(sym_with_loc) orelse return null; |
| 3184 | const entry = self.tlv_ptr_entries.items[index]; |
| 3185 | return entry.atom_index; |
| 3186 | } |
| 3187 | |
| 3188 | /// Returns symbol location corresponding to the set entrypoint. |
| 3189 | /// Asserts output mode is executable. |
| 3190 | pub fn getEntryPoint(self: Zld) SymbolWithLoc { |
| 3191 | assert(self.options.output_mode == .Exe); |
| 3192 | const global_index = self.entry_index.?; |
| 3193 | return self.globals.items[global_index]; |
| 3194 | } |
| 3195 | |
| 3196 | inline fn requiresThunks(self: Zld) bool { |
| 3197 | return self.options.target.cpu.arch == .aarch64; |
| 3198 | } |
| 3199 | |
| 3200 | pub fn generateSymbolStabs(self: *Zld, object: Object, locals: *std.ArrayList(macho.nlist_64)) !void { |
| 3201 | log.debug("generating stabs for '{s}'", .{object.name}); |
| 3202 | |
| 3203 | const gpa = self.gpa; |
| 3204 | var debug_info = object.parseDwarfInfo(); |
| 3205 | |
| 3206 | var lookup = DwarfInfo.AbbrevLookupTable.init(gpa); |
| 3207 | defer lookup.deinit(); |
| 3208 | try lookup.ensureUnusedCapacity(std.math.maxInt(u8)); |
| 3209 | |
| 3210 | // We assume there is only one CU. |
| 3211 | var cu_it = debug_info.getCompileUnitIterator(); |
| 3212 | const compile_unit = while (try cu_it.next()) |cu| { |
| 3213 | try debug_info.genAbbrevLookupByKind(cu.cuh.debug_abbrev_offset, &lookup); |
| 3214 | break cu; |
| 3215 | } else { |
| 3216 | log.debug("no compile unit found in debug info in {s}; skipping", .{object.name}); |
| 3217 | return; |
| 3218 | }; |
| 3219 | |
| 3220 | var abbrev_it = compile_unit.getAbbrevEntryIterator(debug_info); |
| 3221 | const cu_entry: DwarfInfo.AbbrevEntry = while (try abbrev_it.next(lookup)) |entry| switch (entry.tag) { |
| 3222 | dwarf.TAG.compile_unit => break entry, |
| 3223 | else => continue, |
| 3224 | } else { |
| 3225 | log.debug("missing DWARF_TAG_compile_unit tag in {s}; skipping", .{object.name}); |
| 3226 | return; |
| 3227 | }; |
| 3228 | |
| 3229 | var maybe_tu_name: ?[]const u8 = null; |
| 3230 | var maybe_tu_comp_dir: ?[]const u8 = null; |
| 3231 | var attr_it = cu_entry.getAttributeIterator(debug_info, compile_unit.cuh); |
| 3232 | |
| 3233 | while (try attr_it.next()) |attr| switch (attr.name) { |
| 3234 | dwarf.AT.comp_dir => maybe_tu_comp_dir = attr.getString(debug_info, compile_unit.cuh) orelse continue, |
| 3235 | dwarf.AT.name => maybe_tu_name = attr.getString(debug_info, compile_unit.cuh) orelse continue, |
| 3236 | else => continue, |
| 3237 | }; |
| 3238 | |
| 3239 | if (maybe_tu_name == null or maybe_tu_comp_dir == null) { |
| 3240 | log.debug("missing DWARF_AT_comp_dir and DWARF_AT_name attributes {s}; skipping", .{object.name}); |
| 3241 | return; |
| 3242 | } |
| 3243 | |
| 3244 | const tu_name = maybe_tu_name.?; |
| 3245 | const tu_comp_dir = maybe_tu_comp_dir.?; |
| 3246 | |
| 3247 | // Open scope |
| 3248 | try locals.ensureUnusedCapacity(3); |
| 3249 | locals.appendAssumeCapacity(.{ |
| 3250 | .n_strx = try self.strtab.insert(gpa, tu_comp_dir), |
| 3251 | .n_type = macho.N_SO, |
| 3252 | .n_sect = 0, |
| 3253 | .n_desc = 0, |
| 3254 | .n_value = 0, |
| 3255 | }); |
| 3256 | locals.appendAssumeCapacity(.{ |
| 3257 | .n_strx = try self.strtab.insert(gpa, tu_name), |
| 3258 | .n_type = macho.N_SO, |
| 3259 | .n_sect = 0, |
| 3260 | .n_desc = 0, |
| 3261 | .n_value = 0, |
| 3262 | }); |
| 3263 | locals.appendAssumeCapacity(.{ |
| 3264 | .n_strx = try self.strtab.insert(gpa, object.name), |
| 3265 | .n_type = macho.N_OSO, |
| 3266 | .n_sect = 0, |
| 3267 | .n_desc = 1, |
| 3268 | .n_value = object.mtime, |
| 3269 | }); |
| 3270 | |
| 3271 | var stabs_buf: [4]macho.nlist_64 = undefined; |
| 3272 | |
| 3273 | var name_lookup: ?DwarfInfo.SubprogramLookupByName = if (object.header.flags & macho.MH_SUBSECTIONS_VIA_SYMBOLS == 0) blk: { |
| 3274 | var name_lookup = DwarfInfo.SubprogramLookupByName.init(gpa); |
| 3275 | errdefer name_lookup.deinit(); |
| 3276 | try name_lookup.ensureUnusedCapacity(@intCast(u32, object.atoms.items.len)); |
| 3277 | try debug_info.genSubprogramLookupByName(compile_unit, lookup, &name_lookup); |
| 3278 | break :blk name_lookup; |
| 3279 | } else null; |
| 3280 | defer if (name_lookup) |*nl| nl.deinit(); |
| 3281 | |
| 3282 | for (object.atoms.items) |atom_index| { |
| 3283 | const atom = self.getAtom(atom_index); |
| 3284 | const stabs = try self.generateSymbolStabsForSymbol( |
| 3285 | atom_index, |
| 3286 | atom.getSymbolWithLoc(), |
| 3287 | name_lookup, |
| 3288 | &stabs_buf, |
| 3289 | ); |
| 3290 | try locals.appendSlice(stabs); |
| 3291 | |
| 3292 | var it = Atom.getInnerSymbolsIterator(self, atom_index); |
| 3293 | while (it.next()) |sym_loc| { |
| 3294 | const contained_stabs = try self.generateSymbolStabsForSymbol( |
| 3295 | atom_index, |
| 3296 | sym_loc, |
| 3297 | name_lookup, |
| 3298 | &stabs_buf, |
| 3299 | ); |
| 3300 | try locals.appendSlice(contained_stabs); |
| 3301 | } |
| 3302 | } |
| 3303 | |
| 3304 | // Close scope |
| 3305 | try locals.append(.{ |
| 3306 | .n_strx = 0, |
| 3307 | .n_type = macho.N_SO, |
| 3308 | .n_sect = 0, |
| 3309 | .n_desc = 0, |
| 3310 | .n_value = 0, |
| 3311 | }); |
| 3312 | } |
| 3313 | |
| 3314 | fn generateSymbolStabsForSymbol( |
| 3315 | self: *Zld, |
| 3316 | atom_index: AtomIndex, |
| 3317 | sym_loc: SymbolWithLoc, |
| 3318 | lookup: ?DwarfInfo.SubprogramLookupByName, |
| 3319 | buf: *[4]macho.nlist_64, |
| 3320 | ) ![]const macho.nlist_64 { |
| 3321 | const gpa = self.gpa; |
| 3322 | const object = self.objects.items[sym_loc.getFile().?]; |
| 3323 | const sym = self.getSymbol(sym_loc); |
| 3324 | const sym_name = self.getSymbolName(sym_loc); |
| 3325 | const header = self.sections.items(.header)[sym.n_sect - 1]; |
| 3326 | |
| 3327 | if (sym.n_strx == 0) return buf[0..0]; |
| 3328 | if (self.symbolIsTemp(sym_loc)) return buf[0..0]; |
| 3329 | |
| 3330 | if (!header.isCode()) { |
| 3331 | // Since we are not dealing with machine code, it's either a global or a static depending |
| 3332 | // on the linkage scope. |
| 3333 | if (sym.sect() and sym.ext()) { |
| 3334 | // Global gets an N_GSYM stab type. |
| 3335 | buf[0] = .{ |
| 3336 | .n_strx = try self.strtab.insert(gpa, sym_name), |
| 3337 | .n_type = macho.N_GSYM, |
| 3338 | .n_sect = sym.n_sect, |
| 3339 | .n_desc = 0, |
| 3340 | .n_value = 0, |
| 3341 | }; |
| 3342 | } else { |
| 3343 | // Local static gets an N_STSYM stab type. |
| 3344 | buf[0] = .{ |
| 3345 | .n_strx = try self.strtab.insert(gpa, sym_name), |
| 3346 | .n_type = macho.N_STSYM, |
| 3347 | .n_sect = sym.n_sect, |
| 3348 | .n_desc = 0, |
| 3349 | .n_value = sym.n_value, |
| 3350 | }; |
| 3351 | } |
| 3352 | return buf[0..1]; |
| 3353 | } |
| 3354 | |
| 3355 | const size: u64 = size: { |
| 3356 | if (object.header.flags & macho.MH_SUBSECTIONS_VIA_SYMBOLS != 0) { |
| 3357 | break :size self.getAtom(atom_index).size; |
| 3358 | } |
| 3359 | |
| 3360 | // Since we don't have subsections to work with, we need to infer the size of each function |
| 3361 | // the slow way by scanning the debug info for matching symbol names and extracting |
| 3362 | // the symbol's DWARF_AT_low_pc and DWARF_AT_high_pc values. |
| 3363 | const source_sym = object.getSourceSymbol(sym_loc.sym_index) orelse return buf[0..0]; |
| 3364 | const subprogram = lookup.?.get(sym_name[1..]) orelse return buf[0..0]; |
| 3365 | |
| 3366 | if (subprogram.addr <= source_sym.n_value and source_sym.n_value < subprogram.addr + subprogram.size) { |
| 3367 | break :size subprogram.size; |
| 3368 | } else { |
| 3369 | log.debug("no stab found for {s}", .{sym_name}); |
| 3370 | return buf[0..0]; |
| 3371 | } |
| 3372 | }; |
| 3373 | |
| 3374 | buf[0] = .{ |
| 3375 | .n_strx = 0, |
| 3376 | .n_type = macho.N_BNSYM, |
| 3377 | .n_sect = sym.n_sect, |
| 3378 | .n_desc = 0, |
| 3379 | .n_value = sym.n_value, |
| 3380 | }; |
| 3381 | buf[1] = .{ |
| 3382 | .n_strx = try self.strtab.insert(gpa, sym_name), |
| 3383 | .n_type = macho.N_FUN, |
| 3384 | .n_sect = sym.n_sect, |
| 3385 | .n_desc = 0, |
| 3386 | .n_value = sym.n_value, |
| 3387 | }; |
| 3388 | buf[2] = .{ |
| 3389 | .n_strx = 0, |
| 3390 | .n_type = macho.N_FUN, |
| 3391 | .n_sect = 0, |
| 3392 | .n_desc = 0, |
| 3393 | .n_value = size, |
| 3394 | }; |
| 3395 | buf[3] = .{ |
| 3396 | .n_strx = 0, |
| 3397 | .n_type = macho.N_ENSYM, |
| 3398 | .n_sect = sym.n_sect, |
| 3399 | .n_desc = 0, |
| 3400 | .n_value = size, |
| 3401 | }; |
| 3402 | |
| 3403 | return buf; |
| 3404 | } |
| 3405 | |
| 3406 | fn logSegments(self: *Zld) void { |
| 3407 | log.debug("segments:", .{}); |
| 3408 | for (self.segments.items) |segment, i| { |
| 3409 | log.debug(" segment({d}): {s} @{x} ({x}), sizeof({x})", .{ |
| 3410 | i, |
| 3411 | segment.segName(), |
| 3412 | segment.fileoff, |
| 3413 | segment.vmaddr, |
| 3414 | segment.vmsize, |
| 3415 | }); |
| 3416 | } |
| 3417 | } |
| 3418 | |
| 3419 | fn logSections(self: *Zld) void { |
| 3420 | log.debug("sections:", .{}); |
| 3421 | for (self.sections.items(.header)) |header, i| { |
| 3422 | log.debug(" sect({d}): {s},{s} @{x} ({x}), sizeof({x})", .{ |
| 3423 | i + 1, |
| 3424 | header.segName(), |
| 3425 | header.sectName(), |
| 3426 | header.offset, |
| 3427 | header.addr, |
| 3428 | header.size, |
| 3429 | }); |
| 3430 | } |
| 3431 | } |
| 3432 | |
| 3433 | fn logSymAttributes(sym: macho.nlist_64, buf: []u8) []const u8 { |
| 3434 | if (sym.sect()) { |
| 3435 | buf[0] = 's'; |
| 3436 | } |
| 3437 | if (sym.ext()) { |
| 3438 | if (sym.weakDef() or sym.pext()) { |
| 3439 | buf[1] = 'w'; |
| 3440 | } else { |
| 3441 | buf[1] = 'e'; |
| 3442 | } |
| 3443 | } |
| 3444 | if (sym.tentative()) { |
| 3445 | buf[2] = 't'; |
| 3446 | } |
| 3447 | if (sym.undf()) { |
| 3448 | buf[3] = 'u'; |
| 3449 | } |
| 3450 | return buf[0..]; |
| 3451 | } |
| 3452 | |
| 3453 | fn logSymtab(self: *Zld) void { |
| 3454 | var buf: [4]u8 = undefined; |
| 3455 | |
| 3456 | const scoped_log = std.log.scoped(.symtab); |
| 3457 | |
| 3458 | scoped_log.debug("locals:", .{}); |
| 3459 | for (self.objects.items) |object, id| { |
| 3460 | scoped_log.debug(" object({d}): {s}", .{ id, object.name }); |
| 3461 | for (object.symtab) |sym, sym_id| { |
| 3462 | mem.set(u8, &buf, '_'); |
| 3463 | scoped_log.debug(" %{d}: {s} @{x} in sect({d}), {s}", .{ |
| 3464 | sym_id, |
| 3465 | object.getSymbolName(@intCast(u32, sym_id)), |
| 3466 | sym.n_value, |
| 3467 | sym.n_sect, |
| 3468 | logSymAttributes(sym, &buf), |
| 3469 | }); |
| 3470 | } |
| 3471 | } |
| 3472 | scoped_log.debug(" object(null)", .{}); |
| 3473 | for (self.locals.items) |sym, sym_id| { |
| 3474 | if (sym.undf()) continue; |
| 3475 | scoped_log.debug(" %{d}: {s} @{x} in sect({d}), {s}", .{ |
| 3476 | sym_id, |
| 3477 | self.strtab.get(sym.n_strx).?, |
| 3478 | sym.n_value, |
| 3479 | sym.n_sect, |
| 3480 | logSymAttributes(sym, &buf), |
| 3481 | }); |
| 3482 | } |
| 3483 | |
| 3484 | scoped_log.debug("exports:", .{}); |
| 3485 | for (self.globals.items) |global, i| { |
| 3486 | const sym = self.getSymbol(global); |
| 3487 | if (sym.undf()) continue; |
| 3488 | if (sym.n_desc == N_DEAD) continue; |
| 3489 | scoped_log.debug(" %{d}: {s} @{x} in sect({d}), {s} (def in object({?}))", .{ |
| 3490 | i, |
| 3491 | self.getSymbolName(global), |
| 3492 | sym.n_value, |
| 3493 | sym.n_sect, |
| 3494 | logSymAttributes(sym, &buf), |
| 3495 | global.file, |
| 3496 | }); |
| 3497 | } |
| 3498 | |
| 3499 | scoped_log.debug("imports:", .{}); |
| 3500 | for (self.globals.items) |global, i| { |
| 3501 | const sym = self.getSymbol(global); |
| 3502 | if (!sym.undf()) continue; |
| 3503 | if (sym.n_desc == N_DEAD) continue; |
| 3504 | const ord = @divTrunc(sym.n_desc, macho.N_SYMBOL_RESOLVER); |
| 3505 | scoped_log.debug(" %{d}: {s} @{x} in ord({d}), {s}", .{ |
| 3506 | i, |
| 3507 | self.getSymbolName(global), |
| 3508 | sym.n_value, |
| 3509 | ord, |
| 3510 | logSymAttributes(sym, &buf), |
| 3511 | }); |
| 3512 | } |
| 3513 | |
| 3514 | scoped_log.debug("GOT entries:", .{}); |
| 3515 | for (self.got_entries.items) |entry, i| { |
| 3516 | const atom_sym = entry.getAtomSymbol(self); |
| 3517 | const target_sym = entry.getTargetSymbol(self); |
| 3518 | const target_sym_name = entry.getTargetSymbolName(self); |
| 3519 | if (target_sym.undf()) { |
| 3520 | scoped_log.debug(" {d}@{x} => import('{s}')", .{ |
| 3521 | i, |
| 3522 | atom_sym.n_value, |
| 3523 | target_sym_name, |
| 3524 | }); |
| 3525 | } else { |
| 3526 | scoped_log.debug(" {d}@{x} => local(%{d}) in object({?}) {s}", .{ |
| 3527 | i, |
| 3528 | atom_sym.n_value, |
| 3529 | entry.target.sym_index, |
| 3530 | entry.target.file, |
| 3531 | logSymAttributes(target_sym, buf[0..4]), |
| 3532 | }); |
| 3533 | } |
| 3534 | } |
| 3535 | |
| 3536 | scoped_log.debug("__thread_ptrs entries:", .{}); |
| 3537 | for (self.tlv_ptr_entries.items) |entry, i| { |
| 3538 | const atom_sym = entry.getAtomSymbol(self); |
| 3539 | const target_sym = entry.getTargetSymbol(self); |
| 3540 | const target_sym_name = entry.getTargetSymbolName(self); |
| 3541 | assert(target_sym.undf()); |
| 3542 | scoped_log.debug(" {d}@{x} => import('{s}')", .{ |
| 3543 | i, |
| 3544 | atom_sym.n_value, |
| 3545 | target_sym_name, |
| 3546 | }); |
| 3547 | } |
| 3548 | |
| 3549 | scoped_log.debug("stubs entries:", .{}); |
| 3550 | for (self.stubs.items) |entry, i| { |
| 3551 | const atom_sym = entry.getAtomSymbol(self); |
| 3552 | const target_sym = entry.getTargetSymbol(self); |
| 3553 | const target_sym_name = entry.getTargetSymbolName(self); |
| 3554 | assert(target_sym.undf()); |
| 3555 | scoped_log.debug(" {d}@{x} => import('{s}')", .{ |
| 3556 | i, |
| 3557 | atom_sym.n_value, |
| 3558 | target_sym_name, |
| 3559 | }); |
| 3560 | } |
| 3561 | |
| 3562 | scoped_log.debug("thunks:", .{}); |
| 3563 | for (self.thunks.items) |thunk, i| { |
| 3564 | scoped_log.debug(" thunk({d})", .{i}); |
| 3565 | for (thunk.lookup.keys()) |target, j| { |
| 3566 | const target_sym = self.getSymbol(target); |
| 3567 | const atom = self.getAtom(thunk.lookup.get(target).?); |
| 3568 | const atom_sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 3569 | scoped_log.debug(" {d}@{x} => thunk('{s}'@{x})", .{ |
| 3570 | j, |
| 3571 | atom_sym.n_value, |
| 3572 | self.getSymbolName(target), |
| 3573 | target_sym.n_value, |
| 3574 | }); |
| 3575 | } |
| 3576 | } |
| 3577 | } |
| 3578 | |
| 3579 | fn logAtoms(self: *Zld) void { |
| 3580 | log.debug("atoms:", .{}); |
| 3581 | const slice = self.sections.slice(); |
| 3582 | for (slice.items(.first_atom_index)) |first_atom_index, sect_id| { |
| 3583 | var atom_index = first_atom_index; |
| 3584 | const header = slice.items(.header)[sect_id]; |
| 3585 | |
| 3586 | log.debug("{s},{s}", .{ header.segName(), header.sectName() }); |
| 3587 | |
| 3588 | while (true) { |
| 3589 | const atom = self.getAtom(atom_index); |
| 3590 | self.logAtom(atom_index, log); |
| 3591 | |
| 3592 | if (atom.next_index) |next_index| { |
| 3593 | atom_index = next_index; |
| 3594 | } else break; |
| 3595 | } |
| 3596 | } |
| 3597 | } |
| 3598 | |
| 3599 | pub fn logAtom(self: *Zld, atom_index: AtomIndex, logger: anytype) void { |
| 3600 | if (!build_options.enable_logging) return; |
| 3601 | |
| 3602 | const atom = self.getAtom(atom_index); |
| 3603 | const sym = self.getSymbol(atom.getSymbolWithLoc()); |
| 3604 | const sym_name = self.getSymbolName(atom.getSymbolWithLoc()); |
| 3605 | logger.debug(" ATOM({d}, %{d}, '{s}') @ {x} (sizeof({x}), alignof({x})) in object({?}) in sect({d})", .{ |
| 3606 | atom_index, |
| 3607 | atom.sym_index, |
| 3608 | sym_name, |
| 3609 | sym.n_value, |
| 3610 | atom.size, |
| 3611 | atom.alignment, |
| 3612 | atom.file, |
| 3613 | sym.n_sect, |
| 3614 | }); |
| 3615 | |
| 3616 | if (atom.getFile()) |_| { |
| 3617 | var it = Atom.getInnerSymbolsIterator(self, atom_index); |
| 3618 | while (it.next()) |sym_loc| { |
| 3619 | const inner = self.getSymbol(sym_loc); |
| 3620 | const inner_name = self.getSymbolName(sym_loc); |
| 3621 | const offset = Atom.calcInnerSymbolOffset(self, atom_index, sym_loc.sym_index); |
| 3622 | |
| 3623 | logger.debug(" (%{d}, '{s}') @ {x} ({x})", .{ |
| 3624 | sym_loc.sym_index, |
| 3625 | inner_name, |
| 3626 | inner.n_value, |
| 3627 | offset, |
| 3628 | }); |
| 3629 | } |
| 3630 | |
| 3631 | if (Atom.getSectionAlias(self, atom_index)) |sym_loc| { |
| 3632 | const alias = self.getSymbol(sym_loc); |
| 3633 | const alias_name = self.getSymbolName(sym_loc); |
| 3634 | |
| 3635 | logger.debug(" (%{d}, '{s}') @ {x} ({x})", .{ |
| 3636 | sym_loc.sym_index, |
| 3637 | alias_name, |
| 3638 | alias.n_value, |
| 3639 | 0, |
| 3640 | }); |
| 3641 | } |
| 3642 | } |
| 3643 | } |
| 3644 | }; |
| 3645 | |
| 3646 | pub const N_DEAD: u16 = @bitCast(u16, @as(i16, -1)); |
| 3647 | |
| 3648 | const Section = struct { |
| 3649 | header: macho.section_64, |
| 3650 | segment_index: u8, |
| 3651 | first_atom_index: AtomIndex, |
| 3652 | last_atom_index: AtomIndex, |
| 3653 | }; |
| 3654 | |
| 3655 | pub const AtomIndex = u32; |
| 3656 | |
| 3657 | const IndirectPointer = struct { |
| 3658 | target: SymbolWithLoc, |
| 3659 | atom_index: AtomIndex, |
| 3660 | |
| 3661 | pub fn getTargetSymbol(self: @This(), zld: *Zld) macho.nlist_64 { |
| 3662 | return zld.getSymbol(self.target); |
| 3663 | } |
| 3664 | |
| 3665 | pub fn getTargetSymbolName(self: @This(), zld: *Zld) []const u8 { |
| 3666 | return zld.getSymbolName(self.target); |
| 3667 | } |
| 3668 | |
| 3669 | pub fn getAtomSymbol(self: @This(), zld: *Zld) macho.nlist_64 { |
| 3670 | const atom = zld.getAtom(self.atom_index); |
| 3671 | return zld.getSymbol(atom.getSymbolWithLoc()); |
| 3672 | } |
| 3673 | }; |
| 3674 | |
| 3675 | pub const SymbolWithLoc = struct { |
| 3676 | // Index into the respective symbol table. |
| 3677 | sym_index: u32, |
| 3678 | |
| 3679 | // -1 means it's a synthetic global. |
| 3680 | file: i32 = -1, |
| 3681 | |
| 3682 | pub inline fn getFile(self: SymbolWithLoc) ?u31 { |
| 3683 | if (self.file == -1) return null; |
| 3684 | return @intCast(u31, self.file); |
| 3685 | } |
| 3686 | |
| 3687 | pub inline fn eql(self: SymbolWithLoc, other: SymbolWithLoc) bool { |
| 3688 | return self.file == other.file and self.sym_index == other.sym_index; |
| 3689 | } |
| 3690 | }; |
| 3691 | |
| 3692 | const SymbolResolver = struct { |
| 3693 | arena: Allocator, |
| 3694 | table: std.StringHashMap(u32), |
| 3695 | unresolved: std.AutoArrayHashMap(u32, void), |
| 3696 | }; |
| 3697 | |
| 3698 | pub fn linkWithZld(macho_file: *MachO, comp: *Compilation, prog_node: *std.Progress.Node) !void { |
| 3699 | const tracy = trace(@src()); |
| 3700 | defer tracy.end(); |
| 3701 | |
| 3702 | const gpa = macho_file.base.allocator; |
| 3703 | const options = macho_file.base.options; |
| 3704 | const target = options.target; |
| 3705 | |
| 3706 | var arena_allocator = std.heap.ArenaAllocator.init(gpa); |
| 3707 | defer arena_allocator.deinit(); |
| 3708 | const arena = arena_allocator.allocator(); |
| 3709 | |
| 3710 | const directory = options.emit.?.directory; // Just an alias to make it shorter to type. |
| 3711 | const full_out_path = try directory.join(arena, &[_][]const u8{options.emit.?.sub_path}); |
| 3712 | |
| 3713 | // If there is no Zig code to compile, then we should skip flushing the output file because it |
| 3714 | // will not be part of the linker line anyway. |
| 3715 | const module_obj_path: ?[]const u8 = if (options.module) |module| blk: { |
| 3716 | if (options.use_stage1) { |
| 3717 | const obj_basename = try std.zig.binNameAlloc(arena, .{ |
| 3718 | .root_name = options.root_name, |
| 3719 | .target = target, |
| 3720 | .output_mode = .Obj, |
| 3721 | }); |
| 3722 | switch (options.cache_mode) { |
| 3723 | .incremental => break :blk try module.zig_cache_artifact_directory.join( |
| 3724 | arena, |
| 3725 | &[_][]const u8{obj_basename}, |
| 3726 | ), |
| 3727 | .whole => break :blk try fs.path.join(arena, &.{ |
| 3728 | fs.path.dirname(full_out_path).?, obj_basename, |
| 3729 | }), |
| 3730 | } |
| 3731 | } |
| 3732 | |
| 3733 | try macho_file.flushModule(comp, prog_node); |
| 3734 | |
| 3735 | if (fs.path.dirname(full_out_path)) |dirname| { |
| 3736 | break :blk try fs.path.join(arena, &.{ dirname, macho_file.base.intermediary_basename.? }); |
| 3737 | } else { |
| 3738 | break :blk macho_file.base.intermediary_basename.?; |
| 3739 | } |
| 3740 | } else null; |
| 3741 | |
| 3742 | var sub_prog_node = prog_node.start("MachO Flush", 0); |
| 3743 | sub_prog_node.activate(); |
| 3744 | sub_prog_node.context.refresh(); |
| 3745 | defer sub_prog_node.end(); |
| 3746 | |
| 3747 | const cpu_arch = target.cpu.arch; |
| 3748 | const os_tag = target.os.tag; |
| 3749 | const abi = target.abi; |
| 3750 | const is_lib = options.output_mode == .Lib; |
| 3751 | const is_dyn_lib = options.link_mode == .Dynamic and is_lib; |
| 3752 | const is_exe_or_dyn_lib = is_dyn_lib or options.output_mode == .Exe; |
| 3753 | const stack_size = options.stack_size_override orelse 0; |
| 3754 | const is_debug_build = options.optimize_mode == .Debug; |
| 3755 | const gc_sections = options.gc_sections orelse !is_debug_build; |
| 3756 | |
| 3757 | const id_symlink_basename = "zld.id"; |
| 3758 | |
| 3759 | var man: Cache.Manifest = undefined; |
| 3760 | defer if (!options.disable_lld_caching) man.deinit(); |
| 3761 | |
| 3762 | var digest: [Cache.hex_digest_len]u8 = undefined; |
| 3763 | |
| 3764 | if (!options.disable_lld_caching) { |
| 3765 | man = comp.cache_parent.obtain(); |
| 3766 | |
| 3767 | // We are about to obtain this lock, so here we give other processes a chance first. |
| 3768 | macho_file.base.releaseLock(); |
| 3769 | |
| 3770 | comptime assert(Compilation.link_hash_implementation_version == 7); |
| 3771 | |
| 3772 | for (options.objects) |obj| { |
| 3773 | _ = try man.addFile(obj.path, null); |
| 3774 | man.hash.add(obj.must_link); |
| 3775 | } |
| 3776 | for (comp.c_object_table.keys()) |key| { |
| 3777 | _ = try man.addFile(key.status.success.object_path, null); |
| 3778 | } |
| 3779 | try man.addOptionalFile(module_obj_path); |
| 3780 | // We can skip hashing libc and libc++ components that we are in charge of building from Zig |
| 3781 | // installation sources because they are always a product of the compiler version + target information. |
| 3782 | man.hash.add(stack_size); |
| 3783 | man.hash.addOptional(options.pagezero_size); |
| 3784 | man.hash.addOptional(options.search_strategy); |
| 3785 | man.hash.addOptional(options.headerpad_size); |
| 3786 | man.hash.add(options.headerpad_max_install_names); |
| 3787 | man.hash.add(gc_sections); |
| 3788 | man.hash.add(options.dead_strip_dylibs); |
| 3789 | man.hash.add(options.strip); |
| 3790 | man.hash.addListOfBytes(options.lib_dirs); |
| 3791 | man.hash.addListOfBytes(options.framework_dirs); |
| 3792 | link.hashAddSystemLibs(&man.hash, options.frameworks); |
| 3793 | man.hash.addListOfBytes(options.rpath_list); |
| 3794 | if (is_dyn_lib) { |
| 3795 | man.hash.addOptionalBytes(options.install_name); |
| 3796 | man.hash.addOptional(options.version); |
| 3797 | } |
| 3798 | link.hashAddSystemLibs(&man.hash, options.system_libs); |
| 3799 | man.hash.addOptionalBytes(options.sysroot); |
| 3800 | try man.addOptionalFile(options.entitlements); |
| 3801 | |
| 3802 | // We don't actually care whether it's a cache hit or miss; we just need the digest and the lock. |
| 3803 | _ = try man.hit(); |
| 3804 | digest = man.final(); |
| 3805 | |
| 3806 | var prev_digest_buf: [digest.len]u8 = undefined; |
| 3807 | const prev_digest: []u8 = Cache.readSmallFile( |
| 3808 | directory.handle, |
| 3809 | id_symlink_basename, |
| 3810 | &prev_digest_buf, |
| 3811 | ) catch |err| blk: { |
| 3812 | log.debug("MachO Zld new_digest={s} error: {s}", .{ |
| 3813 | std.fmt.fmtSliceHexLower(&digest), |
| 3814 | @errorName(err), |
| 3815 | }); |
| 3816 | // Handle this as a cache miss. |
| 3817 | break :blk prev_digest_buf[0..0]; |
| 3818 | }; |
| 3819 | if (mem.eql(u8, prev_digest, &digest)) { |
| 3820 | // Hot diggity dog! The output binary is already there. |
| 3821 | log.debug("MachO Zld digest={s} match - skipping invocation", .{ |
| 3822 | std.fmt.fmtSliceHexLower(&digest), |
| 3823 | }); |
| 3824 | macho_file.base.lock = man.toOwnedLock(); |
| 3825 | return; |
| 3826 | } |
| 3827 | log.debug("MachO Zld prev_digest={s} new_digest={s}", .{ |
| 3828 | std.fmt.fmtSliceHexLower(prev_digest), |
| 3829 | std.fmt.fmtSliceHexLower(&digest), |
| 3830 | }); |
| 3831 | |
| 3832 | // We are about to change the output file to be different, so we invalidate the build hash now. |
| 3833 | directory.handle.deleteFile(id_symlink_basename) catch |err| switch (err) { |
| 3834 | error.FileNotFound => {}, |
| 3835 | else => |e| return e, |
| 3836 | }; |
| 3837 | } |
| 3838 | |
| 3839 | if (options.output_mode == .Obj) { |
| 3840 | // LLD's MachO driver does not support the equivalent of `-r` so we do a simple file copy |
| 3841 | // here. TODO: think carefully about how we can avoid this redundant operation when doing |
| 3842 | // build-obj. See also the corresponding TODO in linkAsArchive. |
| 3843 | const the_object_path = blk: { |
| 3844 | if (options.objects.len != 0) { |
| 3845 | break :blk options.objects[0].path; |
| 3846 | } |
| 3847 | |
| 3848 | if (comp.c_object_table.count() != 0) |
| 3849 | break :blk comp.c_object_table.keys()[0].status.success.object_path; |
| 3850 | |
| 3851 | if (module_obj_path) |p| |
| 3852 | break :blk p; |
| 3853 | |
| 3854 | // TODO I think this is unreachable. Audit this situation when solving the above TODO |
| 3855 | // regarding eliding redundant object -> object transformations. |
| 3856 | return error.NoObjectsToLink; |
| 3857 | }; |
| 3858 | // This can happen when using --enable-cache and using the stage1 backend. In this case |
| 3859 | // we can skip the file copy. |
| 3860 | if (!mem.eql(u8, the_object_path, full_out_path)) { |
| 3861 | try fs.cwd().copyFile(the_object_path, fs.cwd(), full_out_path, .{}); |
| 3862 | } |
| 3863 | } else { |
| 3864 | const page_size = macho_file.page_size; |
| 3865 | const sub_path = options.emit.?.sub_path; |
| 3866 | if (macho_file.base.file == null) { |
| 3867 | macho_file.base.file = try directory.handle.createFile(sub_path, .{ |
| 3868 | .truncate = true, |
| 3869 | .read = true, |
| 3870 | .mode = link.determineMode(options), |
| 3871 | }); |
| 3872 | } |
| 3873 | var zld = Zld{ |
| 3874 | .gpa = gpa, |
| 3875 | .file = macho_file.base.file.?, |
| 3876 | .page_size = macho_file.page_size, |
| 3877 | .options = options, |
| 3878 | }; |
| 3879 | defer zld.deinit(); |
| 3880 | |
| 3881 | try zld.atoms.append(gpa, Atom.empty); // AtomIndex at 0 is reserved as null atom |
| 3882 | try zld.strtab.buffer.append(gpa, 0); |
| 3883 | |
| 3884 | var lib_not_found = false; |
| 3885 | var framework_not_found = false; |
| 3886 | |
| 3887 | // Positional arguments to the linker such as object files and static archives. |
| 3888 | var positionals = std.ArrayList([]const u8).init(arena); |
| 3889 | try positionals.ensureUnusedCapacity(options.objects.len); |
| 3890 | |
| 3891 | var must_link_archives = std.StringArrayHashMap(void).init(arena); |
| 3892 | try must_link_archives.ensureUnusedCapacity(options.objects.len); |
| 3893 | |
| 3894 | for (options.objects) |obj| { |
| 3895 | if (must_link_archives.contains(obj.path)) continue; |
| 3896 | if (obj.must_link) { |
| 3897 | _ = must_link_archives.getOrPutAssumeCapacity(obj.path); |
| 3898 | } else { |
| 3899 | _ = positionals.appendAssumeCapacity(obj.path); |
| 3900 | } |
| 3901 | } |
| 3902 | |
| 3903 | for (comp.c_object_table.keys()) |key| { |
| 3904 | try positionals.append(key.status.success.object_path); |
| 3905 | } |
| 3906 | |
| 3907 | if (module_obj_path) |p| { |
| 3908 | try positionals.append(p); |
| 3909 | } |
| 3910 | |
| 3911 | if (comp.compiler_rt_lib) |lib| { |
| 3912 | try positionals.append(lib.full_object_path); |
| 3913 | } |
| 3914 | |
| 3915 | // libc++ dep |
| 3916 | if (options.link_libcpp) { |
| 3917 | try positionals.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 3918 | try positionals.append(comp.libcxx_static_lib.?.full_object_path); |
| 3919 | } |
| 3920 | |
| 3921 | // Shared and static libraries passed via `-l` flag. |
| 3922 | var candidate_libs = std.StringArrayHashMap(link.SystemLib).init(arena); |
| 3923 | |
| 3924 | const system_lib_names = options.system_libs.keys(); |
| 3925 | for (system_lib_names) |system_lib_name| { |
| 3926 | // By this time, we depend on these libs being dynamically linked libraries and not static libraries |
| 3927 | // (the check for that needs to be earlier), but they could be full paths to .dylib files, in which |
| 3928 | // case we want to avoid prepending "-l". |
| 3929 | if (Compilation.classifyFileExt(system_lib_name) == .shared_library) { |
| 3930 | try positionals.append(system_lib_name); |
| 3931 | continue; |
| 3932 | } |
| 3933 | |
| 3934 | const system_lib_info = options.system_libs.get(system_lib_name).?; |
| 3935 | try candidate_libs.put(system_lib_name, .{ |
| 3936 | .needed = system_lib_info.needed, |
| 3937 | .weak = system_lib_info.weak, |
| 3938 | }); |
| 3939 | } |
| 3940 | |
| 3941 | var lib_dirs = std.ArrayList([]const u8).init(arena); |
| 3942 | for (options.lib_dirs) |dir| { |
| 3943 | if (try MachO.resolveSearchDir(arena, dir, options.sysroot)) |search_dir| { |
| 3944 | try lib_dirs.append(search_dir); |
| 3945 | } else { |
| 3946 | log.warn("directory not found for '-L{s}'", .{dir}); |
| 3947 | } |
| 3948 | } |
| 3949 | |
| 3950 | var libs = std.StringArrayHashMap(link.SystemLib).init(arena); |
| 3951 | |
| 3952 | // Assume ld64 default -search_paths_first if no strategy specified. |
| 3953 | const search_strategy = options.search_strategy orelse .paths_first; |
| 3954 | outer: for (candidate_libs.keys()) |lib_name| { |
| 3955 | switch (search_strategy) { |
| 3956 | .paths_first => { |
| 3957 | // Look in each directory for a dylib (stub first), and then for archive |
| 3958 | for (lib_dirs.items) |dir| { |
| 3959 | for (&[_][]const u8{ ".tbd", ".dylib", ".a" }) |ext| { |
| 3960 | if (try MachO.resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 3961 | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 3962 | continue :outer; |
| 3963 | } |
| 3964 | } |
| 3965 | } else { |
| 3966 | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 3967 | lib_not_found = true; |
| 3968 | } |
| 3969 | }, |
| 3970 | .dylibs_first => { |
| 3971 | // First, look for a dylib in each search dir |
| 3972 | for (lib_dirs.items) |dir| { |
| 3973 | for (&[_][]const u8{ ".tbd", ".dylib" }) |ext| { |
| 3974 | if (try MachO.resolveLib(arena, dir, lib_name, ext)) |full_path| { |
| 3975 | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 3976 | continue :outer; |
| 3977 | } |
| 3978 | } |
| 3979 | } else for (lib_dirs.items) |dir| { |
| 3980 | if (try MachO.resolveLib(arena, dir, lib_name, ".a")) |full_path| { |
| 3981 | try libs.put(full_path, candidate_libs.get(lib_name).?); |
| 3982 | } else { |
| 3983 | log.warn("library not found for '-l{s}'", .{lib_name}); |
| 3984 | lib_not_found = true; |
| 3985 | } |
| 3986 | } |
| 3987 | }, |
| 3988 | } |
| 3989 | } |
| 3990 | |
| 3991 | if (lib_not_found) { |
| 3992 | log.warn("Library search paths:", .{}); |
| 3993 | for (lib_dirs.items) |dir| { |
| 3994 | log.warn(" {s}", .{dir}); |
| 3995 | } |
| 3996 | } |
| 3997 | |
| 3998 | try MachO.resolveLibSystem(arena, comp, options.sysroot, target, lib_dirs.items, &libs); |
| 3999 | |
| 4000 | // frameworks |
| 4001 | var framework_dirs = std.ArrayList([]const u8).init(arena); |
| 4002 | for (options.framework_dirs) |dir| { |
| 4003 | if (try MachO.resolveSearchDir(arena, dir, options.sysroot)) |search_dir| { |
| 4004 | try framework_dirs.append(search_dir); |
| 4005 | } else { |
| 4006 | log.warn("directory not found for '-F{s}'", .{dir}); |
| 4007 | } |
| 4008 | } |
| 4009 | |
| 4010 | outer: for (options.frameworks.keys()) |f_name| { |
| 4011 | for (framework_dirs.items) |dir| { |
| 4012 | for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| { |
| 4013 | if (try MachO.resolveFramework(arena, dir, f_name, ext)) |full_path| { |
| 4014 | const info = options.frameworks.get(f_name).?; |
| 4015 | try libs.put(full_path, .{ |
| 4016 | .needed = info.needed, |
| 4017 | .weak = info.weak, |
| 4018 | }); |
| 4019 | continue :outer; |
| 4020 | } |
| 4021 | } |
| 4022 | } else { |
| 4023 | log.warn("framework not found for '-framework {s}'", .{f_name}); |
| 4024 | framework_not_found = true; |
| 4025 | } |
| 4026 | } |
| 4027 | |
| 4028 | if (framework_not_found) { |
| 4029 | log.warn("Framework search paths:", .{}); |
| 4030 | for (framework_dirs.items) |dir| { |
| 4031 | log.warn(" {s}", .{dir}); |
| 4032 | } |
| 4033 | } |
| 4034 | |
| 4035 | if (options.verbose_link) { |
| 4036 | var argv = std.ArrayList([]const u8).init(arena); |
| 4037 | |
| 4038 | try argv.append("zig"); |
| 4039 | try argv.append("ld"); |
| 4040 | |
| 4041 | if (is_exe_or_dyn_lib) { |
| 4042 | try argv.append("-dynamic"); |
| 4043 | } |
| 4044 | |
| 4045 | if (is_dyn_lib) { |
| 4046 | try argv.append("-dylib"); |
| 1326 | 4047 | |
| 1327 | | var offsets = std.ArrayList(u32).init(gpa); |
| 1328 | | defer offsets.deinit(); |
| 1329 | | try offsets.ensureTotalCapacityPrecise(addresses.items.len); |
| 4048 | if (options.install_name) |install_name| { |
| 4049 | try argv.append("-install_name"); |
| 4050 | try argv.append(install_name); |
| 4051 | } |
| 4052 | } |
| 1330 | 4053 | |
| 1331 | | var last_off: u32 = 0; |
| 1332 | | for (addresses.items) |addr| { |
| 1333 | | const offset = @intCast(u32, addr - text_seg.vmaddr); |
| 1334 | | const diff = offset - last_off; |
| 4054 | if (options.sysroot) |syslibroot| { |
| 4055 | try argv.append("-syslibroot"); |
| 4056 | try argv.append(syslibroot); |
| 4057 | } |
| 1335 | 4058 | |
| 1336 | | if (diff == 0) continue; |
| 4059 | for (options.rpath_list) |rpath| { |
| 4060 | try argv.append("-rpath"); |
| 4061 | try argv.append(rpath); |
| 4062 | } |
| 1337 | 4063 | |
| 1338 | | offsets.appendAssumeCapacity(diff); |
| 1339 | | last_off = offset; |
| 1340 | | } |
| 4064 | if (options.pagezero_size) |pagezero_size| { |
| 4065 | try argv.append("-pagezero_size"); |
| 4066 | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{pagezero_size})); |
| 4067 | } |
| 1341 | 4068 | |
| 1342 | | var buffer = std.ArrayList(u8).init(gpa); |
| 1343 | | defer buffer.deinit(); |
| 4069 | if (options.search_strategy) |strat| switch (strat) { |
| 4070 | .paths_first => try argv.append("-search_paths_first"), |
| 4071 | .dylibs_first => try argv.append("-search_dylibs_first"), |
| 4072 | }; |
| 1344 | 4073 | |
| 1345 | | const max_size = @intCast(usize, offsets.items.len * @sizeOf(u64)); |
| 1346 | | try buffer.ensureTotalCapacity(max_size); |
| 4074 | if (options.headerpad_size) |headerpad_size| { |
| 4075 | try argv.append("-headerpad_size"); |
| 4076 | try argv.append(try std.fmt.allocPrint(arena, "0x{x}", .{headerpad_size})); |
| 4077 | } |
| 1347 | 4078 | |
| 1348 | | for (offsets.items) |offset| { |
| 1349 | | try std.leb.writeULEB128(buffer.writer(), offset); |
| 1350 | | } |
| 4079 | if (options.headerpad_max_install_names) { |
| 4080 | try argv.append("-headerpad_max_install_names"); |
| 4081 | } |
| 1351 | 4082 | |
| 1352 | | const link_seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 1353 | | const offset = mem.alignForwardGeneric(u64, link_seg.fileoff + link_seg.filesize, @alignOf(u64)); |
| 1354 | | const needed_size = buffer.items.len; |
| 1355 | | link_seg.filesize = offset + needed_size - link_seg.fileoff; |
| 4083 | if (gc_sections) { |
| 4084 | try argv.append("-dead_strip"); |
| 4085 | } |
| 1356 | 4086 | |
| 1357 | | log.debug("writing function starts info from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 4087 | if (options.dead_strip_dylibs) { |
| 4088 | try argv.append("-dead_strip_dylibs"); |
| 4089 | } |
| 1358 | 4090 | |
| 1359 | | try macho_file.base.file.?.pwriteAll(buffer.items, offset); |
| 4091 | if (options.entry) |entry| { |
| 4092 | try argv.append("-e"); |
| 4093 | try argv.append(entry); |
| 4094 | } |
| 1360 | 4095 | |
| 1361 | | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 1362 | | .cmd = .FUNCTION_STARTS, |
| 1363 | | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| 1364 | | .dataoff = @intCast(u32, offset), |
| 1365 | | .datasize = @intCast(u32, needed_size), |
| 1366 | | }); |
| 1367 | | ncmds.* += 1; |
| 1368 | | } |
| 4096 | for (options.objects) |obj| { |
| 4097 | try argv.append(obj.path); |
| 4098 | } |
| 1369 | 4099 | |
| 1370 | | fn filterDataInCode( |
| 1371 | | dices: []align(1) const macho.data_in_code_entry, |
| 1372 | | start_addr: u64, |
| 1373 | | end_addr: u64, |
| 1374 | | ) []align(1) const macho.data_in_code_entry { |
| 1375 | | const Predicate = struct { |
| 1376 | | addr: u64, |
| 4100 | for (comp.c_object_table.keys()) |key| { |
| 4101 | try argv.append(key.status.success.object_path); |
| 4102 | } |
| 1377 | 4103 | |
| 1378 | | pub fn predicate(macho_file: @This(), dice: macho.data_in_code_entry) bool { |
| 1379 | | return dice.offset >= macho_file.addr; |
| 1380 | | } |
| 1381 | | }; |
| 4104 | if (module_obj_path) |p| { |
| 4105 | try argv.append(p); |
| 4106 | } |
| 1382 | 4107 | |
| 1383 | | const start = MachO.findFirst(macho.data_in_code_entry, dices, 0, Predicate{ .addr = start_addr }); |
| 1384 | | const end = MachO.findFirst(macho.data_in_code_entry, dices, start, Predicate{ .addr = end_addr }); |
| 4108 | if (comp.compiler_rt_lib) |lib| { |
| 4109 | try argv.append(lib.full_object_path); |
| 4110 | } |
| 1385 | 4111 | |
| 1386 | | return dices[start..end]; |
| 1387 | | } |
| 4112 | if (options.link_libcpp) { |
| 4113 | try argv.append(comp.libcxxabi_static_lib.?.full_object_path); |
| 4114 | try argv.append(comp.libcxx_static_lib.?.full_object_path); |
| 4115 | } |
| 1388 | 4116 | |
| 1389 | | fn writeDataInCode(macho_file: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 1390 | | const tracy = trace(@src()); |
| 1391 | | defer tracy.end(); |
| 4117 | try argv.append("-o"); |
| 4118 | try argv.append(full_out_path); |
| 1392 | 4119 | |
| 1393 | | var out_dice = std.ArrayList(macho.data_in_code_entry).init(macho_file.base.allocator); |
| 1394 | | defer out_dice.deinit(); |
| 4120 | try argv.append("-lSystem"); |
| 4121 | try argv.append("-lc"); |
| 1395 | 4122 | |
| 1396 | | const text_sect_id = macho_file.text_section_index orelse return; |
| 1397 | | const text_sect_header = macho_file.sections.items(.header)[text_sect_id]; |
| 4123 | for (options.system_libs.keys()) |l_name| { |
| 4124 | const info = options.system_libs.get(l_name).?; |
| 4125 | const arg = if (info.needed) |
| 4126 | try std.fmt.allocPrint(arena, "-needed-l{s}", .{l_name}) |
| 4127 | else if (info.weak) |
| 4128 | try std.fmt.allocPrint(arena, "-weak-l{s}", .{l_name}) |
| 4129 | else |
| 4130 | try std.fmt.allocPrint(arena, "-l{s}", .{l_name}); |
| 4131 | try argv.append(arg); |
| 4132 | } |
| 1398 | 4133 | |
| 1399 | | for (macho_file.objects.items) |object| { |
| 1400 | | const dice = object.parseDataInCode() orelse continue; |
| 1401 | | try out_dice.ensureUnusedCapacity(dice.len); |
| 4134 | for (options.lib_dirs) |lib_dir| { |
| 4135 | try argv.append(try std.fmt.allocPrint(arena, "-L{s}", .{lib_dir})); |
| 4136 | } |
| 1402 | 4137 | |
| 1403 | | for (object.managed_atoms.items) |atom| { |
| 1404 | | const sym = atom.getSymbol(macho_file); |
| 1405 | | if (sym.n_desc == MachO.N_DESC_GCED) continue; |
| 4138 | for (options.frameworks.keys()) |framework| { |
| 4139 | const info = options.frameworks.get(framework).?; |
| 4140 | const arg = if (info.needed) |
| 4141 | try std.fmt.allocPrint(arena, "-needed_framework {s}", .{framework}) |
| 4142 | else if (info.weak) |
| 4143 | try std.fmt.allocPrint(arena, "-weak_framework {s}", .{framework}) |
| 4144 | else |
| 4145 | try std.fmt.allocPrint(arena, "-framework {s}", .{framework}); |
| 4146 | try argv.append(arg); |
| 4147 | } |
| 1406 | 4148 | |
| 1407 | | const sect_id = sym.n_sect - 1; |
| 1408 | | if (sect_id != macho_file.text_section_index.?) { |
| 1409 | | continue; |
| 4149 | for (options.framework_dirs) |framework_dir| { |
| 4150 | try argv.append(try std.fmt.allocPrint(arena, "-F{s}", .{framework_dir})); |
| 1410 | 4151 | } |
| 1411 | 4152 | |
| 1412 | | const source_sym = object.getSourceSymbol(atom.sym_index) orelse continue; |
| 1413 | | const source_addr = math.cast(u32, source_sym.n_value) orelse return error.Overflow; |
| 1414 | | const filtered_dice = filterDataInCode(dice, source_addr, source_addr + atom.size); |
| 1415 | | const base = math.cast(u32, sym.n_value - text_sect_header.addr + text_sect_header.offset) orelse |
| 1416 | | return error.Overflow; |
| 4153 | if (is_dyn_lib and (options.allow_shlib_undefined orelse false)) { |
| 4154 | try argv.append("-undefined"); |
| 4155 | try argv.append("dynamic_lookup"); |
| 4156 | } |
| 1417 | 4157 | |
| 1418 | | for (filtered_dice) |single| { |
| 1419 | | const offset = single.offset - source_addr + base; |
| 1420 | | out_dice.appendAssumeCapacity(.{ |
| 1421 | | .offset = offset, |
| 1422 | | .length = single.length, |
| 1423 | | .kind = single.kind, |
| 1424 | | }); |
| 4158 | for (must_link_archives.keys()) |lib| { |
| 4159 | try argv.append(try std.fmt.allocPrint(arena, "-force_load {s}", .{lib})); |
| 1425 | 4160 | } |
| 4161 | |
| 4162 | Compilation.dump_argv(argv.items); |
| 1426 | 4163 | } |
| 1427 | | } |
| 1428 | 4164 | |
| 1429 | | const seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 1430 | | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 1431 | | const needed_size = out_dice.items.len * @sizeOf(macho.data_in_code_entry); |
| 1432 | | seg.filesize = offset + needed_size - seg.fileoff; |
| 4165 | var dependent_libs = std.fifo.LinearFifo(struct { |
| 4166 | id: Dylib.Id, |
| 4167 | parent: u16, |
| 4168 | }, .Dynamic).init(arena); |
| 1433 | 4169 | |
| 1434 | | log.debug("writing data-in-code from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 4170 | try zld.parseInputFiles(positionals.items, options.sysroot, &dependent_libs); |
| 4171 | try zld.parseAndForceLoadStaticArchives(must_link_archives.keys()); |
| 4172 | try zld.parseLibs(libs.keys(), libs.values(), options.sysroot, &dependent_libs); |
| 4173 | try zld.parseDependentLibs(options.sysroot, &dependent_libs); |
| 1435 | 4174 | |
| 1436 | | try macho_file.base.file.?.pwriteAll(mem.sliceAsBytes(out_dice.items), offset); |
| 1437 | | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 1438 | | .cmd = .DATA_IN_CODE, |
| 1439 | | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| 1440 | | .dataoff = @intCast(u32, offset), |
| 1441 | | .datasize = @intCast(u32, needed_size), |
| 1442 | | }); |
| 1443 | | ncmds.* += 1; |
| 1444 | | } |
| 4175 | var resolver = SymbolResolver{ |
| 4176 | .arena = arena, |
| 4177 | .table = std.StringHashMap(u32).init(arena), |
| 4178 | .unresolved = std.AutoArrayHashMap(u32, void).init(arena), |
| 4179 | }; |
| 1445 | 4180 | |
| 1446 | | fn writeSymtabs(macho_file: *MachO, ncmds: *u32, lc_writer: anytype) !void { |
| 1447 | | var symtab_cmd = macho.symtab_command{ |
| 1448 | | .cmdsize = @sizeOf(macho.symtab_command), |
| 1449 | | .symoff = 0, |
| 1450 | | .nsyms = 0, |
| 1451 | | .stroff = 0, |
| 1452 | | .strsize = 0, |
| 1453 | | }; |
| 1454 | | var dysymtab_cmd = macho.dysymtab_command{ |
| 1455 | | .cmdsize = @sizeOf(macho.dysymtab_command), |
| 1456 | | .ilocalsym = 0, |
| 1457 | | .nlocalsym = 0, |
| 1458 | | .iextdefsym = 0, |
| 1459 | | .nextdefsym = 0, |
| 1460 | | .iundefsym = 0, |
| 1461 | | .nundefsym = 0, |
| 1462 | | .tocoff = 0, |
| 1463 | | .ntoc = 0, |
| 1464 | | .modtaboff = 0, |
| 1465 | | .nmodtab = 0, |
| 1466 | | .extrefsymoff = 0, |
| 1467 | | .nextrefsyms = 0, |
| 1468 | | .indirectsymoff = 0, |
| 1469 | | .nindirectsyms = 0, |
| 1470 | | .extreloff = 0, |
| 1471 | | .nextrel = 0, |
| 1472 | | .locreloff = 0, |
| 1473 | | .nlocrel = 0, |
| 1474 | | }; |
| 1475 | | var ctx = try writeSymtab(macho_file, &symtab_cmd); |
| 1476 | | defer ctx.imports_table.deinit(); |
| 1477 | | try writeDysymtab(macho_file, ctx, &dysymtab_cmd); |
| 1478 | | try writeStrtab(macho_file, &symtab_cmd); |
| 1479 | | try lc_writer.writeStruct(symtab_cmd); |
| 1480 | | try lc_writer.writeStruct(dysymtab_cmd); |
| 1481 | | ncmds.* += 2; |
| 1482 | | } |
| 4181 | for (zld.objects.items) |_, object_id| { |
| 4182 | try zld.resolveSymbolsInObject(@intCast(u16, object_id), &resolver); |
| 4183 | } |
| 1483 | 4184 | |
| 1484 | | fn writeSymtab(macho_file: *MachO, lc: *macho.symtab_command) !SymtabCtx { |
| 1485 | | const gpa = macho_file.base.allocator; |
| 4185 | try zld.resolveSymbolsInArchives(&resolver); |
| 4186 | try zld.resolveDyldStubBinder(&resolver); |
| 4187 | try zld.resolveSymbolsInDylibs(&resolver); |
| 4188 | try zld.createMhExecuteHeaderSymbol(&resolver); |
| 4189 | try zld.createDsoHandleSymbol(&resolver); |
| 4190 | try zld.resolveSymbolsAtLoading(&resolver); |
| 1486 | 4191 | |
| 1487 | | var locals = std.ArrayList(macho.nlist_64).init(gpa); |
| 1488 | | defer locals.deinit(); |
| 1489 | | |
| 1490 | | for (macho_file.locals.items) |sym, sym_id| { |
| 1491 | | if (sym.n_strx == 0) continue; // no name, skip |
| 1492 | | if (sym.n_desc == MachO.N_DESC_GCED) continue; // GCed, skip |
| 1493 | | const sym_loc = SymbolWithLoc{ .sym_index = @intCast(u32, sym_id), .file = null }; |
| 1494 | | if (macho_file.symbolIsTemp(sym_loc)) continue; // local temp symbol, skip |
| 1495 | | if (macho_file.getGlobal(macho_file.getSymbolName(sym_loc)) != null) continue; // global symbol is either an export or import, skip |
| 1496 | | try locals.append(sym); |
| 1497 | | } |
| 1498 | | |
| 1499 | | for (macho_file.objects.items) |object, object_id| { |
| 1500 | | for (object.symtab.items) |sym, sym_id| { |
| 1501 | | if (sym.n_strx == 0) continue; // no name, skip |
| 1502 | | if (sym.n_desc == MachO.N_DESC_GCED) continue; // GCed, skip |
| 1503 | | const sym_loc = SymbolWithLoc{ .sym_index = @intCast(u32, sym_id), .file = @intCast(u32, object_id) }; |
| 1504 | | if (macho_file.symbolIsTemp(sym_loc)) continue; // local temp symbol, skip |
| 1505 | | if (macho_file.getGlobal(macho_file.getSymbolName(sym_loc)) != null) continue; // global symbol is either an export or import, skip |
| 1506 | | var out_sym = sym; |
| 1507 | | out_sym.n_strx = try macho_file.strtab.insert(gpa, macho_file.getSymbolName(sym_loc)); |
| 1508 | | try locals.append(out_sym); |
| 4192 | if (resolver.unresolved.count() > 0) { |
| 4193 | return error.UndefinedSymbolReference; |
| 1509 | 4194 | } |
| 1510 | | |
| 1511 | | if (!macho_file.base.options.strip) { |
| 1512 | | try generateSymbolStabs(macho_file, object, &locals); |
| 4195 | if (lib_not_found) { |
| 4196 | return error.LibraryNotFound; |
| 4197 | } |
| 4198 | if (framework_not_found) { |
| 4199 | return error.FrameworkNotFound; |
| 1513 | 4200 | } |
| 1514 | | } |
| 1515 | | |
| 1516 | | var exports = std.ArrayList(macho.nlist_64).init(gpa); |
| 1517 | | defer exports.deinit(); |
| 1518 | 4201 | |
| 1519 | | for (macho_file.globals.items) |global| { |
| 1520 | | const sym = macho_file.getSymbol(global); |
| 1521 | | if (sym.undf()) continue; // import, skip |
| 1522 | | if (sym.n_desc == MachO.N_DESC_GCED) continue; // GCed, skip |
| 1523 | | var out_sym = sym; |
| 1524 | | out_sym.n_strx = try macho_file.strtab.insert(gpa, macho_file.getSymbolName(global)); |
| 1525 | | try exports.append(out_sym); |
| 1526 | | } |
| 4202 | if (options.output_mode == .Exe) { |
| 4203 | const entry_name = options.entry orelse "_main"; |
| 4204 | const global_index = resolver.table.get(entry_name) orelse { |
| 4205 | log.err("entrypoint '{s}' not found", .{entry_name}); |
| 4206 | return error.MissingMainEntrypoint; |
| 4207 | }; |
| 4208 | zld.entry_index = global_index; |
| 4209 | } |
| 1527 | 4210 | |
| 1528 | | var imports = std.ArrayList(macho.nlist_64).init(gpa); |
| 1529 | | defer imports.deinit(); |
| 4211 | for (zld.objects.items) |*object, object_id| { |
| 4212 | try object.splitIntoAtoms(&zld, @intCast(u31, object_id)); |
| 4213 | } |
| 1530 | 4214 | |
| 1531 | | var imports_table = std.AutoHashMap(SymbolWithLoc, u32).init(gpa); |
| 4215 | var reverse_lookups: [][]u32 = try arena.alloc([]u32, zld.objects.items.len); |
| 4216 | for (zld.objects.items) |object, i| { |
| 4217 | reverse_lookups[i] = try object.createReverseSymbolLookup(arena); |
| 4218 | } |
| 1532 | 4219 | |
| 1533 | | for (macho_file.globals.items) |global| { |
| 1534 | | const sym = macho_file.getSymbol(global); |
| 1535 | | if (sym.n_strx == 0) continue; // no name, skip |
| 1536 | | if (!sym.undf()) continue; // not an import, skip |
| 1537 | | const new_index = @intCast(u32, imports.items.len); |
| 1538 | | var out_sym = sym; |
| 1539 | | out_sym.n_strx = try macho_file.strtab.insert(gpa, macho_file.getSymbolName(global)); |
| 1540 | | try imports.append(out_sym); |
| 1541 | | try imports_table.putNoClobber(global, new_index); |
| 1542 | | } |
| 4220 | if (gc_sections) { |
| 4221 | try dead_strip.gcAtoms(&zld, reverse_lookups); |
| 4222 | } |
| 1543 | 4223 | |
| 1544 | | const nlocals = @intCast(u32, locals.items.len); |
| 1545 | | const nexports = @intCast(u32, exports.items.len); |
| 1546 | | const nimports = @intCast(u32, imports.items.len); |
| 1547 | | const nsyms = nlocals + nexports + nimports; |
| 4224 | try zld.createDyldPrivateAtom(); |
| 4225 | try zld.createTentativeDefAtoms(); |
| 4226 | try zld.createStubHelperPreambleAtom(); |
| 1548 | 4227 | |
| 1549 | | const seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 1550 | | const offset = mem.alignForwardGeneric( |
| 1551 | | u64, |
| 1552 | | seg.fileoff + seg.filesize, |
| 1553 | | @alignOf(macho.nlist_64), |
| 1554 | | ); |
| 1555 | | const needed_size = nsyms * @sizeOf(macho.nlist_64); |
| 1556 | | seg.filesize = offset + needed_size - seg.fileoff; |
| 4228 | for (zld.objects.items) |object| { |
| 4229 | for (object.atoms.items) |atom_index| { |
| 4230 | const atom = zld.getAtom(atom_index); |
| 4231 | const sym = zld.getSymbol(atom.getSymbolWithLoc()); |
| 4232 | const header = zld.sections.items(.header)[sym.n_sect - 1]; |
| 4233 | if (header.isZerofill()) continue; |
| 1557 | 4234 | |
| 1558 | | var buffer = std.ArrayList(u8).init(gpa); |
| 1559 | | defer buffer.deinit(); |
| 1560 | | try buffer.ensureTotalCapacityPrecise(needed_size); |
| 1561 | | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(locals.items)); |
| 1562 | | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(exports.items)); |
| 1563 | | buffer.appendSliceAssumeCapacity(mem.sliceAsBytes(imports.items)); |
| 4235 | const relocs = Atom.getAtomRelocs(&zld, atom_index); |
| 4236 | try Atom.scanAtomRelocs(&zld, atom_index, relocs, reverse_lookups[atom.getFile().?]); |
| 4237 | } |
| 4238 | } |
| 1564 | 4239 | |
| 1565 | | log.debug("writing symtab from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 1566 | | try macho_file.base.file.?.pwriteAll(buffer.items, offset); |
| 4240 | try zld.createDyldStubBinderGotAtom(); |
| 1567 | 4241 | |
| 1568 | | lc.symoff = @intCast(u32, offset); |
| 1569 | | lc.nsyms = nsyms; |
| 4242 | try zld.calcSectionSizes(reverse_lookups); |
| 4243 | try zld.pruneAndSortSections(); |
| 4244 | try zld.createSegments(); |
| 4245 | try zld.allocateSegments(); |
| 1570 | 4246 | |
| 1571 | | return SymtabCtx{ |
| 1572 | | .nlocalsym = nlocals, |
| 1573 | | .nextdefsym = nexports, |
| 1574 | | .nundefsym = nimports, |
| 1575 | | .imports_table = imports_table, |
| 1576 | | }; |
| 1577 | | } |
| 4247 | try zld.allocateSpecialSymbols(); |
| 1578 | 4248 | |
| 1579 | | fn writeStrtab(macho_file: *MachO, lc: *macho.symtab_command) !void { |
| 1580 | | const seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 1581 | | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 1582 | | const needed_size = macho_file.strtab.buffer.items.len; |
| 1583 | | seg.filesize = offset + needed_size - seg.fileoff; |
| 4249 | if (build_options.enable_logging) { |
| 4250 | zld.logSymtab(); |
| 4251 | zld.logSegments(); |
| 4252 | zld.logSections(); |
| 4253 | zld.logAtoms(); |
| 4254 | } |
| 1584 | 4255 | |
| 1585 | | log.debug("writing string table from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 4256 | try zld.writeAtoms(reverse_lookups); |
| 1586 | 4257 | |
| 1587 | | try macho_file.base.file.?.pwriteAll(macho_file.strtab.buffer.items, offset); |
| 4258 | var lc_buffer = std.ArrayList(u8).init(arena); |
| 4259 | const lc_writer = lc_buffer.writer(); |
| 4260 | var ncmds: u32 = 0; |
| 1588 | 4261 | |
| 1589 | | lc.stroff = @intCast(u32, offset); |
| 1590 | | lc.strsize = @intCast(u32, needed_size); |
| 1591 | | } |
| 4262 | try zld.writeLinkeditSegmentData(&ncmds, lc_writer, reverse_lookups); |
| 1592 | 4263 | |
| 1593 | | pub fn generateSymbolStabs( |
| 1594 | | macho_file: *MachO, |
| 1595 | | object: Object, |
| 1596 | | locals: *std.ArrayList(macho.nlist_64), |
| 1597 | | ) !void { |
| 1598 | | assert(!macho_file.base.options.strip); |
| 4264 | // If the last section of __DATA segment is zerofill section, we need to ensure |
| 4265 | // that the free space between the end of the last non-zerofill section of __DATA |
| 4266 | // segment and the beginning of __LINKEDIT segment is zerofilled as the loader will |
| 4267 | // copy-paste this space into memory for quicker zerofill operation. |
| 4268 | if (zld.getSegmentByName("__DATA")) |data_seg_id| blk: { |
| 4269 | var physical_zerofill_start: u64 = 0; |
| 4270 | const section_indexes = zld.getSectionIndexes(data_seg_id); |
| 4271 | for (zld.sections.items(.header)[section_indexes.start..section_indexes.end]) |header| { |
| 4272 | if (header.isZerofill() and header.size > 0) break; |
| 4273 | physical_zerofill_start = header.offset + header.size; |
| 4274 | } else break :blk; |
| 4275 | const linkedit = zld.getLinkeditSegmentPtr(); |
| 4276 | const physical_zerofill_size = linkedit.fileoff - physical_zerofill_start; |
| 4277 | if (physical_zerofill_size > 0) { |
| 4278 | var padding = try zld.gpa.alloc(u8, physical_zerofill_size); |
| 4279 | defer zld.gpa.free(padding); |
| 4280 | mem.set(u8, padding, 0); |
| 4281 | try zld.file.pwriteAll(padding, physical_zerofill_start); |
| 4282 | } |
| 4283 | } |
| 1599 | 4284 | |
| 1600 | | log.debug("parsing debug info in '{s}'", .{object.name}); |
| 4285 | try Zld.writeDylinkerLC(&ncmds, lc_writer); |
| 4286 | try zld.writeMainLC(&ncmds, lc_writer); |
| 4287 | try zld.writeDylibIdLC(&ncmds, lc_writer); |
| 4288 | try zld.writeRpathLCs(&ncmds, lc_writer); |
| 1601 | 4289 | |
| 1602 | | const gpa = macho_file.base.allocator; |
| 1603 | | var debug_info = try object.parseDwarfInfo(); |
| 1604 | | defer debug_info.deinit(gpa); |
| 1605 | | try dwarf.openDwarfDebugInfo(&debug_info, gpa); |
| 1606 | | |
| 1607 | | // We assume there is only one CU. |
| 1608 | | const compile_unit = debug_info.findCompileUnit(0x0) catch |err| switch (err) { |
| 1609 | | error.MissingDebugInfo => { |
| 1610 | | // TODO audit cases with missing debug info and audit our dwarf.zig module. |
| 1611 | | log.debug("invalid or missing debug info in {s}; skipping", .{object.name}); |
| 1612 | | return; |
| 1613 | | }, |
| 1614 | | else => |e| return e, |
| 1615 | | }; |
| 4290 | { |
| 4291 | try lc_writer.writeStruct(macho.source_version_command{ |
| 4292 | .cmdsize = @sizeOf(macho.source_version_command), |
| 4293 | .version = 0x0, |
| 4294 | }); |
| 4295 | ncmds += 1; |
| 4296 | } |
| 1616 | 4297 | |
| 1617 | | const tu_name = try compile_unit.die.getAttrString(&debug_info, dwarf.AT.name, debug_info.debug_str, compile_unit.*); |
| 1618 | | const tu_comp_dir = try compile_unit.die.getAttrString(&debug_info, dwarf.AT.comp_dir, debug_info.debug_str, compile_unit.*); |
| 1619 | | |
| 1620 | | // Open scope |
| 1621 | | try locals.ensureUnusedCapacity(3); |
| 1622 | | locals.appendAssumeCapacity(.{ |
| 1623 | | .n_strx = try macho_file.strtab.insert(gpa, tu_comp_dir), |
| 1624 | | .n_type = macho.N_SO, |
| 1625 | | .n_sect = 0, |
| 1626 | | .n_desc = 0, |
| 1627 | | .n_value = 0, |
| 1628 | | }); |
| 1629 | | locals.appendAssumeCapacity(.{ |
| 1630 | | .n_strx = try macho_file.strtab.insert(gpa, tu_name), |
| 1631 | | .n_type = macho.N_SO, |
| 1632 | | .n_sect = 0, |
| 1633 | | .n_desc = 0, |
| 1634 | | .n_value = 0, |
| 1635 | | }); |
| 1636 | | locals.appendAssumeCapacity(.{ |
| 1637 | | .n_strx = try macho_file.strtab.insert(gpa, object.name), |
| 1638 | | .n_type = macho.N_OSO, |
| 1639 | | .n_sect = 0, |
| 1640 | | .n_desc = 1, |
| 1641 | | .n_value = object.mtime, |
| 1642 | | }); |
| 1643 | | |
| 1644 | | var stabs_buf: [4]macho.nlist_64 = undefined; |
| 1645 | | |
| 1646 | | for (object.managed_atoms.items) |atom| { |
| 1647 | | const stabs = try generateSymbolStabsForSymbol( |
| 1648 | | macho_file, |
| 1649 | | atom.getSymbolWithLoc(), |
| 1650 | | debug_info, |
| 1651 | | &stabs_buf, |
| 1652 | | ); |
| 1653 | | try locals.appendSlice(stabs); |
| 4298 | try zld.writeBuildVersionLC(&ncmds, lc_writer); |
| 1654 | 4299 | |
| 1655 | | for (atom.contained.items) |sym_at_off| { |
| 1656 | | const sym_loc = SymbolWithLoc{ |
| 1657 | | .sym_index = sym_at_off.sym_index, |
| 1658 | | .file = atom.file, |
| 4300 | { |
| 4301 | var uuid_lc = macho.uuid_command{ |
| 4302 | .cmdsize = @sizeOf(macho.uuid_command), |
| 4303 | .uuid = undefined, |
| 1659 | 4304 | }; |
| 1660 | | const contained_stabs = try generateSymbolStabsForSymbol( |
| 1661 | | macho_file, |
| 1662 | | sym_loc, |
| 1663 | | debug_info, |
| 1664 | | &stabs_buf, |
| 1665 | | ); |
| 1666 | | try locals.appendSlice(contained_stabs); |
| 4305 | std.crypto.random.bytes(&uuid_lc.uuid); |
| 4306 | try lc_writer.writeStruct(uuid_lc); |
| 4307 | ncmds += 1; |
| 1667 | 4308 | } |
| 1668 | | } |
| 1669 | | |
| 1670 | | // Close scope |
| 1671 | | try locals.append(.{ |
| 1672 | | .n_strx = 0, |
| 1673 | | .n_type = macho.N_SO, |
| 1674 | | .n_sect = 0, |
| 1675 | | .n_desc = 0, |
| 1676 | | .n_value = 0, |
| 1677 | | }); |
| 1678 | | } |
| 1679 | 4309 | |
| 1680 | | fn generateSymbolStabsForSymbol( |
| 1681 | | macho_file: *MachO, |
| 1682 | | sym_loc: SymbolWithLoc, |
| 1683 | | debug_info: dwarf.DwarfInfo, |
| 1684 | | buf: *[4]macho.nlist_64, |
| 1685 | | ) ![]const macho.nlist_64 { |
| 1686 | | const gpa = macho_file.base.allocator; |
| 1687 | | const object = macho_file.objects.items[sym_loc.file.?]; |
| 1688 | | const sym = macho_file.getSymbol(sym_loc); |
| 1689 | | const sym_name = macho_file.getSymbolName(sym_loc); |
| 1690 | | |
| 1691 | | if (sym.n_strx == 0) return buf[0..0]; |
| 1692 | | if (sym.n_desc == MachO.N_DESC_GCED) return buf[0..0]; |
| 1693 | | if (macho_file.symbolIsTemp(sym_loc)) return buf[0..0]; |
| 1694 | | |
| 1695 | | const source_sym = object.getSourceSymbol(sym_loc.sym_index) orelse return buf[0..0]; |
| 1696 | | const size: ?u64 = size: { |
| 1697 | | if (source_sym.tentative()) break :size null; |
| 1698 | | for (debug_info.func_list.items) |func| { |
| 1699 | | if (func.pc_range) |range| { |
| 1700 | | if (source_sym.n_value >= range.start and source_sym.n_value < range.end) { |
| 1701 | | break :size range.end - range.start; |
| 1702 | | } |
| 1703 | | } |
| 1704 | | } |
| 1705 | | break :size null; |
| 1706 | | }; |
| 4310 | try zld.writeLoadDylibLCs(&ncmds, lc_writer); |
| 1707 | 4311 | |
| 1708 | | if (size) |ss| { |
| 1709 | | buf[0] = .{ |
| 1710 | | .n_strx = 0, |
| 1711 | | .n_type = macho.N_BNSYM, |
| 1712 | | .n_sect = sym.n_sect, |
| 1713 | | .n_desc = 0, |
| 1714 | | .n_value = sym.n_value, |
| 1715 | | }; |
| 1716 | | buf[1] = .{ |
| 1717 | | .n_strx = try macho_file.strtab.insert(gpa, sym_name), |
| 1718 | | .n_type = macho.N_FUN, |
| 1719 | | .n_sect = sym.n_sect, |
| 1720 | | .n_desc = 0, |
| 1721 | | .n_value = sym.n_value, |
| 1722 | | }; |
| 1723 | | buf[2] = .{ |
| 1724 | | .n_strx = 0, |
| 1725 | | .n_type = macho.N_FUN, |
| 1726 | | .n_sect = 0, |
| 1727 | | .n_desc = 0, |
| 1728 | | .n_value = ss, |
| 1729 | | }; |
| 1730 | | buf[3] = .{ |
| 1731 | | .n_strx = 0, |
| 1732 | | .n_type = macho.N_ENSYM, |
| 1733 | | .n_sect = sym.n_sect, |
| 1734 | | .n_desc = 0, |
| 1735 | | .n_value = ss, |
| 1736 | | }; |
| 1737 | | return buf; |
| 1738 | | } else { |
| 1739 | | buf[0] = .{ |
| 1740 | | .n_strx = try macho_file.strtab.insert(gpa, sym_name), |
| 1741 | | .n_type = macho.N_STSYM, |
| 1742 | | .n_sect = sym.n_sect, |
| 1743 | | .n_desc = 0, |
| 1744 | | .n_value = sym.n_value, |
| 4312 | const requires_codesig = blk: { |
| 4313 | if (options.entitlements) |_| break :blk true; |
| 4314 | if (cpu_arch == .aarch64 and (os_tag == .macos or abi == .simulator)) break :blk true; |
| 4315 | break :blk false; |
| 1745 | 4316 | }; |
| 1746 | | return buf[0..1]; |
| 1747 | | } |
| 1748 | | } |
| 4317 | var codesig_offset: ?u32 = null; |
| 4318 | var codesig: ?CodeSignature = if (requires_codesig) blk: { |
| 4319 | // Preallocate space for the code signature. |
| 4320 | // We need to do this at this stage so that we have the load commands with proper values |
| 4321 | // written out to the file. |
| 4322 | // The most important here is to have the correct vm and filesize of the __LINKEDIT segment |
| 4323 | // where the code signature goes into. |
| 4324 | var codesig = CodeSignature.init(page_size); |
| 4325 | codesig.code_directory.ident = options.emit.?.sub_path; |
| 4326 | if (options.entitlements) |path| { |
| 4327 | try codesig.addEntitlements(gpa, path); |
| 4328 | } |
| 4329 | codesig_offset = try zld.writeCodeSignaturePadding(&codesig, &ncmds, lc_writer); |
| 4330 | break :blk codesig; |
| 4331 | } else null; |
| 4332 | defer if (codesig) |*csig| csig.deinit(gpa); |
| 1749 | 4333 | |
| 1750 | | const SymtabCtx = struct { |
| 1751 | | nlocalsym: u32, |
| 1752 | | nextdefsym: u32, |
| 1753 | | nundefsym: u32, |
| 1754 | | imports_table: std.AutoHashMap(SymbolWithLoc, u32), |
| 1755 | | }; |
| 4334 | var headers_buf = std.ArrayList(u8).init(arena); |
| 4335 | try zld.writeSegmentHeaders(&ncmds, headers_buf.writer()); |
| 1756 | 4336 | |
| 1757 | | fn writeDysymtab(macho_file: *MachO, ctx: SymtabCtx, lc: *macho.dysymtab_command) !void { |
| 1758 | | const gpa = macho_file.base.allocator; |
| 1759 | | const nstubs = @intCast(u32, macho_file.stubs_table.count()); |
| 1760 | | const ngot_entries = @intCast(u32, macho_file.got_entries_table.count()); |
| 1761 | | const nindirectsyms = nstubs * 2 + ngot_entries; |
| 1762 | | const iextdefsym = ctx.nlocalsym; |
| 1763 | | const iundefsym = iextdefsym + ctx.nextdefsym; |
| 1764 | | |
| 1765 | | const seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 1766 | | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, @alignOf(u64)); |
| 1767 | | const needed_size = nindirectsyms * @sizeOf(u32); |
| 1768 | | seg.filesize = offset + needed_size - seg.fileoff; |
| 1769 | | |
| 1770 | | log.debug("writing indirect symbol table from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 1771 | | |
| 1772 | | var buf = std.ArrayList(u8).init(gpa); |
| 1773 | | defer buf.deinit(); |
| 1774 | | try buf.ensureTotalCapacity(needed_size); |
| 1775 | | const writer = buf.writer(); |
| 1776 | | |
| 1777 | | if (macho_file.stubs_section_index) |sect_id| { |
| 1778 | | const stubs = &macho_file.sections.items(.header)[sect_id]; |
| 1779 | | stubs.reserved1 = 0; |
| 1780 | | for (macho_file.stubs.items) |entry| { |
| 1781 | | if (entry.sym_index == 0) continue; |
| 1782 | | const atom_sym = entry.getSymbol(macho_file); |
| 1783 | | if (atom_sym.n_desc == MachO.N_DESC_GCED) continue; |
| 1784 | | const target_sym = macho_file.getSymbol(entry.target); |
| 1785 | | assert(target_sym.undf()); |
| 1786 | | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 1787 | | } |
| 1788 | | } |
| 4337 | try zld.file.pwriteAll(headers_buf.items, @sizeOf(macho.mach_header_64)); |
| 4338 | try zld.file.pwriteAll(lc_buffer.items, @sizeOf(macho.mach_header_64) + headers_buf.items.len); |
| 4339 | try zld.writeHeader(ncmds, @intCast(u32, lc_buffer.items.len + headers_buf.items.len)); |
| 1789 | 4340 | |
| 1790 | | if (macho_file.got_section_index) |sect_id| { |
| 1791 | | const got = &macho_file.sections.items(.header)[sect_id]; |
| 1792 | | got.reserved1 = nstubs; |
| 1793 | | for (macho_file.got_entries.items) |entry| { |
| 1794 | | if (entry.sym_index == 0) continue; |
| 1795 | | const atom_sym = entry.getSymbol(macho_file); |
| 1796 | | if (atom_sym.n_desc == MachO.N_DESC_GCED) continue; |
| 1797 | | const target_sym = macho_file.getSymbol(entry.target); |
| 1798 | | if (target_sym.undf()) { |
| 1799 | | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 1800 | | } else { |
| 1801 | | try writer.writeIntLittle(u32, macho.INDIRECT_SYMBOL_LOCAL); |
| 1802 | | } |
| 4341 | if (codesig) |*csig| { |
| 4342 | try zld.writeCodeSignature(csig, codesig_offset.?); // code signing always comes last |
| 1803 | 4343 | } |
| 1804 | 4344 | } |
| 1805 | 4345 | |
| 1806 | | if (macho_file.la_symbol_ptr_section_index) |sect_id| { |
| 1807 | | const la_symbol_ptr = &macho_file.sections.items(.header)[sect_id]; |
| 1808 | | la_symbol_ptr.reserved1 = nstubs + ngot_entries; |
| 1809 | | for (macho_file.stubs.items) |entry| { |
| 1810 | | if (entry.sym_index == 0) continue; |
| 1811 | | const atom_sym = entry.getSymbol(macho_file); |
| 1812 | | if (atom_sym.n_desc == MachO.N_DESC_GCED) continue; |
| 1813 | | const target_sym = macho_file.getSymbol(entry.target); |
| 1814 | | assert(target_sym.undf()); |
| 1815 | | try writer.writeIntLittle(u32, iundefsym + ctx.imports_table.get(entry.target).?); |
| 1816 | | } |
| 4346 | if (!options.disable_lld_caching) { |
| 4347 | // Update the file with the digest. If it fails we can continue; it only |
| 4348 | // means that the next invocation will have an unnecessary cache miss. |
| 4349 | Cache.writeSmallFile(directory.handle, id_symlink_basename, &digest) catch |err| { |
| 4350 | log.debug("failed to save linking hash digest file: {s}", .{@errorName(err)}); |
| 4351 | }; |
| 4352 | // Again failure here only means an unnecessary cache miss. |
| 4353 | man.writeManifest() catch |err| { |
| 4354 | log.debug("failed to write cache manifest when linking: {s}", .{@errorName(err)}); |
| 4355 | }; |
| 4356 | // We hang on to this lock so that the output file path can be used without |
| 4357 | // other processes clobbering it. |
| 4358 | macho_file.base.lock = man.toOwnedLock(); |
| 1817 | 4359 | } |
| 1818 | | |
| 1819 | | assert(buf.items.len == needed_size); |
| 1820 | | try macho_file.base.file.?.pwriteAll(buf.items, offset); |
| 1821 | | |
| 1822 | | lc.nlocalsym = ctx.nlocalsym; |
| 1823 | | lc.iextdefsym = iextdefsym; |
| 1824 | | lc.nextdefsym = ctx.nextdefsym; |
| 1825 | | lc.iundefsym = iundefsym; |
| 1826 | | lc.nundefsym = ctx.nundefsym; |
| 1827 | | lc.indirectsymoff = @intCast(u32, offset); |
| 1828 | | lc.nindirectsyms = nindirectsyms; |
| 1829 | | } |
| 1830 | | |
| 1831 | | fn writeCodeSignaturePadding( |
| 1832 | | macho_file: *MachO, |
| 1833 | | code_sig: *CodeSignature, |
| 1834 | | ncmds: *u32, |
| 1835 | | lc_writer: anytype, |
| 1836 | | ) !u32 { |
| 1837 | | const seg = &macho_file.segments.items[macho_file.linkedit_segment_cmd_index.?]; |
| 1838 | | // Code signature data has to be 16-bytes aligned for Apple tools to recognize the file |
| 1839 | | // https://github.com/opensource-apple/cctools/blob/fdb4825f303fd5c0751be524babd32958181b3ed/libstuff/checkout.c#L271 |
| 1840 | | const offset = mem.alignForwardGeneric(u64, seg.fileoff + seg.filesize, 16); |
| 1841 | | const needed_size = code_sig.estimateSize(offset); |
| 1842 | | seg.filesize = offset + needed_size - seg.fileoff; |
| 1843 | | seg.vmsize = mem.alignForwardGeneric(u64, seg.filesize, macho_file.page_size); |
| 1844 | | log.debug("writing code signature padding from 0x{x} to 0x{x}", .{ offset, offset + needed_size }); |
| 1845 | | // Pad out the space. We need to do this to calculate valid hashes for everything in the file |
| 1846 | | // except for code signature data. |
| 1847 | | try macho_file.base.file.?.pwriteAll(&[_]u8{0}, offset + needed_size - 1); |
| 1848 | | |
| 1849 | | try lc_writer.writeStruct(macho.linkedit_data_command{ |
| 1850 | | .cmd = .CODE_SIGNATURE, |
| 1851 | | .cmdsize = @sizeOf(macho.linkedit_data_command), |
| 1852 | | .dataoff = @intCast(u32, offset), |
| 1853 | | .datasize = @intCast(u32, needed_size), |
| 1854 | | }); |
| 1855 | | ncmds.* += 1; |
| 1856 | | |
| 1857 | | return @intCast(u32, offset); |
| 1858 | | } |
| 1859 | | |
| 1860 | | fn writeCodeSignature(macho_file: *MachO, code_sig: *CodeSignature, offset: u32) !void { |
| 1861 | | const seg = macho_file.segments.items[macho_file.text_segment_cmd_index.?]; |
| 1862 | | |
| 1863 | | var buffer = std.ArrayList(u8).init(macho_file.base.allocator); |
| 1864 | | defer buffer.deinit(); |
| 1865 | | try buffer.ensureTotalCapacityPrecise(code_sig.size()); |
| 1866 | | try code_sig.writeAdhocSignature(macho_file.base.allocator, .{ |
| 1867 | | .file = macho_file.base.file.?, |
| 1868 | | .exec_seg_base = seg.fileoff, |
| 1869 | | .exec_seg_limit = seg.filesize, |
| 1870 | | .file_size = offset, |
| 1871 | | .output_mode = macho_file.base.options.output_mode, |
| 1872 | | }, buffer.writer()); |
| 1873 | | assert(buffer.items.len == code_sig.size()); |
| 1874 | | |
| 1875 | | log.debug("writing code signature from 0x{x} to 0x{x}", .{ |
| 1876 | | offset, |
| 1877 | | offset + buffer.items.len, |
| 1878 | | }); |
| 1879 | | |
| 1880 | | try macho_file.base.file.?.pwriteAll(buffer.items, offset); |
| 1881 | 4360 | } |
| 1882 | 4361 | |
| 1883 | | fn writeSegmentHeaders(macho_file: *MachO, ncmds: *u32, writer: anytype) !void { |
| 1884 | | for (macho_file.segments.items) |seg, i| { |
| 1885 | | const indexes = macho_file.getSectionIndexes(@intCast(u8, i)); |
| 1886 | | var out_seg = seg; |
| 1887 | | out_seg.cmdsize = @sizeOf(macho.segment_command_64); |
| 1888 | | out_seg.nsects = 0; |
| 1889 | | |
| 1890 | | // Update section headers count; any section with size of 0 is excluded |
| 1891 | | // since it doesn't have any data in the final binary file. |
| 1892 | | for (macho_file.sections.items(.header)[indexes.start..indexes.end]) |header| { |
| 1893 | | if (header.size == 0) continue; |
| 1894 | | out_seg.cmdsize += @sizeOf(macho.section_64); |
| 1895 | | out_seg.nsects += 1; |
| 1896 | | } |
| 1897 | | |
| 1898 | | if (out_seg.nsects == 0 and |
| 1899 | | (mem.eql(u8, out_seg.segName(), "__DATA_CONST") or |
| 1900 | | mem.eql(u8, out_seg.segName(), "__DATA"))) continue; |
| 1901 | | |
| 1902 | | try writer.writeStruct(out_seg); |
| 1903 | | for (macho_file.sections.items(.header)[indexes.start..indexes.end]) |header| { |
| 1904 | | if (header.size == 0) continue; |
| 1905 | | try writer.writeStruct(header); |
| 4362 | /// Binary search |
| 4363 | pub fn bsearch(comptime T: type, haystack: []align(1) const T, predicate: anytype) usize { |
| 4364 | if (!@hasDecl(@TypeOf(predicate), "predicate")) |
| 4365 | @compileError("Predicate is required to define fn predicate(@This(), T) bool"); |
| 4366 | |
| 4367 | var min: usize = 0; |
| 4368 | var max: usize = haystack.len; |
| 4369 | while (min < max) { |
| 4370 | const index = (min + max) / 2; |
| 4371 | const curr = haystack[index]; |
| 4372 | if (predicate.predicate(curr)) { |
| 4373 | min = index + 1; |
| 4374 | } else { |
| 4375 | max = index; |
| 1906 | 4376 | } |
| 1907 | | |
| 1908 | | ncmds.* += 1; |
| 1909 | 4377 | } |
| 4378 | return min; |
| 1910 | 4379 | } |
| 1911 | 4380 | |
| 1912 | | /// Writes Mach-O file header. |
| 1913 | | fn writeHeader(macho_file: *MachO, ncmds: u32, sizeofcmds: u32) !void { |
| 1914 | | var header: macho.mach_header_64 = .{}; |
| 1915 | | header.flags = macho.MH_NOUNDEFS | macho.MH_DYLDLINK | macho.MH_PIE | macho.MH_TWOLEVEL; |
| 1916 | | |
| 1917 | | switch (macho_file.base.options.target.cpu.arch) { |
| 1918 | | .aarch64 => { |
| 1919 | | header.cputype = macho.CPU_TYPE_ARM64; |
| 1920 | | header.cpusubtype = macho.CPU_SUBTYPE_ARM_ALL; |
| 1921 | | }, |
| 1922 | | .x86_64 => { |
| 1923 | | header.cputype = macho.CPU_TYPE_X86_64; |
| 1924 | | header.cpusubtype = macho.CPU_SUBTYPE_X86_64_ALL; |
| 1925 | | }, |
| 1926 | | else => return error.UnsupportedCpuArchitecture, |
| 1927 | | } |
| 1928 | | |
| 1929 | | switch (macho_file.base.options.output_mode) { |
| 1930 | | .Exe => { |
| 1931 | | header.filetype = macho.MH_EXECUTE; |
| 1932 | | }, |
| 1933 | | .Lib => { |
| 1934 | | // By this point, it can only be a dylib. |
| 1935 | | header.filetype = macho.MH_DYLIB; |
| 1936 | | header.flags |= macho.MH_NO_REEXPORTED_DYLIBS; |
| 1937 | | }, |
| 1938 | | else => unreachable, |
| 1939 | | } |
| 1940 | | |
| 1941 | | if (macho_file.getSectionByName("__DATA", "__thread_vars")) |sect_id| { |
| 1942 | | if (macho_file.sections.items(.header)[sect_id].size > 0) { |
| 1943 | | header.flags |= macho.MH_HAS_TLV_DESCRIPTORS; |
| 1944 | | } |
| 1945 | | } |
| 1946 | | |
| 1947 | | header.ncmds = ncmds; |
| 1948 | | header.sizeofcmds = sizeofcmds; |
| 4381 | /// Linear search |
| 4382 | pub fn lsearch(comptime T: type, haystack: []align(1) const T, predicate: anytype) usize { |
| 4383 | if (!@hasDecl(@TypeOf(predicate), "predicate")) |
| 4384 | @compileError("Predicate is required to define fn predicate(@This(), T) bool"); |
| 1949 | 4385 | |
| 1950 | | log.debug("writing Mach-O header {}", .{header}); |
| 1951 | | |
| 1952 | | try macho_file.base.file.?.pwriteAll(mem.asBytes(&header), 0); |
| 4386 | var i: usize = 0; |
| 4387 | while (i < haystack.len) : (i += 1) { |
| 4388 | if (predicate.predicate(haystack[i])) break; |
| 4389 | } |
| 4390 | return i; |
| 1953 | 4391 | } |