diff --git a/lib/std/dynamic_library.zig b/lib/std/dynamic_library.zig index 6c99ee644b..68181e5742 100644 --- a/lib/std/dynamic_library.zig +++ b/lib/std/dynamic_library.zig @@ -59,8 +59,14 @@ const RDebug = extern struct { r_ldbase: usize, }; +/// TODO make it possible to reference this same external symbol 2x so we don't need this +/// helper function. +pub fn get_DYNAMIC() ?[*]elf.Dyn { + return @extern([*]elf.Dyn, .{ .name = "_DYNAMIC", .linkage = .Weak }); +} + pub fn linkmap_iterator(phdrs: []elf.Phdr) !LinkMap.Iterator { - const _DYNAMIC = @extern([*]elf.Dyn, .{ .name = "_DYNAMIC", .linkage = .Weak }) orelse { + const _DYNAMIC = get_DYNAMIC() orelse { // No PT_DYNAMIC means this is either a statically-linked program or a // badly corrupted dynamically-linked one. return LinkMap.Iterator{ .current = null }; diff --git a/lib/std/start.zig b/lib/std/start.zig index 6e15dad84c..7d3a9c45c7 100644 --- a/lib/std/start.zig +++ b/lib/std/start.zig @@ -187,9 +187,8 @@ fn wWinMainCRTStartup() callconv(std.os.windows.WINAPI) noreturn { // TODO https://github.com/ziglang/zig/issues/265 fn posixCallMainAndExit() noreturn { - if (builtin.os.tag == .freebsd) { - @setAlignStack(16); - } + @setAlignStack(16); + const argc = argc_argv_ptr[0]; const argv = @ptrCast([*][*:0]u8, argc_argv_ptr + 1); @@ -208,8 +207,13 @@ fn posixCallMainAndExit() noreturn { @import("os/linux/start_pie.zig").apply_relocations(); } - // Initialize the TLS area - std.os.linux.tls.initStaticTLS(); + // Initialize the TLS area. We do a runtime check here to make sure + // this code is truly being statically executed and not inside a dynamic + // loader, otherwise this would clobber the thread ID register. + const is_dynamic = @import("dynamic_library.zig").get_DYNAMIC() != null; + if (!is_dynamic) { + std.os.linux.tls.initStaticTLS(); + } // TODO This is disabled because what should we do when linking libc and this code // does not execute? And also it's causing a test failure in stack traces in release modes.