1 {-# OPTIONS_GHC -XNoImplicitPrelude -#include "HsBase.h" #-}
2 {-# OPTIONS_GHC -fno-warn-unused-matches #-}
3 {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
4 {-# OPTIONS_GHC -XRecordWildCards #-}
5 {-# OPTIONS_HADDOCK hide #-}
7 -----------------------------------------------------------------------------
9 -- Module : GHC.IO.Handle.Internals
10 -- Copyright : (c) The University of Glasgow, 1994-2001
11 -- License : see libraries/base/LICENSE
13 -- Maintainer : libraries@haskell.org
14 -- Stability : internal
15 -- Portability : non-portable
17 -- This module defines the basic operations on I\/O \"handles\". All
18 -- of the operations defined here are independent of the underlying
21 -----------------------------------------------------------------------------
24 module GHC.IO.Handle.Internals (
25 withHandle, withHandle', withHandle_,
26 withHandle__', withHandle_', withAllHandles__,
27 wantWritableHandle, wantReadableHandle, wantReadableHandle_,
30 mkHandle, mkFileHandle, mkDuplexHandle,
31 openTextEncoding, closeTextCodecs, initBufferState,
32 dEFAULT_CHAR_BUFFER_SIZE,
34 flushBuffer, flushWriteBuffer, flushWriteBuffer_, flushCharReadBuffer,
35 flushCharBuffer, flushByteReadBuffer,
37 readTextDevice, writeTextDevice, readTextDeviceNonBlocking,
41 ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable,
42 ioe_finalizedHandle, ioe_bufsiz,
44 hClose_help, hLookAhead_,
46 HandleFinalizer, handleFinalizer,
53 import GHC.IO.Encoding as Encoding
54 import GHC.IO.Handle.Types
56 import GHC.IO.BufferedIO (BufferedIO)
57 import GHC.IO.Exception
58 import GHC.IO.Device (IODevice, SeekMode(..))
59 import qualified GHC.IO.Device as IODevice
60 import qualified GHC.IO.BufferedIO as Buffered
66 import GHC.Num ( Num(..) )
73 import Foreign hiding (unsafePerformIO)
74 -- import System.IO.Error
75 import System.Posix.Internals hiding (FD)
82 -- ---------------------------------------------------------------------------
83 -- Creating a new handle
85 type HandleFinalizer = FilePath -> MVar Handle__ -> IO ()
87 newFileHandle :: FilePath -> Maybe HandleFinalizer -> Handle__ -> IO Handle
88 newFileHandle filepath mb_finalizer hc = do
91 Just finalizer -> addMVarFinalizer m (finalizer filepath m)
93 return (FileHandle filepath m)
95 -- ---------------------------------------------------------------------------
96 -- Working with Handles
99 In the concurrent world, handles are locked during use. This is done
100 by wrapping an MVar around the handle which acts as a mutex over
101 operations on the handle.
103 To avoid races, we use the following bracketing operations. The idea
104 is to obtain the lock, do some operation and replace the lock again,
105 whether the operation succeeded or failed. We also want to handle the
106 case where the thread receives an exception while processing the IO
107 operation: in these cases we also want to relinquish the lock.
109 There are three versions of @withHandle@: corresponding to the three
110 possible combinations of:
112 - the operation may side-effect the handle
113 - the operation may return a result
115 If the operation generates an error or an exception is raised, the
116 original handle is always replaced.
119 {-# INLINE withHandle #-}
120 withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
121 withHandle fun h@(FileHandle _ m) act = withHandle' fun h m act
122 withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act
124 withHandle' :: String -> Handle -> MVar Handle__
125 -> (Handle__ -> IO (Handle__,a)) -> IO a
126 withHandle' fun h m act =
128 (h',v) <- do_operation fun h act m
129 checkHandleInvariants h'
133 {-# INLINE withHandle_ #-}
134 withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
135 withHandle_ fun h@(FileHandle _ m) act = withHandle_' fun h m act
136 withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act
138 withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a
139 withHandle_' fun h m act = withHandle' fun h m $ \h_ -> do
143 withAllHandles__ :: String -> Handle -> (Handle__ -> IO Handle__) -> IO ()
144 withAllHandles__ fun h@(FileHandle _ m) act = withHandle__' fun h m act
145 withAllHandles__ fun h@(DuplexHandle _ r w) act = do
146 withHandle__' fun h r act
147 withHandle__' fun h w act
149 withHandle__' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO Handle__)
151 withHandle__' fun h m act =
153 h' <- do_operation fun h act m
154 checkHandleInvariants h'
158 do_operation :: String -> Handle -> (Handle__ -> IO a) -> MVar Handle__ -> IO a
159 do_operation fun h act m = do
161 checkHandleInvariants h_
162 act h_ `catchException` handler h_
167 _ | Just ioe <- fromException e ->
168 ioError (augmentIOError ioe fun h)
169 _ | Just async_ex <- fromException e -> do -- see Note [async]
170 let _ = async_ex :: AsyncException
173 do_operation fun h act m
179 -- If an asynchronous exception is raised during an I/O operation,
180 -- normally it is fine to just re-throw the exception synchronously.
181 -- However, if we are inside an unsafePerformIO or an
182 -- unsafeInterleaveIO, this would replace the enclosing thunk with the
183 -- exception raised, which is wrong (#3997). We have to release the
184 -- lock on the Handle, but what do we replace the thunk with? What
185 -- should happen when the thunk is subsequently demanded again?
187 -- The only sensible choice we have is to re-do the IO operation on
188 -- resumption, but then we have to be careful in the IO library that
189 -- this is always safe to do. In particular we should
191 -- never perform any side-effects before an interruptible operation
193 -- because the interruptible operation may raise an asynchronous
194 -- exception, which may cause the operation and its side effects to be
195 -- subsequently performed again.
197 -- Re-doing the IO operation is achieved by:
198 -- - using throwTo to re-throw the asynchronous exception asynchronously
199 -- in the current thread
200 -- - on resumption, it will be as if throwTo returns. In that case, we
201 -- recursively invoke the original operation (see do_operation above).
203 -- Interruptible operations in the I/O library are:
204 -- - threadWaitRead/threadWaitWrite
205 -- - fillReadBuffer/flushWriteBuffer
206 -- - readTextDevice/writeTextDevice
208 augmentIOError :: IOException -> String -> Handle -> IOException
209 augmentIOError ioe@IOError{ ioe_filename = fp } fun h
210 = ioe { ioe_handle = Just h, ioe_location = fun, ioe_filename = filepath }
213 | otherwise = case h of
214 FileHandle path _ -> Just path
215 DuplexHandle path _ _ -> Just path
217 -- ---------------------------------------------------------------------------
218 -- Wrapper for write operations.
220 wantWritableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
221 wantWritableHandle fun h@(FileHandle _ m) act
222 = wantWritableHandle' fun h m act
223 wantWritableHandle fun h@(DuplexHandle _ _ m) act
224 = withHandle_' fun h m act
227 :: String -> Handle -> MVar Handle__
228 -> (Handle__ -> IO a) -> IO a
229 wantWritableHandle' fun h m act
230 = withHandle_' fun h m (checkWritableHandle act)
232 checkWritableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
233 checkWritableHandle act h_@Handle__{..}
235 ClosedHandle -> ioe_closedHandle
236 SemiClosedHandle -> ioe_closedHandle
237 ReadHandle -> ioe_notWritable
238 ReadWriteHandle -> do
239 buf <- readIORef haCharBuffer
240 when (not (isWriteBuffer buf)) $ do
241 flushCharReadBuffer h_
242 flushByteReadBuffer h_
243 buf <- readIORef haCharBuffer
244 writeIORef haCharBuffer buf{ bufState = WriteBuffer }
245 buf <- readIORef haByteBuffer
246 buf' <- Buffered.emptyWriteBuffer haDevice buf
247 writeIORef haByteBuffer buf'
251 -- ---------------------------------------------------------------------------
252 -- Wrapper for read operations.
254 wantReadableHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
255 wantReadableHandle fun h act = withHandle fun h (checkReadableHandle act)
257 wantReadableHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
258 wantReadableHandle_ fun h@(FileHandle _ m) act
259 = wantReadableHandle' fun h m act
260 wantReadableHandle_ fun h@(DuplexHandle _ m _) act
261 = withHandle_' fun h m act
264 :: String -> Handle -> MVar Handle__
265 -> (Handle__ -> IO a) -> IO a
266 wantReadableHandle' fun h m act
267 = withHandle_' fun h m (checkReadableHandle act)
269 checkReadableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
270 checkReadableHandle act h_@Handle__{..} =
272 ClosedHandle -> ioe_closedHandle
273 SemiClosedHandle -> ioe_closedHandle
274 AppendHandle -> ioe_notReadable
275 WriteHandle -> ioe_notReadable
276 ReadWriteHandle -> do
277 -- a read/write handle and we want to read from it. We must
278 -- flush all buffered write data first.
279 cbuf <- readIORef haCharBuffer
280 when (isWriteBuffer cbuf) $ do
281 cbuf' <- flushWriteBuffer_ h_ cbuf
282 writeIORef haCharBuffer cbuf'{ bufState = ReadBuffer }
283 bbuf <- readIORef haByteBuffer
284 writeIORef haByteBuffer bbuf{ bufState = ReadBuffer }
288 -- ---------------------------------------------------------------------------
289 -- Wrapper for seek operations.
291 wantSeekableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
292 wantSeekableHandle fun h@(DuplexHandle _ _ _) _act =
293 ioException (IOError (Just h) IllegalOperation fun
294 "handle is not seekable" Nothing Nothing)
295 wantSeekableHandle fun h@(FileHandle _ m) act =
296 withHandle_' fun h m (checkSeekableHandle act)
298 checkSeekableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
299 checkSeekableHandle act handle_@Handle__{haDevice=dev} =
300 case haType handle_ of
301 ClosedHandle -> ioe_closedHandle
302 SemiClosedHandle -> ioe_closedHandle
303 AppendHandle -> ioe_notSeekable
304 _ -> do b <- IODevice.isSeekable dev
305 if b then act handle_
308 -- -----------------------------------------------------------------------------
311 ioe_closedHandle, ioe_EOF,
312 ioe_notReadable, ioe_notWritable, ioe_cannotFlushNotSeekable,
313 ioe_notSeekable, ioe_invalidCharacter :: IO a
315 ioe_closedHandle = ioException
316 (IOError Nothing IllegalOperation ""
317 "handle is closed" Nothing Nothing)
318 ioe_EOF = ioException
319 (IOError Nothing EOF "" "" Nothing Nothing)
320 ioe_notReadable = ioException
321 (IOError Nothing IllegalOperation ""
322 "handle is not open for reading" Nothing Nothing)
323 ioe_notWritable = ioException
324 (IOError Nothing IllegalOperation ""
325 "handle is not open for writing" Nothing Nothing)
326 ioe_notSeekable = ioException
327 (IOError Nothing IllegalOperation ""
328 "handle is not seekable" Nothing Nothing)
329 ioe_cannotFlushNotSeekable = ioException
330 (IOError Nothing IllegalOperation ""
331 "cannot flush the read buffer: underlying device is not seekable"
333 ioe_invalidCharacter = ioException
334 (IOError Nothing InvalidArgument ""
335 ("invalid byte sequence for this encoding") Nothing Nothing)
337 ioe_finalizedHandle :: FilePath -> Handle__
338 ioe_finalizedHandle fp = throw
339 (IOError Nothing IllegalOperation ""
340 "handle is finalized" Nothing (Just fp))
342 ioe_bufsiz :: Int -> IO a
343 ioe_bufsiz n = ioException
344 (IOError Nothing InvalidArgument "hSetBuffering"
345 ("illegal buffer size " ++ showsPrec 9 n []) Nothing Nothing)
346 -- 9 => should be parens'ified.
348 -- -----------------------------------------------------------------------------
351 -- For a duplex handle, we arrange that the read side points to the write side
352 -- (and hence keeps it alive if the read side is alive). This is done by
353 -- having the haOtherSide field of the read side point to the read side.
354 -- The finalizer is then placed on the write side, and the handle only gets
355 -- finalized once, when both sides are no longer required.
357 -- NOTE about finalized handles: It's possible that a handle can be
358 -- finalized and then we try to use it later, for example if the
359 -- handle is referenced from another finalizer, or from a thread that
360 -- has become unreferenced and then resurrected (arguably in the
361 -- latter case we shouldn't finalize the Handle...). Anyway,
362 -- we try to emit a helpful message which is better than nothing.
364 -- [later; 8/2010] However, a program like this can yield a strange
367 -- main = writeFile "out" loop
368 -- loop = let x = x in x
370 -- because the main thread and the Handle are both unreachable at the
371 -- same time, the Handle may get finalized before the main thread
372 -- receives the NonTermination exception, and the exception handler
373 -- will then report an error. We'd rather this was not an error and
374 -- the program just prints "<<loop>>".
376 handleFinalizer :: FilePath -> MVar Handle__ -> IO ()
377 handleFinalizer fp m = do
378 handle_ <- takeMVar m
379 (handle_', _) <- hClose_help handle_
383 -- ---------------------------------------------------------------------------
384 -- Allocating buffers
386 -- using an 8k char buffer instead of 32k improved performance for a
387 -- basic "cat" program by ~30% for me. --SDM
388 dEFAULT_CHAR_BUFFER_SIZE :: Int
389 dEFAULT_CHAR_BUFFER_SIZE = dEFAULT_BUFFER_SIZE `div` 4
391 getCharBuffer :: IODevice dev => dev -> BufferState
392 -> IO (IORef CharBuffer, BufferMode)
393 getCharBuffer dev state = do
394 buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state
395 ioref <- newIORef buffer
396 is_tty <- IODevice.isTerminal dev
399 | is_tty = LineBuffering
400 | otherwise = BlockBuffering Nothing
402 return (ioref, buffer_mode)
404 mkUnBuffer :: BufferState -> IO (IORef CharBuffer, BufferMode)
405 mkUnBuffer state = do
406 buffer <- case state of -- See [note Buffer Sizing], GHC.IO.Handle.Types
407 ReadBuffer -> newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state
408 WriteBuffer -> newCharBuffer 1 state
409 ref <- newIORef buffer
410 return (ref, NoBuffering)
412 -- -----------------------------------------------------------------------------
415 -- | syncs the file with the buffer, including moving the
416 -- file pointer backwards in the case of a read buffer. This can fail
417 -- on a non-seekable read Handle.
418 flushBuffer :: Handle__ -> IO ()
419 flushBuffer h_@Handle__{..} = do
420 buf <- readIORef haCharBuffer
423 flushCharReadBuffer h_
424 flushByteReadBuffer h_
426 buf' <- flushWriteBuffer_ h_ buf
427 writeIORef haCharBuffer buf'
429 -- | flushes at least the Char buffer, and the byte buffer for a write
430 -- Handle. Works on all Handles.
431 flushCharBuffer :: Handle__ -> IO ()
432 flushCharBuffer h_@Handle__{..} = do
433 buf <- readIORef haCharBuffer
436 flushCharReadBuffer h_
438 buf' <- flushWriteBuffer_ h_ buf
439 writeIORef haCharBuffer buf'
441 -- -----------------------------------------------------------------------------
442 -- Writing data (flushing write buffers)
444 -- flushWriteBuffer flushes the buffer iff it contains pending write
445 -- data. Flushes both the Char and the byte buffer, leaving both
447 flushWriteBuffer :: Handle__ -> IO ()
448 flushWriteBuffer h_@Handle__{..} = do
449 buf <- readIORef haCharBuffer
451 then do buf' <- flushWriteBuffer_ h_ buf
452 writeIORef haCharBuffer buf'
455 flushWriteBuffer_ :: Handle__ -> CharBuffer -> IO CharBuffer
456 flushWriteBuffer_ h_@Handle__{..} cbuf = do
457 bbuf <- readIORef haByteBuffer
458 if not (isEmptyBuffer cbuf) || not (isEmptyBuffer bbuf)
459 then do writeTextDevice h_ cbuf
460 return cbuf{ bufL=0, bufR=0 }
463 -- -----------------------------------------------------------------------------
464 -- Flushing read buffers
466 -- It is always possible to flush the Char buffer back to the byte buffer.
467 flushCharReadBuffer :: Handle__ -> IO ()
468 flushCharReadBuffer Handle__{..} = do
469 cbuf <- readIORef haCharBuffer
470 if isWriteBuffer cbuf || isEmptyBuffer cbuf then return () else do
472 -- haLastDecode is the byte buffer just before we did our last batch of
473 -- decoding. We're going to re-decode the bytes up to the current char,
474 -- to find out where we should revert the byte buffer to.
475 (codec_state, bbuf0) <- readIORef haLastDecode
477 cbuf0 <- readIORef haCharBuffer
478 writeIORef haCharBuffer cbuf0{ bufL=0, bufR=0 }
480 -- if we haven't used any characters from the char buffer, then just
481 -- re-install the old byte buffer.
483 then do writeIORef haByteBuffer bbuf0
489 writeIORef haByteBuffer bbuf0 { bufL = bufL bbuf0 + bufL cbuf0 }
490 -- no decoder: the number of bytes to decode is the same as the
491 -- number of chars we have used up.
494 debugIO ("flushCharReadBuffer re-decode, bbuf=" ++ summaryBuffer bbuf0 ++
495 " cbuf=" ++ summaryBuffer cbuf0)
497 -- restore the codec state
498 setState decoder codec_state
500 (bbuf1,cbuf1) <- (encode decoder) bbuf0
501 cbuf0{ bufL=0, bufR=0, bufSize = bufL cbuf0 }
503 debugIO ("finished, bbuf=" ++ summaryBuffer bbuf1 ++
504 " cbuf=" ++ summaryBuffer cbuf1)
506 writeIORef haByteBuffer bbuf1
509 -- When flushing the byte read buffer, we seek backwards by the number
510 -- of characters in the buffer. The file descriptor must therefore be
511 -- seekable: attempting to flush the read buffer on an unseekable
512 -- handle is not allowed.
514 flushByteReadBuffer :: Handle__ -> IO ()
515 flushByteReadBuffer h_@Handle__{..} = do
516 bbuf <- readIORef haByteBuffer
518 if isEmptyBuffer bbuf then return () else do
520 seekable <- IODevice.isSeekable haDevice
521 when (not seekable) $ ioe_cannotFlushNotSeekable
523 let seek = negate (bufR bbuf - bufL bbuf)
525 debugIO ("flushByteReadBuffer: new file offset = " ++ show seek)
526 IODevice.seek haDevice RelativeSeek (fromIntegral seek)
528 writeIORef haByteBuffer bbuf{ bufL=0, bufR=0 }
530 -- ----------------------------------------------------------------------------
533 mkHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev
537 -> Maybe TextEncoding
539 -> Maybe HandleFinalizer
540 -> Maybe (MVar Handle__)
543 mkHandle dev filepath ha_type buffered mb_codec nl finalizer other_side = do
544 openTextEncoding mb_codec ha_type $ \ mb_encoder mb_decoder -> do
546 let buf_state = initBufferState ha_type
547 bbuf <- Buffered.newBuffer dev buf_state
548 bbufref <- newIORef bbuf
549 last_decode <- newIORef (error "codec_state", bbuf)
552 if buffered then getCharBuffer dev buf_state
553 else mkUnBuffer buf_state
555 spares <- newIORef BufferListNil
556 newFileHandle filepath finalizer
557 (Handle__ { haDevice = dev,
559 haBufferMode = bmode,
560 haByteBuffer = bbufref,
561 haLastDecode = last_decode,
562 haCharBuffer = cbufref,
564 haEncoder = mb_encoder,
565 haDecoder = mb_decoder,
567 haInputNL = inputNL nl,
568 haOutputNL = outputNL nl,
569 haOtherSide = other_side
572 -- | makes a new 'Handle'
573 mkFileHandle :: (IODevice dev, BufferedIO dev, Typeable dev)
574 => dev -- ^ the underlying IO device, which must support
575 -- 'IODevice', 'BufferedIO' and 'Typeable'
577 -- ^ a string describing the 'Handle', e.g. the file
578 -- path for a file. Used in error messages.
580 -- The mode in which the 'Handle' is to be used
581 -> Maybe TextEncoding
582 -- Create the 'Handle' with no text encoding?
584 -- Translate newlines?
586 mkFileHandle dev filepath iomode mb_codec tr_newlines = do
587 mkHandle dev filepath (ioModeToHandleType iomode) True{-buffered-} mb_codec
589 (Just handleFinalizer) Nothing{-other_side-}
591 -- | like 'mkFileHandle', except that a 'Handle' is created with two
592 -- independent buffers, one for reading and one for writing. Used for
593 -- full-duplex streams, such as network sockets.
594 mkDuplexHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev
595 -> FilePath -> Maybe TextEncoding -> NewlineMode -> IO Handle
596 mkDuplexHandle dev filepath mb_codec tr_newlines = do
598 write_side@(FileHandle _ write_m) <-
599 mkHandle dev filepath WriteHandle True mb_codec
601 (Just handleFinalizer)
602 Nothing -- no othersie
604 read_side@(FileHandle _ read_m) <-
605 mkHandle dev filepath ReadHandle True mb_codec
607 Nothing -- no finalizer
610 return (DuplexHandle filepath read_m write_m)
612 ioModeToHandleType :: IOMode -> HandleType
613 ioModeToHandleType ReadMode = ReadHandle
614 ioModeToHandleType WriteMode = WriteHandle
615 ioModeToHandleType ReadWriteMode = ReadWriteHandle
616 ioModeToHandleType AppendMode = AppendHandle
618 initBufferState :: HandleType -> BufferState
619 initBufferState ReadHandle = ReadBuffer
620 initBufferState _ = WriteBuffer
623 :: Maybe TextEncoding
625 -> (forall es ds . Maybe (TextEncoder es) -> Maybe (TextDecoder ds) -> IO a)
628 openTextEncoding Nothing ha_type cont = cont Nothing Nothing
629 openTextEncoding (Just TextEncoding{..}) ha_type cont = do
630 mb_decoder <- if isReadableHandleType ha_type then do
631 decoder <- mkTextDecoder
632 return (Just decoder)
635 mb_encoder <- if isWritableHandleType ha_type then do
636 encoder <- mkTextEncoder
637 return (Just encoder)
640 cont mb_encoder mb_decoder
642 closeTextCodecs :: Handle__ -> IO ()
643 closeTextCodecs Handle__{..} = do
644 case haDecoder of Nothing -> return (); Just d -> Encoding.close d
645 case haEncoder of Nothing -> return (); Just d -> Encoding.close d
647 -- ---------------------------------------------------------------------------
650 -- hClose_help is also called by lazyRead (in GHC.IO.Handle.Text) when
651 -- EOF is read or an IO error occurs on a lazy stream. The
652 -- semi-closed Handle is then closed immediately. We have to be
653 -- careful with DuplexHandles though: we have to leave the closing to
654 -- the finalizer in that case, because the write side may still be in
656 hClose_help :: Handle__ -> IO (Handle__, Maybe SomeException)
657 hClose_help handle_ =
658 case haType handle_ of
659 ClosedHandle -> return (handle_,Nothing)
660 _ -> do mb_exc1 <- trymaybe $ flushWriteBuffer handle_ -- interruptible
661 -- it is important that hClose doesn't fail and
662 -- leave the Handle open (#3128), so we catch
663 -- exceptions when flushing the buffer.
664 (h_, mb_exc2) <- hClose_handle_ handle_
665 return (h_, if isJust mb_exc1 then mb_exc1 else mb_exc2)
668 trymaybe :: IO () -> IO (Maybe SomeException)
669 trymaybe io = (do io; return Nothing) `catchException` \e -> return (Just e)
671 hClose_handle_ :: Handle__ -> IO (Handle__, Maybe SomeException)
672 hClose_handle_ h_@Handle__{..} = do
674 -- close the file descriptor, but not when this is the read
675 -- side of a duplex handle.
676 -- If an exception is raised by the close(), we want to continue
677 -- to close the handle and release the lock if it has one, then
678 -- we return the exception to the caller of hClose_help which can
679 -- raise it if necessary.
682 Nothing -> trymaybe $ IODevice.close haDevice
683 Just _ -> return Nothing
685 -- free the spare buffers
686 writeIORef haBuffers BufferListNil
687 writeIORef haCharBuffer noCharBuffer
688 writeIORef haByteBuffer noByteBuffer
690 -- release our encoder/decoder
693 -- we must set the fd to -1, because the finalizer is going
694 -- to run eventually and try to close/unlock it.
695 -- ToDo: necessary? the handle will be marked ClosedHandle
696 -- XXX GHC won't let us use record update here, hence wildcards
697 return (Handle__{ haType = ClosedHandle, .. }, maybe_exception)
699 {-# NOINLINE noCharBuffer #-}
700 noCharBuffer :: CharBuffer
701 noCharBuffer = unsafePerformIO $ newCharBuffer 1 ReadBuffer
703 {-# NOINLINE noByteBuffer #-}
704 noByteBuffer :: Buffer Word8
705 noByteBuffer = unsafePerformIO $ newByteBuffer 1 ReadBuffer
707 -- ---------------------------------------------------------------------------
710 hLookAhead_ :: Handle__ -> IO Char
711 hLookAhead_ handle_@Handle__{..} = do
712 buf <- readIORef haCharBuffer
714 -- fill up the read buffer if necessary
715 new_buf <- if isEmptyBuffer buf
716 then readTextDevice handle_ buf
718 writeIORef haCharBuffer new_buf
720 peekCharBuf (bufRaw buf) (bufL buf)
722 -- ---------------------------------------------------------------------------
725 debugIO :: String -> IO ()
728 = do _ <- withCStringLen (s ++ "\n") $
729 \(p, len) -> c_write 1 (castPtr p) (fromIntegral len)
731 | otherwise = return ()
733 -- ----------------------------------------------------------------------------
736 -- Write the contents of the supplied Char buffer to the device, return
737 -- only when all the data has been written.
738 writeTextDevice :: Handle__ -> CharBuffer -> IO ()
739 writeTextDevice h_@Handle__{..} cbuf = do
741 bbuf <- readIORef haByteBuffer
743 debugIO ("writeTextDevice: cbuf=" ++ summaryBuffer cbuf ++
744 " bbuf=" ++ summaryBuffer bbuf)
746 (cbuf',bbuf') <- case haEncoder of
747 Nothing -> latin1_encode cbuf bbuf
748 Just encoder -> (encode encoder) cbuf bbuf
750 debugIO ("writeTextDevice after encoding: cbuf=" ++ summaryBuffer cbuf' ++
751 " bbuf=" ++ summaryBuffer bbuf')
753 bbuf' <- Buffered.flushWriteBuffer haDevice bbuf'
754 writeIORef haByteBuffer bbuf'
755 if not (isEmptyBuffer cbuf')
756 then writeTextDevice h_ cbuf'
759 -- Read characters into the provided buffer. Return when any
760 -- characters are available; raise an exception if the end of
762 readTextDevice :: Handle__ -> CharBuffer -> IO CharBuffer
763 readTextDevice h_@Handle__{..} cbuf = do
765 bbuf0 <- readIORef haByteBuffer
767 debugIO ("readTextDevice: cbuf=" ++ summaryBuffer cbuf ++
768 " bbuf=" ++ summaryBuffer bbuf0)
770 bbuf1 <- if not (isEmptyBuffer bbuf0)
773 (r,bbuf1) <- Buffered.fillReadBuffer haDevice bbuf0
774 if r == 0 then ioe_EOF else do -- raise EOF
777 debugIO ("readTextDevice after reading: bbuf=" ++ summaryBuffer bbuf1)
782 writeIORef haLastDecode (error "codec_state", bbuf1)
783 latin1_decode bbuf1 cbuf
785 state <- getState decoder
786 writeIORef haLastDecode (state, bbuf1)
787 (encode decoder) bbuf1 cbuf
789 debugIO ("readTextDevice after decoding: cbuf=" ++ summaryBuffer cbuf' ++
790 " bbuf=" ++ summaryBuffer bbuf2)
792 writeIORef haByteBuffer bbuf2
793 if bufR cbuf' == bufR cbuf -- no new characters
794 then readTextDevice' h_ bbuf2 cbuf -- we need more bytes to make a Char
797 -- we have an incomplete byte sequence at the end of the buffer: try to
799 readTextDevice' :: Handle__ -> Buffer Word8 -> CharBuffer -> IO CharBuffer
800 readTextDevice' h_@Handle__{..} bbuf0 cbuf = do
802 -- copy the partial sequence to the beginning of the buffer, so we have
803 -- room to read more bytes.
804 bbuf1 <- slideContents bbuf0
806 bbuf2 <- do (r,bbuf2) <- Buffered.fillReadBuffer haDevice bbuf1
808 then ioe_invalidCharacter
811 debugIO ("readTextDevice after reading: bbuf=" ++ summaryBuffer bbuf2)
816 writeIORef haLastDecode (error "codec_state", bbuf2)
817 latin1_decode bbuf2 cbuf
819 state <- getState decoder
820 writeIORef haLastDecode (state, bbuf2)
821 (encode decoder) bbuf2 cbuf
823 debugIO ("readTextDevice after decoding: cbuf=" ++ summaryBuffer cbuf' ++
824 " bbuf=" ++ summaryBuffer bbuf3)
826 writeIORef haByteBuffer bbuf3
827 if bufR cbuf == bufR cbuf'
828 then readTextDevice' h_ bbuf3 cbuf'
831 -- Read characters into the provided buffer. Do not block;
832 -- return zero characters instead. Raises an exception on end-of-file.
833 readTextDeviceNonBlocking :: Handle__ -> CharBuffer -> IO CharBuffer
834 readTextDeviceNonBlocking h_@Handle__{..} cbuf = do
836 bbuf0 <- readIORef haByteBuffer
837 when (isEmptyBuffer bbuf0) $ do
838 (r,bbuf1) <- Buffered.fillReadBuffer0 haDevice bbuf0
839 if isNothing r then ioe_EOF else do -- raise EOF
840 writeIORef haByteBuffer bbuf1
842 decodeByteBuf h_ cbuf
844 -- Decode bytes from the byte buffer into the supplied CharBuffer.
845 decodeByteBuf :: Handle__ -> CharBuffer -> IO CharBuffer
846 decodeByteBuf h_@Handle__{..} cbuf = do
848 bbuf0 <- readIORef haByteBuffer
853 writeIORef haLastDecode (error "codec_state", bbuf0)
854 latin1_decode bbuf0 cbuf
856 state <- getState decoder
857 writeIORef haLastDecode (state, bbuf0)
858 (encode decoder) bbuf0 cbuf
860 writeIORef haByteBuffer bbuf2