From b3741f99f84dee99e774941dfca4baa0d0b0db87 Mon Sep 17 00:00:00 2001
From: Cheng Shao <terrorjack@type.dance>
Date: Tue, 1 Oct 2024 19:10:02 +0000
Subject: [PATCH] driver: add necessary compile-time flags for wasm PIC mode

This commit adds necessary compile-time flags when compiling for wasm
PIC mode, see added comment for detailed explanation.

(cherry picked from commit f6abaf13c527e372edea2d70f9c012da8624e27c)
---
 compiler/GHC/Driver/Session.hs | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/compiler/GHC/Driver/Session.hs b/compiler/GHC/Driver/Session.hs
index f2e1d36e8a5..85e68e306ca 100644
--- a/compiler/GHC/Driver/Session.hs
+++ b/compiler/GHC/Driver/Session.hs
@@ -3571,7 +3571,17 @@ picCCOpts dflags =
       -- objects, but can't without -fPIC.  See
       -- https://gitlab.haskell.org/ghc/ghc/wikis/commentary/position-independent-code
        | gopt Opt_PIC dflags || ways dflags `hasWay` WayDyn ->
-          ["-fPIC", "-U__PIC__", "-D__PIC__"]
+          ["-fPIC", "-U__PIC__", "-D__PIC__"] ++
+          -- Clang defaults to -fvisibility=hidden for wasm targets,
+          -- but we need these compile-time flags to generate PIC
+          -- objects that can be properly linked by wasm-ld using
+          -- --export-dynamic; without these flags we would need
+          -- -Wl,--export-all at .so link-time which will export
+          -- internal symbols as well, and that severely pollutes the
+          -- global symbol namespace.
+          (if platformArch (targetPlatform dflags) == ArchWasm32
+            then [ "-fvisibility=default", "-fvisibility-inlines-hidden" ]
+            else [])
       -- gcc may be configured to have PIC on by default, let's be
       -- explicit here, see #15847
        | otherwise -> ["-fno-PIC"]
-- 
GitLab