From 3e99afdbfe9a66bc5461148a4754c1e88b33fb88 Mon Sep 17 00:00:00 2001 From: Isaac Freund Date: Wed, 8 Mar 2023 14:21:33 +0100 Subject: [PATCH] build: add -Dpie option It is becoming increasingly common for distributions to want to enable PIE for all binaries and zig currently does not provide any way to do so aside from patching the build.zig. --- CMakeLists.txt | 7 +++++++ build.zig | 2 ++ 2 files changed, 9 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 925fd2d639..501d12889f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -827,6 +827,12 @@ else() set(ZIG_STATIC_ARG "") endif() +if(CMAKE_POSITION_INDEPENDENT_CODE) + set(ZIG_PIE_ARG="-Dpie") +else() + set(ZIG_PIE_ARG="") +endif() + set(ZIG_BUILD_ARGS --zig-lib-dir "${CMAKE_SOURCE_DIR}/lib" "-Dconfig_h=${ZIG_CONFIG_H_OUT}" @@ -835,6 +841,7 @@ set(ZIG_BUILD_ARGS ${ZIG_STATIC_ARG} ${ZIG_NO_LIB_ARG} ${ZIG_SINGLE_THREADED_ARG} + ${ZIG_PIE_ARG} "-Dtarget=${ZIG_TARGET_TRIPLE}" "-Dcpu=${ZIG_TARGET_MCPU}" "-Dversion-string=${RESOLVED_ZIG_VERSION}" diff --git a/build.zig b/build.zig index a95c9dfb58..12e5d014e2 100644 --- a/build.zig +++ b/build.zig @@ -152,6 +152,7 @@ pub fn build(b: *std.Build) !void { const link_libc = b.option(bool, "force-link-libc", "Force self-hosted compiler to link libc") orelse (enable_llvm or only_c); const sanitize_thread = b.option(bool, "sanitize-thread", "Enable thread-sanitization") orelse false; const strip = b.option(bool, "strip", "Omit debug information"); + const pie = b.option(bool, "pie", "Produce a Position Independent Executable"); const value_tracing = b.option(bool, "value-tracing", "Enable extra state tracking to help troubleshoot bugs in the compiler (using the std.debug.Trace API)") orelse false; const mem_leak_frames: u32 = b.option(u32, "mem-leak-frames", "How many stack frames to print when a memory leak occurs. Tests get 2x this amount.") orelse blk: { @@ -162,6 +163,7 @@ pub fn build(b: *std.Build) !void { const exe = addCompilerStep(b, optimize, target); exe.strip = strip; + exe.pie = pie; exe.sanitize_thread = sanitize_thread; exe.build_id = b.option(bool, "build-id", "Include a build id note") orelse false; exe.install();