diff --git a/src/build_settings.cpp b/src/build_settings.cpp index df9142c74..4d8a5a495 100644 --- a/src/build_settings.cpp +++ b/src/build_settings.cpp @@ -1898,6 +1898,20 @@ gb_internal void init_build_context(TargetMetrics *cross_target, Subtarget subta } break; } + } else if (metrics->os == TargetOs_linux) { + if (bc->reloc_mode == RelocMode_Default) { + bc->reloc_mode = RelocMode_PIC; + } + } else if (metrics->os == TargetOs_openbsd) { + // Always use PIC for OpenBSD: it defaults to PIE + if (bc->reloc_mode == RelocMode_Default) { + bc->reloc_mode = RelocMode_PIC; + } + } else if (metrics->arch == TargetArch_riscv64) { + // NOTE(laytan): didn't seem to work without this. + if (bc->reloc_mode == RelocMode_Default) { + bc->reloc_mode = RelocMode_PIC; + } } else if (metrics->os == TargetOs_linux && subtarget == Subtarget_Android) { switch (metrics->arch) { case TargetArch_arm64: diff --git a/src/linker.cpp b/src/linker.cpp index 50bb4e524..1af78de15 100644 --- a/src/linker.cpp +++ b/src/linker.cpp @@ -788,7 +788,12 @@ try_cross_linking:; } if (build_context.build_mode == BuildMode_Executable && build_context.reloc_mode == RelocMode_PIC) { - // Do not disable PIE, let the linker choose. (most likely you want it enabled) + if (build_context.metrics.os == TargetOs_linux) { + // Linux does not enable PIE by default but required for ASLR + link_settings = gb_string_appendc(link_settings, "-pie "); + } else { + // Do not disable PIE, let the linker choose. (most likely you want it enabled) + } } else if (build_context.build_mode != BuildMode_DynamicLibrary) { if (build_context.metrics.os != TargetOs_openbsd && build_context.metrics.arch != TargetArch_riscv64 @@ -906,6 +911,9 @@ try_cross_linking:; // need to pass -z nobtcfi in order to allow the resulting program to run under // OpenBSD 7.4 and newer. Once support is added at compile time, this can be dropped. platform_lib_str = gb_string_appendc(platform_lib_str, "-Wl,-z,nobtcfi "); + } else if (build_context.metrics.os == TargetOs_linux) { + // required for RELRO + platform_lib_str = gb_string_appendc(platform_lib_str, "-Wl,-z,now -Wl,-z,relro "); } if (is_android) { diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 40aceb7fe..e08116736 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -3156,16 +3156,6 @@ gb_internal bool lb_generate_code(lbGenerator *gen) { switch (build_context.reloc_mode) { case RelocMode_Default: - if (build_context.metrics.os == TargetOs_openbsd) { - // Always use PIC for OpenBSD: it defaults to PIE - reloc_mode = LLVMRelocPIC; - } - - if (build_context.metrics.arch == TargetArch_riscv64) { - // NOTE(laytan): didn't seem to work without this. - reloc_mode = LLVMRelocPIC; - } - break; case RelocMode_Static: reloc_mode = LLVMRelocStatic;