build/toolchain/musl-host-gcc: add pie feature, disabled by default

This isn't enabled anywhere, but we should enable it for all of our
binaries.

Change-Id: I77dc163a7085c792c0b0d64e6423e9117b596ec4
Reviewed-on: https://review.monogon.dev/c/monogon/+/1838
Reviewed-by: Lorenz Brun <lorenz@monogon.tech>
Tested-by: Jenkins CI
diff --git a/build/toolchain/cc_toolchain_config.bzl b/build/toolchain/cc_toolchain_config.bzl
index a40dec0..0fdb23e 100644
--- a/build/toolchain/cc_toolchain_config.bzl
+++ b/build/toolchain/cc_toolchain_config.bzl
@@ -59,6 +59,11 @@
     ACTION_NAMES.lto_backend,
 ]
 
+executable_link_actions = [
+    ACTION_NAMES.cpp_link_executable,
+    ACTION_NAMES.lto_index_for_executable,
+]
+
 all_link_actions = [
     ACTION_NAMES.cpp_link_executable,
     ACTION_NAMES.cpp_link_dynamic_library,
@@ -117,6 +122,32 @@
             ),
         ],
     )
+    pie_feature = feature(
+        name = "pie",
+        enabled = False,
+        flag_sets = [
+            flag_set(
+                actions = executable_link_actions,
+                flag_groups = ([
+                    flag_group(
+                        flags = [
+                            "-static-pie",
+                        ],
+                    ),
+                ]),
+            ),
+            flag_set(
+                actions = all_compile_actions,
+                flag_groups = ([
+                    flag_group(
+                        flags = [
+                            "-fPIE",
+                        ],
+                    ),
+                ]),
+            ),
+        ],
+    )
     default_link_flags_feature = feature(
         name = "default_link_flags",
         enabled = True,
@@ -175,7 +206,12 @@
 
     return cc_common.create_cc_toolchain_config_info(
         ctx = ctx,
-        features = [default_link_flags_feature, link_full_libc_feature, cpp_feature],
+        features = [
+            default_link_flags_feature,
+            link_full_libc_feature,
+            cpp_feature,
+            pie_feature,
+        ],
         cxx_builtin_include_directories = ctx.attr.host_includes,
         toolchain_identifier = "k8-toolchain",
         host_system_name = "local",
diff --git a/build/toolchain/musl-host-gcc/musl.spec b/build/toolchain/musl-host-gcc/musl.spec
index c726fe5..49f0176 100644
--- a/build/toolchain/musl-host-gcc/musl.spec
+++ b/build/toolchain/musl-host-gcc/musl.spec
@@ -13,13 +13,13 @@
 libgcc.a%s %:if-exists(libgcc_eh.a%s)
 
 *startfile:
-%{!shared: %R/lib/Scrt1.o} %R/lib/crti.o crtbeginS.o%s
+%{static-pie: %R/lib/rcrt1.o; !shared: %R/lib/Scrt1.o} %R/lib/crti.o crtbeginS.o%s
 
 *endfile:
 crtendS.o%s %R/lib/crtn.o
 
 *link:
--no-dynamic-linker -nostdlib -static %{rdynamic:-export-dynamic}
+%{static-pie: -pie} -no-dynamic-linker -nostdlib -static %{rdynamic:-export-dynamic}
 
 *esp_link: