authorgravatar for kubkon@jakubkonka.comJakub Konka <kubkon@jakubkonka.com> 2022-06-28 20:29:20+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-06-28 20:29:20+02:00
log9e8298b864e076221ca9c487412209d8a08c43b2
tree50eca29c2dd63c025823f818e882631c94cf8053
parentca3c4ff2d0afcdc8fe86e7e7b41a967c88779729
parent5834a608fc629319772b1623a31b62dd49ac6d63
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #11950 from ziglang/macho-weak-libs-frameworks

macho: fully implement `-weak-lx` and `-weak_framework x` flags

21 files changed, 430 insertions(+), 113 deletions(-)

lib/std/build.zig+61-11
......@@ -1483,7 +1483,7 @@ pub const LibExeObjStep = struct {
14831483 lib_paths: ArrayList([]const u8),
14841484 rpaths: ArrayList([]const u8),
14851485 framework_dirs: ArrayList([]const u8),
1486 frameworks: StringHashMap(bool),
1486 frameworks: StringHashMap(FrameworkLinkInfo),
14871487 verbose_link: bool,
14881488 verbose_cc: bool,
14891489 emit_analysis: EmitOption = .default,
......@@ -1643,6 +1643,7 @@ pub const LibExeObjStep = struct {
16431643 pub const SystemLib = struct {
16441644 name: []const u8,
16451645 needed: bool,
1646 weak: bool,
16461647 use_pkg_config: enum {
16471648 /// Don't use pkg-config, just pass -lfoo where foo is name.
16481649 no,
......@@ -1655,6 +1656,11 @@ pub const LibExeObjStep = struct {
16551656 },
16561657 };
16571658
1659 const FrameworkLinkInfo = struct {
1660 needed: bool = false,
1661 weak: bool = false,
1662 };
1663
16581664 pub const IncludeDir = union(enum) {
16591665 raw_path: []const u8,
16601666 raw_path_system: []const u8,
......@@ -1744,7 +1750,7 @@ pub const LibExeObjStep = struct {
17441750 .kind = kind,
17451751 .root_src = root_src,
17461752 .name = name,
1747 .frameworks = StringHashMap(bool).init(builder.allocator),
1753 .frameworks = StringHashMap(FrameworkLinkInfo).init(builder.allocator),
17481754 .step = Step.init(base_id, name, builder.allocator, make),
17491755 .version = ver,
17501756 .out_filename = undefined,
......@@ -1893,11 +1899,19 @@ pub const LibExeObjStep = struct {
18931899 }
18941900
18951901 pub fn linkFramework(self: *LibExeObjStep, framework_name: []const u8) void {
1896 self.frameworks.put(self.builder.dupe(framework_name), false) catch unreachable;
1902 self.frameworks.put(self.builder.dupe(framework_name), .{}) catch unreachable;
18971903 }
18981904
18991905 pub fn linkFrameworkNeeded(self: *LibExeObjStep, framework_name: []const u8) void {
1900 self.frameworks.put(self.builder.dupe(framework_name), true) catch unreachable;
1906 self.frameworks.put(self.builder.dupe(framework_name), .{
1907 .needed = true,
1908 }) catch unreachable;
1909 }
1910
1911 pub fn linkFrameworkWeak(self: *LibExeObjStep, framework_name: []const u8) void {
1912 self.frameworks.put(self.builder.dupe(framework_name), .{
1913 .weak = true,
1914 }) catch unreachable;
19011915 }
19021916
19031917 /// Returns whether the library, executable, or object depends on a particular system library.
......@@ -1939,6 +1953,7 @@ pub const LibExeObjStep = struct {
19391953 .system_lib = .{
19401954 .name = "c",
19411955 .needed = false,
1956 .weak = false,
19421957 .use_pkg_config = .no,
19431958 },
19441959 }) catch unreachable;
......@@ -1952,6 +1967,7 @@ pub const LibExeObjStep = struct {
19521967 .system_lib = .{
19531968 .name = "c++",
19541969 .needed = false,
1970 .weak = false,
19551971 .use_pkg_config = .no,
19561972 },
19571973 }) catch unreachable;
......@@ -1977,6 +1993,7 @@ pub const LibExeObjStep = struct {
19771993 .system_lib = .{
19781994 .name = self.builder.dupe(name),
19791995 .needed = false,
1996 .weak = false,
19801997 .use_pkg_config = .no,
19811998 },
19821999 }) catch unreachable;
......@@ -1989,6 +2006,20 @@ pub const LibExeObjStep = struct {
19892006 .system_lib = .{
19902007 .name = self.builder.dupe(name),
19912008 .needed = true,
2009 .weak = false,
2010 .use_pkg_config = .no,
2011 },
2012 }) catch unreachable;
2013 }
2014
2015 /// Darwin-only. This one has no integration with anything, it just puts -weak-lname on the
2016 /// command line. Prefer to use `linkSystemLibraryWeak` instead.
2017 pub fn linkSystemLibraryWeakName(self: *LibExeObjStep, name: []const u8) void {
2018 self.link_objects.append(.{
2019 .system_lib = .{
2020 .name = self.builder.dupe(name),
2021 .needed = false,
2022 .weak = true,
19922023 .use_pkg_config = .no,
19932024 },
19942025 }) catch unreachable;
......@@ -2001,6 +2032,7 @@ pub const LibExeObjStep = struct {
20012032 .system_lib = .{
20022033 .name = self.builder.dupe(lib_name),
20032034 .needed = false,
2035 .weak = false,
20042036 .use_pkg_config = .force,
20052037 },
20062038 }) catch unreachable;
......@@ -2013,6 +2045,7 @@ pub const LibExeObjStep = struct {
20132045 .system_lib = .{
20142046 .name = self.builder.dupe(lib_name),
20152047 .needed = true,
2048 .weak = false,
20162049 .use_pkg_config = .force,
20172050 },
20182051 }) catch unreachable;
......@@ -2115,14 +2148,21 @@ pub const LibExeObjStep = struct {
21152148 }
21162149
21172150 pub fn linkSystemLibrary(self: *LibExeObjStep, name: []const u8) void {
2118 self.linkSystemLibraryInner(name, false);
2151 self.linkSystemLibraryInner(name, .{});
21192152 }
21202153
21212154 pub fn linkSystemLibraryNeeded(self: *LibExeObjStep, name: []const u8) void {
2122 self.linkSystemLibraryInner(name, true);
2155 self.linkSystemLibraryInner(name, .{ .needed = true });
21232156 }
21242157
2125 fn linkSystemLibraryInner(self: *LibExeObjStep, name: []const u8, needed: bool) void {
2158 pub fn linkSystemLibraryWeak(self: *LibExeObjStep, name: []const u8) void {
2159 self.linkSystemLibraryInner(name, .{ .weak = true });
2160 }
2161
2162 fn linkSystemLibraryInner(self: *LibExeObjStep, name: []const u8, opts: struct {
2163 needed: bool = false,
2164 weak: bool = false,
2165 }) void {
21262166 if (isLibCLibrary(name)) {
21272167 self.linkLibC();
21282168 return;
......@@ -2135,7 +2175,8 @@ pub const LibExeObjStep = struct {
21352175 self.link_objects.append(.{
21362176 .system_lib = .{
21372177 .name = self.builder.dupe(name),
2138 .needed = needed,
2178 .needed = opts.needed,
2179 .weak = opts.weak,
21392180 .use_pkg_config = .yes,
21402181 },
21412182 }) catch unreachable;
......@@ -2513,7 +2554,14 @@ pub const LibExeObjStep = struct {
25132554 },
25142555
25152556 .system_lib => |system_lib| {
2516 const prefix: []const u8 = if (system_lib.needed) "-needed-l" else "-l";
2557 const prefix: []const u8 = prefix: {
2558 if (system_lib.needed) break :prefix "-needed-l";
2559 if (system_lib.weak) {
2560 if (self.target.isDarwin()) break :prefix "-weak-l";
2561 warn("Weak library import used for a non-darwin target, this will be converted to normally library import `-lname`\n", .{});
2562 }
2563 break :prefix "-l";
2564 };
25172565 switch (system_lib.use_pkg_config) {
25182566 .no => try zig_args.append(builder.fmt("{s}{s}", .{ prefix, system_lib.name })),
25192567 .yes, .force => {
......@@ -3018,9 +3066,11 @@ pub const LibExeObjStep = struct {
30183066 var it = self.frameworks.iterator();
30193067 while (it.next()) |entry| {
30203068 const name = entry.key_ptr.*;
3021 const needed = entry.value_ptr.*;
3022 if (needed) {
3069 const info = entry.value_ptr.*;
3070 if (info.needed) {
30233071 zig_args.append("-needed_framework") catch unreachable;
3072 } else if (info.weak) {
3073 zig_args.append("-weak_framework") catch unreachable;
30243074 } else {
30253075 zig_args.append("-framework") catch unreachable;
30263076 }
lib/std/build/CheckObjectStep.zig+83-6
......@@ -65,6 +65,7 @@ const Action = struct {
6565 fn match(act: Action, haystack: []const u8, global_vars: anytype) !bool {
6666 assert(act.tag == .match);
6767
68 var candidate_var: ?struct { name: []const u8, value: u64 } = null;
6869 var hay_it = mem.tokenize(u8, mem.trim(u8, haystack, " "), " ");
6970 var needle_it = mem.tokenize(u8, mem.trim(u8, act.phrase, " "), " ");
7071
......@@ -92,12 +93,19 @@ const Action = struct {
9293 const name = needle_tok[1..closing_brace];
9394 if (name.len == 0) return error.MissingBraceValue;
9495 const value = try std.fmt.parseInt(u64, hay_tok, 16);
95 try global_vars.putNoClobber(name, value);
96 candidate_var = .{
97 .name = name,
98 .value = value,
99 };
96100 } else {
97101 if (!mem.eql(u8, hay_tok, needle_tok)) return false;
98102 }
99103 }
100104
105 if (candidate_var) |v| {
106 try global_vars.putNoClobber(v.name, v.value);
107 }
108
101109 return true;
102110 }
103111
......@@ -332,20 +340,43 @@ const MachODumper = struct {
332340 var output = std.ArrayList(u8).init(gpa);
333341 const writer = output.writer();
334342
335 var symtab_cmd: ?macho.symtab_command = null;
343 var load_commands = std.ArrayList(macho.LoadCommand).init(gpa);
344 try load_commands.ensureTotalCapacity(hdr.ncmds);
345
346 var sections = std.ArrayList(struct { seg: u16, sect: u16 }).init(gpa);
347 var imports = std.ArrayList(u16).init(gpa);
348
349 var symtab_cmd: ?u16 = null;
336350 var i: u16 = 0;
337351 while (i < hdr.ncmds) : (i += 1) {
338352 var cmd = try macho.LoadCommand.read(gpa, reader);
353 load_commands.appendAssumeCapacity(cmd);
339354
340 if (opts.dump_symtab and cmd.cmd() == .SYMTAB) {
341 symtab_cmd = cmd.symtab;
355 switch (cmd.cmd()) {
356 .SEGMENT_64 => {
357 const seg = cmd.segment;
358 for (seg.sections.items) |_, j| {
359 try sections.append(.{ .seg = i, .sect = @intCast(u16, j) });
360 }
361 },
362 .SYMTAB => {
363 symtab_cmd = i;
364 },
365 .LOAD_DYLIB,
366 .LOAD_WEAK_DYLIB,
367 .REEXPORT_DYLIB,
368 => {
369 try imports.append(i);
370 },
371 else => {},
342372 }
343373
344374 try dumpLoadCommand(cmd, i, writer);
345375 try writer.writeByte('\n');
346376 }
347377
348 if (symtab_cmd) |cmd| {
378 if (opts.dump_symtab) {
379 const cmd = load_commands.items[symtab_cmd.?].symtab;
349380 try writer.writeAll(symtab_label ++ "\n");
350381 const strtab = bytes[cmd.stroff..][0..cmd.strsize];
351382 const raw_symtab = bytes[cmd.symoff..][0 .. cmd.nsyms * @sizeOf(macho.nlist_64)];
......@@ -354,7 +385,51 @@ const MachODumper = struct {
354385 for (symtab) |sym| {
355386 if (sym.stab()) continue;
356387 const sym_name = mem.sliceTo(@ptrCast([*:0]const u8, strtab.ptr + sym.n_strx), 0);
357 try writer.print("{s} {x}\n", .{ sym_name, sym.n_value });
388 if (sym.sect()) {
389 const map = sections.items[sym.n_sect - 1];
390 const seg = load_commands.items[map.seg].segment;
391 const sect = seg.sections.items[map.sect];
392 try writer.print("{x} ({s},{s})", .{
393 sym.n_value,
394 sect.segName(),
395 sect.sectName(),
396 });
397 if (sym.ext()) {
398 try writer.writeAll(" external");
399 }
400 try writer.print(" {s}\n", .{sym_name});
401 } else if (sym.undf()) {
402 const ordinal = @divTrunc(@bitCast(i16, sym.n_desc), macho.N_SYMBOL_RESOLVER);
403 const import_name = blk: {
404 if (ordinal <= 0) {
405 if (ordinal == macho.BIND_SPECIAL_DYLIB_SELF)
406 break :blk "self import";
407 if (ordinal == macho.BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE)
408 break :blk "main executable";
409 if (ordinal == macho.BIND_SPECIAL_DYLIB_FLAT_LOOKUP)
410 break :blk "flat lookup";
411 unreachable;
412 }
413 const import_id = imports.items[@bitCast(u16, ordinal) - 1];
414 const import = load_commands.items[import_id].dylib;
415 const full_path = mem.sliceTo(import.data, 0);
416 const basename = fs.path.basename(full_path);
417 assert(basename.len > 0);
418 const ext = mem.lastIndexOfScalar(u8, basename, '.') orelse basename.len;
419 break :blk basename[0..ext];
420 };
421 try writer.writeAll("(undefined)");
422 if (sym.weakRef()) {
423 try writer.writeAll(" weak");
424 }
425 if (sym.ext()) {
426 try writer.writeAll(" external");
427 }
428 try writer.print(" {s} (from {s})\n", .{
429 sym_name,
430 import_name,
431 });
432 } else unreachable;
358433 }
359434 }
360435
......@@ -408,6 +483,8 @@ const MachODumper = struct {
408483
409484 .ID_DYLIB,
410485 .LOAD_DYLIB,
486 .LOAD_WEAK_DYLIB,
487 .REEXPORT_DYLIB,
411488 => {
412489 const dylib = lc.dylib.inner.dylib;
413490 try writer.writeByte('\n');
lib/std/macho.zig+3-1
......@@ -2085,11 +2085,13 @@ pub fn GenericCommandWithData(comptime Cmd: type) type {
20852085
20862086pub fn createLoadDylibCommand(
20872087 allocator: Allocator,
2088 cmd_id: LC,
20882089 name: []const u8,
20892090 timestamp: u32,
20902091 current_version: u32,
20912092 compatibility_version: u32,
20922093) !GenericCommandWithData(dylib_command) {
2094 assert(cmd_id == .LOAD_DYLIB or cmd_id == .LOAD_WEAK_DYLIB or cmd_id == .REEXPORT_DYLIB or cmd_id == .ID_DYLIB);
20932095 const cmdsize = @intCast(u32, mem.alignForwardGeneric(
20942096 u64,
20952097 @sizeOf(dylib_command) + name.len + 1, // +1 for nul
......@@ -2097,7 +2099,7 @@ pub fn createLoadDylibCommand(
20972099 ));
20982100
20992101 var dylib_cmd = emptyGenericCommandWithData(dylib_command{
2100 .cmd = .LOAD_DYLIB,
2102 .cmd = cmd_id,
21012103 .cmdsize = cmdsize,
21022104 .dylib = .{
21032105 .name = @sizeOf(dylib_command),
src/link.zig+1
......@@ -21,6 +21,7 @@ const TypedValue = @import("TypedValue.zig");
2121
2222pub const SystemLib = struct {
2323 needed: bool = false,
24 weak: bool = false,
2425};
2526
2627pub const CacheMode = enum { incremental, whole };
src/link/MachO.zig+91-40
......@@ -52,6 +52,11 @@ pub const SearchStrategy = enum {
5252 dylibs_first,
5353};
5454
55const SystemLib = struct {
56 needed: bool = false,
57 weak: bool = false,
58};
59
5560base: File,
5661
5762/// If this is not null, an object file is created by LLVM and linked with LLD afterwards.
......@@ -768,7 +773,7 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
768773 }
769774
770775 // Shared and static libraries passed via `-l` flag.
771 var candidate_libs = std.StringArrayHashMap(Compilation.SystemLib).init(arena);
776 var candidate_libs = std.StringArrayHashMap(SystemLib).init(arena);
772777
773778 const system_lib_names = self.base.options.system_libs.keys();
774779 for (system_lib_names) |system_lib_name| {
......@@ -781,7 +786,10 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
781786 }
782787
783788 const system_lib_info = self.base.options.system_libs.get(system_lib_name).?;
784 try candidate_libs.put(system_lib_name, system_lib_info);
789 try candidate_libs.put(system_lib_name, .{
790 .needed = system_lib_info.needed,
791 .weak = system_lib_info.weak,
792 });
785793 }
786794
787795 var lib_dirs = std.ArrayList([]const u8).init(arena);
......@@ -793,7 +801,7 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
793801 }
794802 }
795803
796 var libs = std.StringArrayHashMap(Compilation.SystemLib).init(arena);
804 var libs = std.StringArrayHashMap(SystemLib).init(arena);
797805
798806 // Assume ld64 default -search_paths_first if no strategy specified.
799807 const search_strategy = self.base.options.search_strategy orelse .paths_first;
......@@ -890,7 +898,11 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
890898 for (framework_dirs.items) |dir| {
891899 for (&[_][]const u8{ ".tbd", ".dylib", "" }) |ext| {
892900 if (try resolveFramework(arena, dir, f_name, ext)) |full_path| {
893 try libs.put(full_path, self.base.options.frameworks.get(f_name).?);
901 const info = self.base.options.frameworks.get(f_name).?;
902 try libs.put(full_path, .{
903 .needed = info.needed,
904 .weak = info.weak,
905 });
894906 continue :outer;
895907 }
896908 }
......@@ -1026,9 +1038,11 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
10261038 try argv.append("-lc");
10271039
10281040 for (self.base.options.system_libs.keys()) |l_name| {
1029 const needed = self.base.options.system_libs.get(l_name).?.needed;
1030 const arg = if (needed)
1041 const info = self.base.options.system_libs.get(l_name).?;
1042 const arg = if (info.needed)
10311043 try std.fmt.allocPrint(arena, "-needed-l{s}", .{l_name})
1044 else if (info.weak)
1045 try std.fmt.allocPrint(arena, "-weak-l{s}", .{l_name})
10321046 else
10331047 try std.fmt.allocPrint(arena, "-l{s}", .{l_name});
10341048 try argv.append(arg);
......@@ -1039,9 +1053,11 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
10391053 }
10401054
10411055 for (self.base.options.frameworks.keys()) |framework| {
1042 const needed = self.base.options.frameworks.get(framework).?.needed;
1043 const arg = if (needed)
1056 const info = self.base.options.frameworks.get(framework).?;
1057 const arg = if (info.needed)
10441058 try std.fmt.allocPrint(arena, "-needed_framework {s}", .{framework})
1059 else if (info.weak)
1060 try std.fmt.allocPrint(arena, "-weak_framework {s}", .{framework})
10451061 else
10461062 try std.fmt.allocPrint(arena, "-framework {s}", .{framework});
10471063 try argv.append(arg);
......@@ -1063,7 +1079,10 @@ pub fn flushModule(self: *MachO, comp: *Compilation, prog_node: *std.Progress.No
10631079 Compilation.dump_argv(argv.items);
10641080 }
10651081
1066 var dependent_libs = std.fifo.LinearFifo(Dylib.Id, .Dynamic).init(self.base.allocator);
1082 var dependent_libs = std.fifo.LinearFifo(struct {
1083 id: Dylib.Id,
1084 parent: u16,
1085 }, .Dynamic).init(self.base.allocator);
10671086 defer dependent_libs.deinit();
10681087 try self.parseInputFiles(positionals.items, self.base.options.sysroot, &dependent_libs);
10691088 try self.parseAndForceLoadStaticArchives(must_link_archives.keys());
......@@ -1389,13 +1408,18 @@ const ParseDylibError = error{
13891408
13901409const DylibCreateOpts = struct {
13911410 syslibroot: ?[]const u8,
1392 dependent_libs: *std.fifo.LinearFifo(Dylib.Id, .Dynamic),
13931411 id: ?Dylib.Id = null,
1394 is_dependent: bool = false,
1395 is_needed: bool = false,
1412 dependent: bool = false,
1413 needed: bool = false,
1414 weak: bool = false,
13961415};
13971416
1398pub fn parseDylib(self: *MachO, path: []const u8, opts: DylibCreateOpts) ParseDylibError!bool {
1417pub fn parseDylib(
1418 self: *MachO,
1419 path: []const u8,
1420 dependent_libs: anytype,
1421 opts: DylibCreateOpts,
1422) ParseDylibError!bool {
13991423 const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) {
14001424 error.FileNotFound => return false,
14011425 else => |e| return e,
......@@ -1405,12 +1429,19 @@ pub fn parseDylib(self: *MachO, path: []const u8, opts: DylibCreateOpts) ParseDy
14051429 const name = try self.base.allocator.dupe(u8, path);
14061430 errdefer self.base.allocator.free(name);
14071431
1432 const dylib_id = @intCast(u16, self.dylibs.items.len);
14081433 var dylib = Dylib{
14091434 .name = name,
14101435 .file = file,
1436 .weak = opts.weak,
14111437 };
14121438
1413 dylib.parse(self.base.allocator, self.base.options.target, opts.dependent_libs) catch |err| switch (err) {
1439 dylib.parse(
1440 self.base.allocator,
1441 self.base.options.target,
1442 dylib_id,
1443 dependent_libs,
1444 ) catch |err| switch (err) {
14141445 error.EndOfStream, error.NotDylib => {
14151446 try file.seekTo(0);
14161447
......@@ -1420,7 +1451,13 @@ pub fn parseDylib(self: *MachO, path: []const u8, opts: DylibCreateOpts) ParseDy
14201451 };
14211452 defer lib_stub.deinit();
14221453
1423 try dylib.parseFromStub(self.base.allocator, self.base.options.target, lib_stub, opts.dependent_libs);
1454 try dylib.parseFromStub(
1455 self.base.allocator,
1456 self.base.options.target,
1457 lib_stub,
1458 dylib_id,
1459 dependent_libs,
1460 );
14241461 },
14251462 else => |e| return e,
14261463 };
......@@ -1438,13 +1475,12 @@ pub fn parseDylib(self: *MachO, path: []const u8, opts: DylibCreateOpts) ParseDy
14381475 }
14391476 }
14401477
1441 const dylib_id = @intCast(u16, self.dylibs.items.len);
14421478 try self.dylibs.append(self.base.allocator, dylib);
14431479 try self.dylibs_map.putNoClobber(self.base.allocator, dylib.id.?.name, dylib_id);
14441480
14451481 const should_link_dylib_even_if_unreachable = blk: {
1446 if (self.base.options.dead_strip_dylibs and !opts.is_needed) break :blk false;
1447 break :blk !(opts.is_dependent or self.referenced_dylibs.contains(dylib_id));
1482 if (self.base.options.dead_strip_dylibs and !opts.needed) break :blk false;
1483 break :blk !(opts.dependent or self.referenced_dylibs.contains(dylib_id));
14481484 };
14491485
14501486 if (should_link_dylib_even_if_unreachable) {
......@@ -1467,9 +1503,8 @@ fn parseInputFiles(self: *MachO, files: []const []const u8, syslibroot: ?[]const
14671503
14681504 if (try self.parseObject(full_path)) continue;
14691505 if (try self.parseArchive(full_path, false)) continue;
1470 if (try self.parseDylib(full_path, .{
1506 if (try self.parseDylib(full_path, dependent_libs, .{
14711507 .syslibroot = syslibroot,
1472 .dependent_libs = dependent_libs,
14731508 })) continue;
14741509
14751510 log.warn("unknown filetype for positional input file: '{s}'", .{file_name});
......@@ -1494,17 +1529,17 @@ fn parseAndForceLoadStaticArchives(self: *MachO, files: []const []const u8) !voi
14941529fn parseLibs(
14951530 self: *MachO,
14961531 lib_names: []const []const u8,
1497 lib_infos: []const Compilation.SystemLib,
1532 lib_infos: []const SystemLib,
14981533 syslibroot: ?[]const u8,
14991534 dependent_libs: anytype,
15001535) !void {
15011536 for (lib_names) |lib, i| {
15021537 const lib_info = lib_infos[i];
15031538 log.debug("parsing lib path '{s}'", .{lib});
1504 if (try self.parseDylib(lib, .{
1539 if (try self.parseDylib(lib, dependent_libs, .{
15051540 .syslibroot = syslibroot,
1506 .dependent_libs = dependent_libs,
1507 .is_needed = lib_info.needed,
1541 .needed = lib_info.needed,
1542 .weak = lib_info.weak,
15081543 })) continue;
15091544 if (try self.parseArchive(lib, false)) continue;
15101545
......@@ -1522,20 +1557,21 @@ fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: any
15221557 const arena = arena_alloc.allocator();
15231558 defer arena_alloc.deinit();
15241559
1525 while (dependent_libs.readItem()) |*id| {
1526 defer id.deinit(self.base.allocator);
1560 while (dependent_libs.readItem()) |*dep_id| {
1561 defer dep_id.id.deinit(self.base.allocator);
15271562
1528 if (self.dylibs_map.contains(id.name)) continue;
1563 if (self.dylibs_map.contains(dep_id.id.name)) continue;
15291564
1565 const weak = self.dylibs.items[dep_id.parent].weak;
15301566 const has_ext = blk: {
1531 const basename = fs.path.basename(id.name);
1567 const basename = fs.path.basename(dep_id.id.name);
15321568 break :blk mem.lastIndexOfScalar(u8, basename, '.') != null;
15331569 };
1534 const extension = if (has_ext) fs.path.extension(id.name) else "";
1570 const extension = if (has_ext) fs.path.extension(dep_id.id.name) else "";
15351571 const without_ext = if (has_ext) blk: {
1536 const index = mem.lastIndexOfScalar(u8, id.name, '.') orelse unreachable;
1537 break :blk id.name[0..index];
1538 } else id.name;
1572 const index = mem.lastIndexOfScalar(u8, dep_id.id.name, '.') orelse unreachable;
1573 break :blk dep_id.id.name[0..index];
1574 } else dep_id.id.name;
15391575
15401576 for (&[_][]const u8{ extension, ".tbd" }) |ext| {
15411577 const with_ext = try std.fmt.allocPrint(arena, "{s}{s}", .{ without_ext, ext });
......@@ -1543,15 +1579,15 @@ fn parseDependentLibs(self: *MachO, syslibroot: ?[]const u8, dependent_libs: any
15431579
15441580 log.debug("trying dependency at fully resolved path {s}", .{full_path});
15451581
1546 const did_parse_successfully = try self.parseDylib(full_path, .{
1547 .id = id.*,
1582 const did_parse_successfully = try self.parseDylib(full_path, dependent_libs, .{
1583 .id = dep_id.id,
15481584 .syslibroot = syslibroot,
1549 .is_dependent = true,
1550 .dependent_libs = dependent_libs,
1585 .dependent = true,
1586 .weak = weak,
15511587 });
15521588 if (did_parse_successfully) break;
15531589 } else {
1554 log.warn("unable to resolve dependency {s}", .{id.name});
1590 log.warn("unable to resolve dependency {s}", .{dep_id.id.name});
15551591 }
15561592 }
15571593}
......@@ -3081,6 +3117,10 @@ fn resolveSymbolsInDylibs(self: *MachO) !void {
30813117 undef.n_type |= macho.N_EXT;
30823118 undef.n_desc = @intCast(u16, ordinal + 1) * macho.N_SYMBOL_RESOLVER;
30833119
3120 if (dylib.weak) {
3121 undef.n_desc |= macho.N_WEAK_REF;
3122 }
3123
30843124 if (self.unresolved.fetchSwapRemove(resolv.where_index)) |entry| outer_blk: {
30853125 switch (entry.value) {
30863126 .none => {},
......@@ -3441,6 +3481,7 @@ fn addLoadDylibLC(self: *MachO, id: u16) !void {
34413481 const dylib_id = dylib.id orelse unreachable;
34423482 var dylib_cmd = try macho.createLoadDylibCommand(
34433483 self.base.allocator,
3484 if (dylib.weak) .LOAD_WEAK_DYLIB else .LOAD_DYLIB,
34443485 dylib_id.name,
34453486 dylib_id.timestamp,
34463487 dylib_id.current_version,
......@@ -4885,13 +4926,13 @@ fn populateMissingMetadata(self: *MachO) !void {
48854926 std.builtin.Version{ .major = 1, .minor = 0, .patch = 0 };
48864927 var dylib_cmd = try macho.createLoadDylibCommand(
48874928 self.base.allocator,
4929 .ID_DYLIB,
48884930 install_name,
48894931 2,
48904932 current_version.major << 16 | current_version.minor << 8 | current_version.patch,
48914933 compat_version.major << 16 | compat_version.minor << 8 | compat_version.patch,
48924934 );
48934935 errdefer dylib_cmd.deinit(self.base.allocator);
4894 dylib_cmd.inner.cmd = .ID_DYLIB;
48954936 try self.load_commands.append(self.base.allocator, .{ .dylib = dylib_cmd });
48964937 self.load_commands_dirty = true;
48974938 }
......@@ -5769,11 +5810,16 @@ fn writeDyldInfoData(self: *MachO) !void {
57695810 },
57705811 .undef => {
57715812 const bind_sym = self.undefs.items[resolv.where_index];
5813 var flags: u4 = 0;
5814 if (bind_sym.weakRef()) {
5815 flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT);
5816 }
57725817 try bind_pointers.append(.{
57735818 .offset = binding.offset + base_offset,
57745819 .segment_id = match.seg,
5775 .dylib_ordinal = @divExact(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER),
5820 .dylib_ordinal = @divTrunc(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER),
57765821 .name = self.getString(bind_sym.n_strx),
5822 .bind_flags = flags,
57775823 });
57785824 },
57795825 }
......@@ -5791,11 +5837,16 @@ fn writeDyldInfoData(self: *MachO) !void {
57915837 },
57925838 .undef => {
57935839 const bind_sym = self.undefs.items[resolv.where_index];
5840 var flags: u4 = 0;
5841 if (bind_sym.weakRef()) {
5842 flags |= @truncate(u4, macho.BIND_SYMBOL_FLAGS_WEAK_IMPORT);
5843 }
57945844 try lazy_bind_pointers.append(.{
57955845 .offset = binding.offset + base_offset,
57965846 .segment_id = match.seg,
5797 .dylib_ordinal = @divExact(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER),
5847 .dylib_ordinal = @divTrunc(@bitCast(i16, bind_sym.n_desc), macho.N_SYMBOL_RESOLVER),
57985848 .name = self.getString(bind_sym.n_strx),
5849 .bind_flags = flags,
57995850 });
58005851 },
58015852 }
src/link/MachO/Dylib.zig+20-6
......@@ -30,6 +30,7 @@ dysymtab_cmd_index: ?u16 = null,
3030id_cmd_index: ?u16 = null,
3131
3232id: ?Id = null,
33weak: bool = false,
3334
3435/// Parsed symbol table represented as hash map of symbols'
3536/// names. We can and should defer creating *Symbols until
......@@ -141,7 +142,13 @@ pub fn deinit(self: *Dylib, allocator: Allocator) void {
141142 }
142143}
143144
144pub fn parse(self: *Dylib, allocator: Allocator, target: std.Target, dependent_libs: anytype) !void {
145pub fn parse(
146 self: *Dylib,
147 allocator: Allocator,
148 target: std.Target,
149 dylib_id: u16,
150 dependent_libs: anytype,
151) !void {
145152 log.debug("parsing shared library '{s}'", .{self.name});
146153
147154 self.library_offset = try fat.getLibraryOffset(self.file.reader(), target);
......@@ -163,12 +170,18 @@ pub fn parse(self: *Dylib, allocator: Allocator, target: std.Target, dependent_l
163170 return error.MismatchedCpuArchitecture;
164171 }
165172
166 try self.readLoadCommands(allocator, reader, dependent_libs);
173 try self.readLoadCommands(allocator, reader, dylib_id, dependent_libs);
167174 try self.parseId(allocator);
168175 try self.parseSymbols(allocator);
169176}
170177
171fn readLoadCommands(self: *Dylib, allocator: Allocator, reader: anytype, dependent_libs: anytype) !void {
178fn readLoadCommands(
179 self: *Dylib,
180 allocator: Allocator,
181 reader: anytype,
182 dylib_id: u16,
183 dependent_libs: anytype,
184) !void {
172185 const should_lookup_reexports = self.header.?.flags & macho.MH_NO_REEXPORTED_DYLIBS == 0;
173186
174187 try self.load_commands.ensureUnusedCapacity(allocator, self.header.?.ncmds);
......@@ -190,7 +203,7 @@ fn readLoadCommands(self: *Dylib, allocator: Allocator, reader: anytype, depende
190203 if (should_lookup_reexports) {
191204 // Parse install_name to dependent dylib.
192205 var id = try Id.fromLoadCommand(allocator, cmd.dylib);
193 try dependent_libs.writeItem(id);
206 try dependent_libs.writeItem(.{ .id = id, .parent = dylib_id });
194207 }
195208 },
196209 else => {
......@@ -338,6 +351,7 @@ pub fn parseFromStub(
338351 allocator: Allocator,
339352 target: std.Target,
340353 lib_stub: LibStub,
354 dylib_id: u16,
341355 dependent_libs: anytype,
342356) !void {
343357 if (lib_stub.inner.len == 0) return error.EmptyStubFile;
......@@ -417,7 +431,7 @@ pub fn parseFromStub(
417431 log.debug(" (found re-export '{s}')", .{lib});
418432
419433 var dep_id = try Id.default(allocator, lib);
420 try dependent_libs.writeItem(dep_id);
434 try dependent_libs.writeItem(.{ .id = dep_id, .parent = dylib_id });
421435 }
422436 }
423437 }
......@@ -522,7 +536,7 @@ pub fn parseFromStub(
522536 log.debug(" (found re-export '{s}')", .{lib});
523537
524538 var dep_id = try Id.default(allocator, lib);
525 try dependent_libs.writeItem(dep_id);
539 try dependent_libs.writeItem(.{ .id = dep_id, .parent = dylib_id });
526540 }
527541 }
528542 }
src/link/MachO/bind.zig+3-2
......@@ -7,6 +7,7 @@ pub const Pointer = struct {
77 segment_id: u16,
88 dylib_ordinal: ?i64 = null,
99 name: ?[]const u8 = null,
10 bind_flags: u4 = 0,
1011};
1112
1213pub fn rebaseInfoSize(pointers: []const Pointer) !u64 {
......@@ -73,7 +74,7 @@ pub fn writeBindInfo(pointers: []const Pointer, writer: anytype) !void {
7374 }
7475 try writer.writeByte(macho.BIND_OPCODE_SET_TYPE_IMM | @truncate(u4, macho.BIND_TYPE_POINTER));
7576
76 try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
77 try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | pointer.bind_flags);
7778 try writer.writeAll(pointer.name.?);
7879 try writer.writeByte(0);
7980
......@@ -127,7 +128,7 @@ pub fn writeLazyBindInfo(pointers: []const Pointer, writer: anytype) !void {
127128 try writer.writeByte(macho.BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | @truncate(u4, @bitCast(u64, pointer.dylib_ordinal.?)));
128129 }
129130
130 try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); // TODO Sometimes we might want to add flags.
131 try writer.writeByte(macho.BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | pointer.bind_flags);
131132 try writer.writeAll(pointer.name.?);
132133 try writer.writeByte(0);
133134
src/main.zig+35-6
......@@ -443,9 +443,12 @@ const usage_build_generic =
443443 \\ --subsystem [subsystem] (Windows) /SUBSYSTEM:<subsystem> to the linker
444444 \\ --stack [size] Override default stack size
445445 \\ --image-base [addr] Set base address for executable image
446 \\ -weak-l[lib] (Darwin) link against system library and mark it and all referenced symbols as weak
447 \\ -weak_library [lib]
446448 \\ -framework [name] (Darwin) link against framework
447449 \\ -needed_framework [name] (Darwin) link against framework (even if unused)
448450 \\ -needed_library [lib] (Darwin) link against system library (even if unused)
451 \\ -weak_framework [name] (Darwin) link against framework and mark it and all referenced symbols as weak
449452 \\ -F[dir] (Darwin) add search path for frameworks
450453 \\ -install_name=[value] (Darwin) add dylib's install name
451454 \\ --entitlements [path] (Darwin) add path to entitlements file for embedding in code signature
......@@ -916,7 +919,12 @@ fn buildOutputType(
916919 const path = args_iter.next() orelse {
917920 fatal("expected parameter after {s}", .{arg});
918921 };
919 try frameworks.put(gpa, path, .{ .needed = false });
922 try frameworks.put(gpa, path, .{});
923 } else if (mem.eql(u8, arg, "-weak_framework")) {
924 const path = args_iter.next() orelse {
925 fatal("expected parameter after {s}", .{arg});
926 };
927 try frameworks.put(gpa, path, .{ .weak = true });
920928 } else if (mem.eql(u8, arg, "-needed_framework")) {
921929 const path = args_iter.next() orelse {
922930 fatal("expected parameter after {s}", .{arg});
......@@ -962,7 +970,7 @@ fn buildOutputType(
962970 };
963971 // We don't know whether this library is part of libc or libc++ until
964972 // we resolve the target, so we simply append to the list for now.
965 try system_libs.put(next_arg, .{ .needed = false });
973 try system_libs.put(next_arg, .{});
966974 } else if (mem.eql(u8, arg, "--needed-library") or
967975 mem.eql(u8, arg, "-needed-l") or
968976 mem.eql(u8, arg, "-needed_library"))
......@@ -971,6 +979,11 @@ fn buildOutputType(
971979 fatal("expected parameter after {s}", .{arg});
972980 };
973981 try system_libs.put(next_arg, .{ .needed = true });
982 } else if (mem.eql(u8, arg, "-weak_library") or mem.eql(u8, arg, "-weak-l")) {
983 const next_arg = args_iter.next() orelse {
984 fatal("expected parameter after {s}", .{arg});
985 };
986 try system_libs.put(next_arg, .{ .weak = true });
974987 } else if (mem.eql(u8, arg, "-D") or
975988 mem.eql(u8, arg, "-isystem") or
976989 mem.eql(u8, arg, "-I") or
......@@ -1300,9 +1313,11 @@ fn buildOutputType(
13001313 } else if (mem.startsWith(u8, arg, "-l")) {
13011314 // We don't know whether this library is part of libc or libc++ until
13021315 // we resolve the target, so we simply append to the list for now.
1303 try system_libs.put(arg["-l".len..], .{ .needed = false });
1316 try system_libs.put(arg["-l".len..], .{});
13041317 } else if (mem.startsWith(u8, arg, "-needed-l")) {
13051318 try system_libs.put(arg["-needed-l".len..], .{ .needed = true });
1319 } else if (mem.startsWith(u8, arg, "-weak-l")) {
1320 try system_libs.put(arg["-weak-l".len..], .{ .weak = true });
13061321 } else if (mem.startsWith(u8, arg, "-D") or
13071322 mem.startsWith(u8, arg, "-I"))
13081323 {
......@@ -1596,7 +1611,7 @@ fn buildOutputType(
15961611 try clang_argv.appendSlice(it.other_args);
15971612 },
15981613 .framework_dir => try framework_dirs.append(it.only_arg),
1599 .framework => try frameworks.put(gpa, it.only_arg, .{ .needed = false }),
1614 .framework => try frameworks.put(gpa, it.only_arg, .{}),
16001615 .nostdlibinc => want_native_include_dirs = false,
16011616 .strip => strip = true,
16021617 .exec_model => {
......@@ -1879,12 +1894,18 @@ fn buildOutputType(
18791894 ) catch |err| {
18801895 fatal("unable to parse '{s}': {s}", .{ arg, @errorName(err) });
18811896 };
1882 } else if (mem.eql(u8, arg, "-framework") or mem.eql(u8, arg, "-weak_framework")) {
1897 } else if (mem.eql(u8, arg, "-framework")) {
1898 i += 1;
1899 if (i >= linker_args.items.len) {
1900 fatal("expected linker arg after '{s}'", .{arg});
1901 }
1902 try frameworks.put(gpa, linker_args.items[i], .{});
1903 } else if (mem.eql(u8, arg, "-weak_framework")) {
18831904 i += 1;
18841905 if (i >= linker_args.items.len) {
18851906 fatal("expected linker arg after '{s}'", .{arg});
18861907 }
1887 try frameworks.put(gpa, linker_args.items[i], .{ .needed = false });
1908 try frameworks.put(gpa, linker_args.items[i], .{ .weak = true });
18881909 } else if (mem.eql(u8, arg, "-needed_framework")) {
18891910 i += 1;
18901911 if (i >= linker_args.items.len) {
......@@ -1897,6 +1918,14 @@ fn buildOutputType(
18971918 fatal("expected linker arg after '{s}'", .{arg});
18981919 }
18991920 try system_libs.put(linker_args.items[i], .{ .needed = true });
1921 } else if (mem.startsWith(u8, arg, "-weak-l")) {
1922 try system_libs.put(arg["-weak-l".len..], .{ .weak = true });
1923 } else if (mem.eql(u8, arg, "-weak_library")) {
1924 i += 1;
1925 if (i >= linker_args.items.len) {
1926 fatal("expected linker arg after '{s}'", .{arg});
1927 }
1928 try system_libs.put(linker_args.items[i], .{ .weak = true });
19001929 } else if (mem.eql(u8, arg, "-compatibility_version")) {
19011930 i += 1;
19021931 if (i >= linker_args.items.len) {
test/link.zig+10-1
......@@ -45,7 +45,11 @@ pub fn addCases(cases: *tests.StandaloneContext) void {
4545 .requires_macos_sdk = true,
4646 });
4747
48 cases.addBuildFile("test/link/macho/needed_l/build.zig", .{
48 cases.addBuildFile("test/link/macho/needed_library/build.zig", .{
49 .build_modes = true,
50 });
51
52 cases.addBuildFile("test/link/macho/weak_library/build.zig", .{
4953 .build_modes = true,
5054 });
5155
......@@ -54,6 +58,11 @@ pub fn addCases(cases: *tests.StandaloneContext) void {
5458 .requires_macos_sdk = true,
5559 });
5660
61 cases.addBuildFile("test/link/macho/weak_framework/build.zig", .{
62 .build_modes = true,
63 .requires_macos_sdk = true,
64 });
65
5766 // Try to build and run an Objective-C executable.
5867 cases.addBuildFile("test/link/macho/objc/build.zig", .{
5968 .build_modes = true,
test/link/macho/entry/build.zig+1-1
......@@ -22,7 +22,7 @@ pub fn build(b: *Builder) void {
2222 check_exe.checkNext("entryoff {entryoff}");
2323
2424 check_exe.checkInSymtab();
25 check_exe.checkNext("_non_main {n_value}");
25 check_exe.checkNext("{n_value} (__TEXT,__text) external _non_main");
2626
2727 check_exe.checkComputeCompare("vmaddr entryoff +", .{ .op = .eq, .value = .{ .variable = "n_value" } });
2828
test/link/macho/needed_l/a.c deleted-1
......@@ -1 +0,0 @@
1int a = 42;
test/link/macho/needed_l/build.zig deleted-35
......@@ -1,35 +0,0 @@
1const std = @import("std");
2const Builder = std.build.Builder;
3const LibExeObjectStep = std.build.LibExeObjStep;
4
5pub fn build(b: *Builder) void {
6 const mode = b.standardReleaseOptions();
7
8 const test_step = b.step("test", "Test the program");
9 test_step.dependOn(b.getInstallStep());
10
11 const dylib = b.addSharedLibrary("a", null, b.version(1, 0, 0));
12 dylib.setBuildMode(mode);
13 dylib.addCSourceFile("a.c", &.{});
14 dylib.linkLibC();
15 dylib.install();
16
17 // -dead_strip_dylibs
18 // -needed-la
19 const exe = b.addExecutable("test", null);
20 exe.addCSourceFile("main.c", &[0][]const u8{});
21 exe.setBuildMode(mode);
22 exe.linkLibC();
23 exe.linkSystemLibraryNeeded("a");
24 exe.addLibraryPath(b.pathFromRoot("zig-out/lib"));
25 exe.addRPath(b.pathFromRoot("zig-out/lib"));
26 exe.dead_strip_dylibs = true;
27
28 const check = exe.checkObject(.macho);
29 check.checkStart("cmd LOAD_DYLIB");
30 check.checkNext("name @rpath/liba.dylib");
31 test_step.dependOn(&check.step);
32
33 const run_cmd = exe.run();
34 test_step.dependOn(&run_cmd.step);
35}
test/link/macho/needed_l/main.c deleted-3
......@@ -1,3 +0,0 @@
1int main(int argc, char* argv[]) {
2 return 0;
3}
test/link/macho/needed_library/a.c created+1
......@@ -0,0 +1 @@
1int a = 42;
test/link/macho/needed_library/build.zig created+35
......@@ -0,0 +1,35 @@
1const std = @import("std");
2const Builder = std.build.Builder;
3const LibExeObjectStep = std.build.LibExeObjStep;
4
5pub fn build(b: *Builder) void {
6 const mode = b.standardReleaseOptions();
7
8 const test_step = b.step("test", "Test the program");
9 test_step.dependOn(b.getInstallStep());
10
11 const dylib = b.addSharedLibrary("a", null, b.version(1, 0, 0));
12 dylib.setBuildMode(mode);
13 dylib.addCSourceFile("a.c", &.{});
14 dylib.linkLibC();
15 dylib.install();
16
17 // -dead_strip_dylibs
18 // -needed-la
19 const exe = b.addExecutable("test", null);
20 exe.addCSourceFile("main.c", &[0][]const u8{});
21 exe.setBuildMode(mode);
22 exe.linkLibC();
23 exe.linkSystemLibraryNeeded("a");
24 exe.addLibraryPath(b.pathFromRoot("zig-out/lib"));
25 exe.addRPath(b.pathFromRoot("zig-out/lib"));
26 exe.dead_strip_dylibs = true;
27
28 const check = exe.checkObject(.macho);
29 check.checkStart("cmd LOAD_DYLIB");
30 check.checkNext("name @rpath/liba.dylib");
31 test_step.dependOn(&check.step);
32
33 const run_cmd = exe.run();
34 test_step.dependOn(&run_cmd.step);
35}
test/link/macho/needed_library/main.c created+3
......@@ -0,0 +1,3 @@
1int main(int argc, char* argv[]) {
2 return 0;
3}
test/link/macho/weak_framework/build.zig created+24
......@@ -0,0 +1,24 @@
1const std = @import("std");
2const Builder = std.build.Builder;
3const LibExeObjectStep = std.build.LibExeObjStep;
4
5pub fn build(b: *Builder) void {
6 const mode = b.standardReleaseOptions();
7
8 const test_step = b.step("test", "Test the program");
9 test_step.dependOn(b.getInstallStep());
10
11 const exe = b.addExecutable("test", null);
12 exe.addCSourceFile("main.c", &[0][]const u8{});
13 exe.setBuildMode(mode);
14 exe.linkLibC();
15 exe.linkFrameworkWeak("Cocoa");
16
17 const check = exe.checkObject(.macho);
18 check.checkStart("cmd LOAD_WEAK_DYLIB");
19 check.checkNext("name {*}Cocoa");
20 test_step.dependOn(&check.step);
21
22 const run_cmd = exe.run();
23 test_step.dependOn(&run_cmd.step);
24}
test/link/macho/weak_framework/main.c created+3
......@@ -0,0 +1,3 @@
1int main(int argc, char* argv[]) {
2 return 0;
3}
test/link/macho/weak_library/a.c created+9
......@@ -0,0 +1,9 @@
1#include <stdio.h>
2
3int a = 42;
4
5const char* asStr() {
6 static char str[3];
7 sprintf(str, "%d", 42);
8 return str;
9}
test/link/macho/weak_library/build.zig created+38
......@@ -0,0 +1,38 @@
1const std = @import("std");
2const Builder = std.build.Builder;
3const LibExeObjectStep = std.build.LibExeObjStep;
4
5pub fn build(b: *Builder) void {
6 const mode = b.standardReleaseOptions();
7
8 const test_step = b.step("test", "Test the program");
9 test_step.dependOn(b.getInstallStep());
10
11 const dylib = b.addSharedLibrary("a", null, b.version(1, 0, 0));
12 dylib.setBuildMode(mode);
13 dylib.addCSourceFile("a.c", &.{});
14 dylib.linkLibC();
15 dylib.install();
16
17 const exe = b.addExecutable("test", null);
18 exe.addCSourceFile("main.c", &[0][]const u8{});
19 exe.setBuildMode(mode);
20 exe.linkLibC();
21 exe.linkSystemLibraryWeak("a");
22 exe.addLibraryPath(b.pathFromRoot("zig-out/lib"));
23 exe.addRPath(b.pathFromRoot("zig-out/lib"));
24
25 const check = exe.checkObject(.macho);
26 check.checkStart("cmd LOAD_WEAK_DYLIB");
27 check.checkNext("name @rpath/liba.dylib");
28
29 check.checkInSymtab();
30 check.checkNext("(undefined) weak external _a (from liba)");
31 check.checkNext("(undefined) weak external _asStr (from liba)");
32
33 test_step.dependOn(&check.step);
34
35 const run_cmd = exe.run();
36 run_cmd.expectStdOutEqual("42 42");
37 test_step.dependOn(&run_cmd.step);
38}
test/link/macho/weak_library/main.c created+9
......@@ -0,0 +1,9 @@
1#include <stdio.h>
2
3extern int a;
4extern const char* asStr();
5
6int main(int argc, char* argv[]) {
7 printf("%d %s", a, asStr());
8 return 0;
9}