[zlib] Add zlib target for Rust host_toolchain builds

Enable zlib to be built with `-fPIC` to allow Rust host_toolchain binaries to
link to zlib.

Bug: 36315
Bug: 8892
Change-Id: I0386586e7d69f0994a28438d5a0f652c983ab648
diff --git a/BUILD.gn b/BUILD.gn
index ec8bb2e..9819f66 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -36,6 +36,14 @@
   cflags = [ "-Wno-implicit-function-declaration" ]
 }
 
+# TODO(36315): Remove workaround for Rust host_toolchain
+config("zlib_config_for_rust_host") {
+  # Without `-fPIC`, we get the error:
+  # > ld.lld: error: can't create dynamic relocation R_X86_64_64 against local symbol in readonly
+  # > segment
+  cflags = ["-fPIC"]
+}
+
 if (is_fuchsia) {
   shared_library("zlib") {
     output_name = "z"
@@ -55,39 +63,60 @@
   }
 }
 
-source_set("zlib_static") {
-  sources = [
-    "adler32.c",
-    "compress.c",
-    "crc32.c",
-    "crc32.h",
-    "deflate.c",
-    "deflate.h",
-    "gzclose.c",
-    "gzguts.h",
-    "gzlib.c",
-    "gzread.c",
-    "gzwrite.c",
-    "infback.c",
-    "inffast.c",
-    "inffast.h",
-    "inffixed.h",
-    "inflate.c",
-    "inflate.h",
-    "inftrees.c",
-    "inftrees.h",
-    "trees.c",
-    "trees.h",
-    "uncompr.c",
-    "zconf.h",
-    "zlib.h",
-    "zutil.c",
-    "zutil.h",
-  ]
+template("zlib_library") {
+  target(invoker.library_type, target_name) {
+    forward_variables_from(invoker, "*")
 
-  configs += [ ":zlib_warnings" ]
-  configs -= [ "//build/config:symbol_visibility_hidden" ]
-  public_configs = [ ":zlib_config" ]
+    if (!defined(rust_host)) {
+      rust_host = false
+    }
+
+    sources = [
+      "adler32.c",
+      "compress.c",
+      "crc32.c",
+      "crc32.h",
+      "deflate.c",
+      "deflate.h",
+      "gzclose.c",
+      "gzguts.h",
+      "gzlib.c",
+      "gzread.c",
+      "gzwrite.c",
+      "infback.c",
+      "inffast.c",
+      "inffast.h",
+      "inffixed.h",
+      "inflate.c",
+      "inflate.h",
+      "inftrees.c",
+      "inftrees.h",
+      "trees.c",
+      "trees.h",
+      "uncompr.c",
+      "zconf.h",
+      "zlib.h",
+      "zutil.c",
+      "zutil.h",
+    ]
+
+    configs += [ ":zlib_warnings" ]
+    configs -= [ "//build/config:symbol_visibility_hidden" ]
+
+    public_configs = [ ":zlib_config" ]
+    if (rust_host) {
+      public_configs += [ ":zlib_config_for_rust_host" ]
+    }
+  }
+}
+
+zlib_library("zlib_static") {
+  library_type = "source_set"
+}
+
+zlib_library("zlib_for_rust_host") {
+  library_type = "static_library"
+  rust_host = true
 }
 
 config("minizip_warnings") {