From a0379db01dce6b4371ead2ce82e4221e1ae8c334 Mon Sep 17 00:00:00 2001
From: Paolo Capriotti <p.capriotti@gmail.com>
Date: Wed, 4 Apr 2012 15:33:53 +0100
Subject: [PATCH] Add workaround for systems without clearenv.

---
 System/Posix/Env.hsc | 11 ++++++++++-
 configure.ac         |  2 +-
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/System/Posix/Env.hsc b/System/Posix/Env.hsc
index 51e8891..be4711b 100644
--- a/System/Posix/Env.hsc
+++ b/System/Posix/Env.hsc
@@ -36,7 +36,7 @@ import Foreign.C.String
 import Foreign.Marshal.Array
 import Foreign.Ptr
 import Foreign.Storable
-import Control.Monad (liftM, forM_, void)
+import Control.Monad
 import Data.Maybe (fromMaybe)
 #if __GLASGOW_HASKELL__ > 700
 import System.Posix.Internals (withFilePath, peekFilePath)
@@ -83,6 +83,7 @@ getEnvironmentPrim = do
       mapM peekFilePath arr
 
 getCEnviron :: IO (Ptr CString)
+
 #if darwin_HOST_OS
 -- You should not access _environ directly on Darwin in a bundle/shared library.
 -- See #2458 and http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man7/environ.7.html
@@ -170,7 +171,15 @@ setEnv key value False = do
 
 -- |The 'clearEnv' function clears the environment of all name-value pairs.
 clearEnv :: IO ()
+#if HAVE_CLEARENV
 clearEnv = void c_clearenv
 
 foreign import ccall unsafe "clearenv"
   c_clearenv :: IO Int
+#else
+-- Fallback to 'environ[0] = NULL'.
+clearEnv = do
+  c_environ <- getCEnviron
+  unless (c_environ == nullPtr) $
+    poke c_environ nullPtr
+#endif
diff --git a/configure.ac b/configure.ac
index 775af6c..ebf708d 100644
--- a/configure.ac
+++ b/configure.ac
@@ -28,7 +28,7 @@ AC_CHECK_HEADERS([termios.h time.h unistd.h utime.h])
 
 AC_CHECK_FUNCS([getgrgid_r getgrnam_r getpwnam_r getpwuid_r getpwnam getpwuid])
 AC_CHECK_FUNCS([getpwent getgrent])
-AC_CHECK_FUNCS([lchown setenv sysconf unsetenv])
+AC_CHECK_FUNCS([lchown setenv sysconf unsetenv clearenv])
 AC_CHECK_FUNCS([nanosleep])
 AC_CHECK_FUNCS([ptsname])
 AC_CHECK_FUNCS([setitimer])
-- 
GitLab