Skip to content
Snippets Groups Projects
Commit dc28bdac authored by Jens Nolte's avatar Jens Nolte
Browse files

Add helper for mmap

parent 1f2f984d
No related branches found
No related tags found
No related merge requests found
...@@ -99,6 +99,7 @@ library ...@@ -99,6 +99,7 @@ library
network, network,
quasar, quasar,
template-haskell, template-haskell,
unix,
unordered-containers, unordered-containers,
utf8-string, utf8-string,
stm, stm,
......
...@@ -2,24 +2,28 @@ ...@@ -2,24 +2,28 @@
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TemplateHaskell #-}
module Quasar.Wayland.Utils.SharedMemory ( module Quasar.Wayland.Utils.SharedMemory (
allocateShmFd, memfdCreate,
mmap,
) where ) where
import Foreign
import Foreign.Concurrent qualified as FC
import Foreign.C.Error import Foreign.C.Error
import Language.C.Inline qualified as C import Language.C.Inline qualified as C
import Language.C.Inline.Unsafe qualified as CU import Language.C.Inline.Unsafe qualified as CU
import Quasar.Prelude import Quasar.Prelude
import Quasar.Wayland.Utils.InlineC import Quasar.Wayland.Utils.InlineC
import System.Posix.Types (COff(..), Fd(Fd)) import System.Posix.Types (Fd(Fd), COff(..))
C.context ctx C.context ctx
C.verbatim "#define _GNU_SOURCE" C.verbatim "#define _GNU_SOURCE"
C.include "<unistd.h>" C.include "<unistd.h>"
C.include "<stdint.h>"
C.include "<sys/mman.h>" C.include "<sys/mman.h>"
allocateShmFd :: COff -> IO Fd memfdCreate :: COff -> IO Fd
allocateShmFd size = Fd <$> throwErrnoIfMinus1 "allocateShmFd" memfdCreate size = Fd <$> throwErrnoIfMinus1 "memfd_create/ftruncate"
[CU.block| [CU.block|
int { int {
int fd = memfd_create("shm", MFD_CLOEXEC | MFD_ALLOW_SEALING); int fd = memfd_create("shm", MFD_CLOEXEC | MFD_ALLOW_SEALING);
...@@ -34,3 +38,14 @@ allocateShmFd size = Fd <$> throwErrnoIfMinus1 "allocateShmFd" ...@@ -34,3 +38,14 @@ allocateShmFd size = Fd <$> throwErrnoIfMinus1 "allocateShmFd"
return fd; return fd;
} }
|] |]
mmap :: Fd -> C.CSize -> IO (ForeignPtr Word8)
mmap (Fd fd) size = do
ptr <- fmap intPtrToPtr . throwErrnoIfMinus1 "mmap" $
ptrToIntPtr <$> [CU.exp| void*{ mmap(NULL, $(size_t size), PROT_READ | PROT_WRITE, MAP_SHARED, $(int fd), 0) } |]
FC.newForeignPtr ptr (munmap ptr size)
munmap :: Ptr a -> C.CSize -> IO ()
munmap (castPtr -> ptr) size =
throwErrnoIfMinus1_ "munmap" $
[CU.exp| int { munmap($(void* ptr), $(size_t size)) } |]
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment