[Git][ghc/ghc][wip/T24344] base: Use strerror_r
Ben Gamari (@bgamari)
gitlab at gitlab.haskell.org
Thu Jan 25 21:22:32 UTC 2024
Ben Gamari pushed to branch wip/T24344 at Glasgow Haskell Compiler / GHC
Commits:
abf485e6 by Ben Gamari at 2024-01-25T16:22:27-05:00
base: Use strerror_r
As noted by #24344, `strerror` is not necessarily thread-safe.
Thankfully, POSIX.1-2001 has long offered `strerror_r`, which is
safe to use.
Fixes #24344.
- - - - -
2 changed files:
- + libraries/base/cbits/strerror.c
- libraries/base/src/Foreign/C/Error.hs
Changes:
=====================================
libraries/base/cbits/strerror.c
=====================================
@@ -0,0 +1,9 @@
+// glibc will only expose the POSIX strerror_r if this is defined.
+#define _POSIX_C_SOURCE 200112L
+
+#include <string.h>
+
+int base_strerror_r(int errnum, char *ptr, size_t buflen)
+{
+ return strerror_r(errnum, ptr, buflen);
+}
=====================================
libraries/base/src/Foreign/C/Error.hs
=====================================
@@ -460,6 +460,20 @@ throwErrnoPathIfMinus1_ = throwErrnoPathIf_ (== -1)
-- conversion of an "errno" value into IO error
-- --------------------------------------------
+foreign import ccall "base_strerror_r"
+ c_strerror_r :: CInt -> Ptr CChar -> CSize -> IO CInt
+
+errnoToString :: Errno -> IO String
+errnoToString errno =
+ allocaBytes len $ \ptr -> do
+ ret <- c_strerror_r errno ptr len
+ if ret /= 0
+ then return "errnoToString failed"
+ else peekCString ptr
+ where
+ len :: Num a => a
+ len = 512
+
-- | Construct an 'IOError' based on the given 'Errno' value.
-- The optional information can be used to improve the accuracy of
-- error messages.
@@ -470,7 +484,7 @@ errnoToIOError :: String -- ^ the location where the error occurred
-> Maybe String -- ^ optional filename associated with the error
-> IOError
errnoToIOError loc errno maybeHdl maybeName = unsafePerformIO $ do
- str <- strerror errno >>= peekCString
+ str <- errnoToString errno
return (IOError maybeHdl errType loc str (Just errno') maybeName)
where
Errno errno' = errno
@@ -576,5 +590,3 @@ errnoToIOError loc errno maybeHdl maybeName = unsafePerformIO $ do
| errno == eXDEV = UnsupportedOperation
| otherwise = OtherError
-foreign import ccall unsafe "string.h" strerror :: Errno -> IO (Ptr CChar)
-
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/abf485e6186beed0180f64a11bdcc82ca87525c4
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/abf485e6186beed0180f64a11bdcc82ca87525c4
You're receiving this email because of your account on gitlab.haskell.org.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/ghc-commits/attachments/20240125/e28d031b/attachment-0001.html>
More information about the ghc-commits
mailing list