summaryrefslogtreecommitdiff
path: root/src/Mmap.hs
blob: d62dcab80b55b05ccf488331865121eeea7193ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
{-# LANGUAGE ForeignFunctionInterface #-}
module Mmap where

import Control.Exception
import Data.ByteString (ByteString)
import qualified Data.ByteString.Unsafe as BS
import Foreign
import Foreign.C.Types
import System.Posix.IO
import System.Posix.Types

import AtomicPrint


foreign import ccall "ircbrowse_mmap"
  c_mmap :: CInt -> Ptr CSize -> IO (Ptr Word8)
  --        fd      out length

foreign import ccall "ircbrowse_munmap"
  c_munmap :: Ptr Word8 -> CSize -> IO ()
  --          addr         length

-- | Returns Nothing if the open(2) fails.
mapFile :: FilePath -> IO (Maybe ByteString)
mapFile path = mask_ $ do
  -- if open fails, we simply return Nothing, and nothing has happened yet so that's fine
  try @IOException (openFd path ReadOnly defaultFileFlags) >>= \case
    Left _ -> return Nothing
    Right (Fd fd) -> do
      -- do the mmap; if it fails, close the file, ignoring exceptions there
      (addr, filelen) <-
        onException
          (alloca $ \lengthp -> do
            addr <- c_mmap fd lengthp
            lengthval <- peek lengthp
            return (addr, lengthval))
          (catch @SomeException (closeFd (Fd fd))
             (\_ -> return ()))

      -- mmap succeeded, close the file; if closing fails, something is badly wrong, so unmap, and if that throws an exception propagate that
      onException
        (closeFd (Fd fd))
        (do atomicPrintNoWaitS ("[munmap " ++ show addr ++ " as close(2) exception handler]")
            c_munmap addr filelen)

      -- close succeeded, we're safe now since bytestring construction will not
      -- fail (and no exceptions are coming from outside as we're masked)
      if addr == nullPtr
        then fail "mapFile: could not mmap"
        else do bs <- BS.unsafePackCStringFinalizer addr (fromIntegral @CSize @Int filelen)
                        (do atomicPrintNoWaitS ("[munmap " ++ show addr ++ "]")
                            c_munmap addr filelen)
                atomicPrintNoWaitS ("[mmap " ++ show addr ++ "]")
                return (Just bs)