{-# LINE 1 "libraries/ghc-internal/src/GHC/Internal/IO/Handle/Lock/Flock.hsc" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE InterruptibleFFI #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | File locking via POSIX @flock@.
module GHC.Internal.IO.Handle.Lock.Flock where




{-# LINE 15 "libraries/ghc-internal/src/GHC/Internal/IO/Handle/Lock/Flock.hsc" #-}



import GHC.Internal.Data.Bits
import GHC.Internal.Data.Function
import GHC.Internal.Foreign.C.Error
import GHC.Internal.Foreign.C.Types
import GHC.Internal.Base
import GHC.Internal.IO.Exception
import GHC.Internal.IO.FD
import GHC.Internal.IO.Handle.FD
import GHC.Internal.IO.Handle.Lock.Common
import GHC.Internal.IO.Handle.Types (Handle)

lockImpl :: Handle -> String -> LockMode -> Bool -> IO Bool
lockImpl :: Handle -> String -> LockMode -> Bool -> IO Bool
lockImpl Handle
h String
ctx LockMode
mode Bool
block = do
  FD{fdFD = fd} <- Handle -> IO FD
handleToFd Handle
h
  let flags = CInt
cmode CInt -> CInt -> CInt
forall a. Bits a => a -> a -> a
.|. (if Bool
block then CInt
0 else CInt
4)
{-# LINE 33 "libraries/ghc-internal/src/GHC/Internal/IO/Handle/Lock/Flock.hsc" #-}
  fix $ \retry -> c_flock fd flags >>= \case
    0 -> return True
    _ -> getErrno >>= \errno -> if
      | not block
      , errno == eAGAIN || errno == eACCES -> return False
      | errno == eINTR -> retry
      | otherwise -> ioException $ errnoToIOError ctx errno (Just h) Nothing
  where
    cmode :: CInt
cmode = case LockMode
mode of
      LockMode
SharedLock    -> CInt
1
{-# LINE 43 "libraries/ghc-internal/src/GHC/Internal/IO/Handle/Lock/Flock.hsc" #-}
      ExclusiveLock -> 2
{-# LINE 44 "libraries/ghc-internal/src/GHC/Internal/IO/Handle/Lock/Flock.hsc" #-}

unlockImpl :: Handle -> IO ()
unlockImpl :: Handle -> IO ()
unlockImpl Handle
h = do
  FD{fdFD = fd} <- Handle -> IO FD
handleToFd Handle
h
  throwErrnoIfMinus1_ "flock" $ c_flock fd 8
{-# LINE 49 "libraries/ghc-internal/src/GHC/Internal/IO/Handle/Lock/Flock.hsc" #-}

foreign import ccall interruptible "flock"
  c_flock :: CInt -> CInt -> IO CInt


{-# LINE 54 "libraries/ghc-internal/src/GHC/Internal/IO/Handle/Lock/Flock.hsc" #-}