1 {-# OPTIONS_GHC -fno-implicit-prelude -#include "HsBase.h" #-}
2 {-# OPTIONS_HADDOCK hide #-}
7 -----------------------------------------------------------------------------
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\".
19 -----------------------------------------------------------------------------
23 withHandle, withHandle', withHandle_,
24 wantWritableHandle, wantReadableHandle, wantSeekableHandle,
26 newEmptyBuffer, allocateBuffer, readCharFromBuffer, writeCharIntoBuffer,
27 flushWriteBufferOnly, flushWriteBuffer, flushReadBuffer,
28 fillReadBuffer, fillReadBufferWithoutBlocking,
29 readRawBuffer, readRawBufferPtr,
30 writeRawBuffer, writeRawBufferPtr,
32 #ifndef mingw32_HOST_OS
36 ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable,
38 stdin, stdout, stderr,
39 IOMode(..), openFile, openBinaryFile, fdToHandle_stat, fdToHandle, fdToHandle',
40 hFileSize, hSetFileSize, hIsEOF, isEOF, hLookAhead, hSetBuffering, hSetBinaryMode,
41 hFlush, hDuplicate, hDuplicateTo,
45 HandlePosition, HandlePosn(..), hGetPosn, hSetPosn,
46 SeekMode(..), hSeek, hTell,
48 hIsOpen, hIsClosed, hIsReadable, hIsWritable, hGetBuffering, hIsSeekable,
49 hSetEcho, hGetEcho, hIsTerminalDevice,
64 import System.IO.Error
65 import System.Posix.Internals
66 import System.Posix.Types
72 import GHC.Read ( Read )
77 import GHC.Num ( Integer(..), Num(..) )
79 import GHC.Real ( toInteger )
80 #if defined(DEBUG_DUMP)
86 -- -----------------------------------------------------------------------------
89 -- hWaitForInput blocks (should use a timeout)
91 -- unbuffered hGetLine is a bit dodgy
93 -- hSetBuffering: can't change buffering on a stream,
94 -- when the read buffer is non-empty? (no way to flush the buffer)
96 -- ---------------------------------------------------------------------------
97 -- Are files opened by default in text or binary mode, if the user doesn't
100 dEFAULT_OPEN_IN_BINARY_MODE = False :: Bool
102 -- ---------------------------------------------------------------------------
103 -- Creating a new handle
105 newFileHandle :: FilePath -> (MVar Handle__ -> IO ()) -> Handle__ -> IO Handle
106 newFileHandle filepath finalizer hc = do
108 addMVarFinalizer m (finalizer m)
109 return (FileHandle filepath m)
111 -- ---------------------------------------------------------------------------
112 -- Working with Handles
115 In the concurrent world, handles are locked during use. This is done
116 by wrapping an MVar around the handle which acts as a mutex over
117 operations on the handle.
119 To avoid races, we use the following bracketing operations. The idea
120 is to obtain the lock, do some operation and replace the lock again,
121 whether the operation succeeded or failed. We also want to handle the
122 case where the thread receives an exception while processing the IO
123 operation: in these cases we also want to relinquish the lock.
125 There are three versions of @withHandle@: corresponding to the three
126 possible combinations of:
128 - the operation may side-effect the handle
129 - the operation may return a result
131 If the operation generates an error or an exception is raised, the
132 original handle is always replaced [ this is the case at the moment,
133 but we might want to revisit this in the future --SDM ].
136 {-# INLINE withHandle #-}
137 withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
138 withHandle fun h@(FileHandle _ m) act = withHandle' fun h m act
139 withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act
141 withHandle' :: String -> Handle -> MVar Handle__
142 -> (Handle__ -> IO (Handle__,a)) -> IO a
143 withHandle' fun h m act =
146 checkBufferInvariants h_
147 (h',v) <- catchException (act h_)
148 (\ err -> putMVar m h_ >>
150 IOException ex -> ioError (augmentIOError ex fun h)
152 checkBufferInvariants h'
156 {-# INLINE withHandle_ #-}
157 withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
158 withHandle_ fun h@(FileHandle _ m) act = withHandle_' fun h m act
159 withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act
161 withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a
162 withHandle_' fun h m act =
165 checkBufferInvariants h_
166 v <- catchException (act h_)
167 (\ err -> putMVar m h_ >>
169 IOException ex -> ioError (augmentIOError ex fun h)
171 checkBufferInvariants h_
175 withAllHandles__ :: String -> Handle -> (Handle__ -> IO Handle__) -> IO ()
176 withAllHandles__ fun h@(FileHandle _ m) act = withHandle__' fun h m act
177 withAllHandles__ fun h@(DuplexHandle _ r w) act = do
178 withHandle__' fun h r act
179 withHandle__' fun h w act
181 withHandle__' fun h m act =
184 checkBufferInvariants h_
185 h' <- catchException (act h_)
186 (\ err -> putMVar m h_ >>
188 IOException ex -> ioError (augmentIOError ex fun h)
190 checkBufferInvariants h'
194 augmentIOError (IOError _ iot _ str fp) fun h
195 = IOError (Just h) iot fun str filepath
198 | otherwise = case h of
199 FileHandle fp _ -> Just fp
200 DuplexHandle fp _ _ -> Just fp
202 -- ---------------------------------------------------------------------------
203 -- Wrapper for write operations.
205 wantWritableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
206 wantWritableHandle fun h@(FileHandle _ m) act
207 = wantWritableHandle' fun h m act
208 wantWritableHandle fun h@(DuplexHandle _ _ m) act
209 = wantWritableHandle' fun h m act
210 -- ToDo: in the Duplex case, we don't need to checkWritableHandle
213 :: String -> Handle -> MVar Handle__
214 -> (Handle__ -> IO a) -> IO a
215 wantWritableHandle' fun h m act
216 = withHandle_' fun h m (checkWritableHandle act)
218 checkWritableHandle act handle_
219 = case haType handle_ of
220 ClosedHandle -> ioe_closedHandle
221 SemiClosedHandle -> ioe_closedHandle
222 ReadHandle -> ioe_notWritable
223 ReadWriteHandle -> do
224 let ref = haBuffer handle_
227 if not (bufferIsWritable buf)
228 then do b <- flushReadBuffer (haFD handle_) buf
229 return b{ bufState=WriteBuffer }
231 writeIORef ref new_buf
233 _other -> act handle_
235 -- ---------------------------------------------------------------------------
236 -- Wrapper for read operations.
238 wantReadableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
239 wantReadableHandle fun h@(FileHandle _ m) act
240 = wantReadableHandle' fun h m act
241 wantReadableHandle fun h@(DuplexHandle _ m _) act
242 = wantReadableHandle' fun h m act
243 -- ToDo: in the Duplex case, we don't need to checkReadableHandle
246 :: String -> Handle -> MVar Handle__
247 -> (Handle__ -> IO a) -> IO a
248 wantReadableHandle' fun h m act
249 = withHandle_' fun h m (checkReadableHandle act)
251 checkReadableHandle act handle_ =
252 case haType handle_ of
253 ClosedHandle -> ioe_closedHandle
254 SemiClosedHandle -> ioe_closedHandle
255 AppendHandle -> ioe_notReadable
256 WriteHandle -> ioe_notReadable
257 ReadWriteHandle -> do
258 let ref = haBuffer handle_
260 when (bufferIsWritable buf) $ do
261 new_buf <- flushWriteBuffer (haFD handle_) (haIsStream handle_) buf
262 writeIORef ref new_buf{ bufState=ReadBuffer }
264 _other -> act handle_
266 -- ---------------------------------------------------------------------------
267 -- Wrapper for seek operations.
269 wantSeekableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
270 wantSeekableHandle fun h@(DuplexHandle _ _ _) _act =
271 ioException (IOError (Just h) IllegalOperation fun
272 "handle is not seekable" Nothing)
273 wantSeekableHandle fun h@(FileHandle _ m) act =
274 withHandle_' fun h m (checkSeekableHandle act)
276 checkSeekableHandle act handle_ =
277 case haType handle_ of
278 ClosedHandle -> ioe_closedHandle
279 SemiClosedHandle -> ioe_closedHandle
280 AppendHandle -> ioe_notSeekable
281 _ | haIsBin handle_ || tEXT_MODE_SEEK_ALLOWED -> act handle_
282 | otherwise -> ioe_notSeekable_notBin
284 -- -----------------------------------------------------------------------------
287 ioe_closedHandle, ioe_EOF,
288 ioe_notReadable, ioe_notWritable,
289 ioe_notSeekable, ioe_notSeekable_notBin :: IO a
291 ioe_closedHandle = ioException
292 (IOError Nothing IllegalOperation ""
293 "handle is closed" Nothing)
294 ioe_EOF = ioException
295 (IOError Nothing EOF "" "" Nothing)
296 ioe_notReadable = ioException
297 (IOError Nothing IllegalOperation ""
298 "handle is not open for reading" Nothing)
299 ioe_notWritable = ioException
300 (IOError Nothing IllegalOperation ""
301 "handle is not open for writing" Nothing)
302 ioe_notSeekable = ioException
303 (IOError Nothing IllegalOperation ""
304 "handle is not seekable" Nothing)
305 ioe_notSeekable_notBin = ioException
306 (IOError Nothing IllegalOperation ""
307 "seek operations on text-mode handles are not allowed on this platform"
310 ioe_finalizedHandle fp = throw (IOException
311 (IOError Nothing IllegalOperation ""
312 "handle is finalized" (Just fp)))
314 ioe_bufsiz :: Int -> IO a
315 ioe_bufsiz n = ioException
316 (IOError Nothing InvalidArgument "hSetBuffering"
317 ("illegal buffer size " ++ showsPrec 9 n []) Nothing)
318 -- 9 => should be parens'ified.
320 -- -----------------------------------------------------------------------------
323 -- For a duplex handle, we arrange that the read side points to the write side
324 -- (and hence keeps it alive if the read side is alive). This is done by
325 -- having the haOtherSide field of the read side point to the read side.
326 -- The finalizer is then placed on the write side, and the handle only gets
327 -- finalized once, when both sides are no longer required.
329 -- NOTE about finalized handles: It's possible that a handle can be
330 -- finalized and then we try to use it later, for example if the
331 -- handle is referenced from another finalizer, or from a thread that
332 -- has become unreferenced and then resurrected (arguably in the
333 -- latter case we shouldn't finalize the Handle...). Anyway,
334 -- we try to emit a helpful message which is better than nothing.
336 stdHandleFinalizer :: FilePath -> MVar Handle__ -> IO ()
337 stdHandleFinalizer fp m = do
339 flushWriteBufferOnly h_
340 putMVar m (ioe_finalizedHandle fp)
342 handleFinalizer :: FilePath -> MVar Handle__ -> IO ()
343 handleFinalizer fp m = do
344 handle_ <- takeMVar m
345 case haType handle_ of
346 ClosedHandle -> return ()
347 _ -> do flushWriteBufferOnly handle_ `catchException` \_ -> return ()
348 -- ignore errors and async exceptions, and close the
349 -- descriptor anyway...
350 hClose_handle_ handle_
352 putMVar m (ioe_finalizedHandle fp)
354 -- ---------------------------------------------------------------------------
355 -- Grimy buffer operations
358 checkBufferInvariants h_ = do
359 let ref = haBuffer h_
360 Buffer{ bufWPtr=w, bufRPtr=r, bufSize=size, bufState=state } <- readIORef ref
365 && ( r /= w || (r == 0 && w == 0) )
366 && ( state /= WriteBuffer || r == 0 )
367 && ( state /= WriteBuffer || w < size ) -- write buffer is never full
369 then error "buffer invariant violation"
372 checkBufferInvariants h_ = return ()
375 newEmptyBuffer :: RawBuffer -> BufferState -> Int -> Buffer
376 newEmptyBuffer b state size
377 = Buffer{ bufBuf=b, bufRPtr=0, bufWPtr=0, bufSize=size, bufState=state }
379 allocateBuffer :: Int -> BufferState -> IO Buffer
380 allocateBuffer sz@(I# size) state = IO $ \s ->
381 -- We sometimes need to pass the address of this buffer to
382 -- a "safe" foreign call, hence it must be immovable.
383 case newPinnedByteArray# size s of { (# s, b #) ->
384 (# s, newEmptyBuffer b state sz #) }
386 writeCharIntoBuffer :: RawBuffer -> Int -> Char -> IO Int
387 writeCharIntoBuffer slab (I# off) (C# c)
388 = IO $ \s -> case writeCharArray# slab off c s of
389 s -> (# s, I# (off +# 1#) #)
391 readCharFromBuffer :: RawBuffer -> Int -> IO (Char, Int)
392 readCharFromBuffer slab (I# off)
393 = IO $ \s -> case readCharArray# slab off s of
394 (# s, c #) -> (# s, (C# c, I# (off +# 1#)) #)
396 getBuffer :: FD -> BufferState -> IO (IORef Buffer, BufferMode)
397 getBuffer fd state = do
398 buffer <- allocateBuffer dEFAULT_BUFFER_SIZE state
399 ioref <- newIORef buffer
403 | is_tty = LineBuffering
404 | otherwise = BlockBuffering Nothing
406 return (ioref, buffer_mode)
408 mkUnBuffer :: IO (IORef Buffer)
410 buffer <- allocateBuffer 1 ReadBuffer
413 -- flushWriteBufferOnly flushes the buffer iff it contains pending write data.
414 flushWriteBufferOnly :: Handle__ -> IO ()
415 flushWriteBufferOnly h_ = do
419 new_buf <- if bufferIsWritable buf
420 then flushWriteBuffer fd (haIsStream h_) buf
422 writeIORef ref new_buf
424 -- flushBuffer syncs the file with the buffer, including moving the
425 -- file pointer backwards in the case of a read buffer.
426 flushBuffer :: Handle__ -> IO ()
428 let ref = haBuffer h_
433 ReadBuffer -> flushReadBuffer (haFD h_) buf
434 WriteBuffer -> flushWriteBuffer (haFD h_) (haIsStream h_) buf
436 writeIORef ref flushed_buf
438 -- When flushing a read buffer, we seek backwards by the number of
439 -- characters in the buffer. The file descriptor must therefore be
440 -- seekable: attempting to flush the read buffer on an unseekable
441 -- handle is not allowed.
443 flushReadBuffer :: FD -> Buffer -> IO Buffer
444 flushReadBuffer fd buf
445 | bufferEmpty buf = return buf
447 let off = negate (bufWPtr buf - bufRPtr buf)
449 puts ("flushReadBuffer: new file offset = " ++ show off ++ "\n")
451 throwErrnoIfMinus1Retry "flushReadBuffer"
452 (c_lseek fd (fromIntegral off) sEEK_CUR)
453 return buf{ bufWPtr=0, bufRPtr=0 }
455 flushWriteBuffer :: FD -> Bool -> Buffer -> IO Buffer
456 flushWriteBuffer fd is_stream buf@Buffer{ bufBuf=b, bufRPtr=r, bufWPtr=w } =
457 seq fd $ do -- strictness hack
460 puts ("flushWriteBuffer, fd=" ++ show fd ++ ", bytes=" ++ show bytes ++ "\n")
463 then return (buf{ bufRPtr=0, bufWPtr=0 })
465 res <- writeRawBuffer "flushWriteBuffer" fd is_stream b
466 (fromIntegral r) (fromIntegral bytes)
467 let res' = fromIntegral res
469 then flushWriteBuffer fd is_stream (buf{ bufRPtr = r + res' })
470 else return buf{ bufRPtr=0, bufWPtr=0 }
472 fillReadBuffer :: FD -> Bool -> Bool -> Buffer -> IO Buffer
473 fillReadBuffer fd is_line is_stream
474 buf@Buffer{ bufBuf=b, bufRPtr=r, bufWPtr=w, bufSize=size } =
475 -- buffer better be empty:
476 assert (r == 0 && w == 0) $ do
477 fillReadBufferLoop fd is_line is_stream buf b w size
479 -- For a line buffer, we just get the first chunk of data to arrive,
480 -- and don't wait for the whole buffer to be full (but we *do* wait
481 -- until some data arrives). This isn't really line buffering, but it
482 -- appears to be what GHC has done for a long time, and I suspect it
483 -- is more useful than line buffering in most cases.
485 fillReadBufferLoop fd is_line is_stream buf b w size = do
487 if bytes == 0 -- buffer full?
488 then return buf{ bufRPtr=0, bufWPtr=w }
491 puts ("fillReadBufferLoop: bytes = " ++ show bytes ++ "\n")
493 res <- readRawBuffer "fillReadBuffer" fd is_stream b
494 (fromIntegral w) (fromIntegral bytes)
495 let res' = fromIntegral res
497 puts ("fillReadBufferLoop: res' = " ++ show res' ++ "\n")
502 else return buf{ bufRPtr=0, bufWPtr=w }
503 else if res' < bytes && not is_line
504 then fillReadBufferLoop fd is_line is_stream buf b (w+res') size
505 else return buf{ bufRPtr=0, bufWPtr=w+res' }
508 fillReadBufferWithoutBlocking :: FD -> Bool -> Buffer -> IO Buffer
509 fillReadBufferWithoutBlocking fd is_stream
510 buf@Buffer{ bufBuf=b, bufRPtr=r, bufWPtr=w, bufSize=size } =
511 -- buffer better be empty:
512 assert (r == 0 && w == 0) $ do
514 puts ("fillReadBufferLoopNoBlock: bytes = " ++ show size ++ "\n")
516 res <- readRawBufferNoBlock "fillReadBuffer" fd is_stream b
517 0 (fromIntegral size)
518 let res' = fromIntegral res
520 puts ("fillReadBufferLoopNoBlock: res' = " ++ show res' ++ "\n")
522 return buf{ bufRPtr=0, bufWPtr=res' }
524 -- Low level routines for reading/writing to (raw)buffers:
526 #ifndef mingw32_HOST_OS
531 Unix has broken semantics when it comes to non-blocking I/O: you can
532 set the O_NONBLOCK flag on an FD, but it applies to the all other FDs
533 attached to the same underlying file, pipe or TTY; there's no way to
534 have private non-blocking behaviour for an FD. See bug #724.
536 We fix this by only setting O_NONBLOCK on FDs that we create; FDs that
537 come from external sources or are exposed externally are left in
538 blocking mode. This solution has some problems though. We can't
539 completely simulate a non-blocking read without O_NONBLOCK: several
540 cases are wrong here. The cases that are wrong:
542 * reading/writing to a blocking FD in non-threaded mode.
543 In threaded mode, we just make a safe call to read().
544 In non-threaded mode we call select() before attempting to read,
545 but that leaves a small race window where the data can be read
546 from the file descriptor before we issue our blocking read().
547 * readRawBufferNoBlock for a blocking FD
550 readRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
551 readRawBuffer loc fd is_nonblock buf off len
552 | is_nonblock = unsafe_read
553 | threaded = safe_read
554 | otherwise = do r <- throwErrnoIfMinus1 loc
555 (fdReady (fromIntegral fd) 0 0 False)
558 else do threadWaitRead (fromIntegral fd); unsafe_read
560 do_read call = throwErrnoIfMinus1RetryMayBlock loc call
561 (threadWaitRead (fromIntegral fd))
562 unsafe_read = do_read (read_rawBuffer fd buf off len)
563 safe_read = do_read (safe_read_rawBuffer fd buf off len)
565 readRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
566 readRawBufferPtr loc fd is_nonblock buf off len
567 | is_nonblock = unsafe_read
568 | threaded = safe_read
569 | otherwise = do r <- throwErrnoIfMinus1 loc
570 (fdReady (fromIntegral fd) 0 0 False)
573 else do threadWaitRead (fromIntegral fd); unsafe_read
575 do_read call = throwErrnoIfMinus1RetryMayBlock loc call
576 (threadWaitRead (fromIntegral fd))
577 unsafe_read = do_read (read_off fd buf off len)
578 safe_read = do_read (safe_read_off fd buf off len)
580 readRawBufferNoBlock :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
581 readRawBufferNoBlock loc fd is_nonblock buf off len
582 | is_nonblock = unsafe_read
583 | otherwise = do r <- fdReady (fromIntegral fd) 0 0 False
584 if r /= 0 then safe_read
586 -- XXX see note [nonblock]
588 do_read call = throwErrnoIfMinus1RetryOnBlock loc call (return 0)
589 unsafe_read = do_read (read_rawBuffer fd buf off len)
590 safe_read = do_read (safe_read_rawBuffer fd buf off len)
592 writeRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
593 writeRawBuffer loc fd is_nonblock buf off len
594 | is_nonblock = unsafe_write
595 | threaded = safe_write
596 | otherwise = do r <- fdReady (fromIntegral fd) 1 0 False
599 else do threadWaitWrite (fromIntegral fd); unsafe_write
601 do_write call = throwErrnoIfMinus1RetryMayBlock loc call
602 (threadWaitWrite (fromIntegral fd))
603 unsafe_write = do_write (write_rawBuffer fd buf off len)
604 safe_write = do_write (safe_write_rawBuffer (fromIntegral fd) buf off len)
606 writeRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
607 writeRawBufferPtr loc fd is_nonblock buf off len
608 | is_nonblock = unsafe_write
609 | threaded = safe_write
610 | otherwise = do r <- fdReady (fromIntegral fd) 1 0 False
613 else do threadWaitWrite (fromIntegral fd); unsafe_write
615 do_write call = throwErrnoIfMinus1RetryMayBlock loc call
616 (threadWaitWrite (fromIntegral fd))
617 unsafe_write = do_write (write_off fd buf off len)
618 safe_write = do_write (safe_write_off (fromIntegral fd) buf off len)
620 foreign import ccall unsafe "__hscore_PrelHandle_read"
621 read_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
623 foreign import ccall unsafe "__hscore_PrelHandle_read"
624 read_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
626 foreign import ccall unsafe "__hscore_PrelHandle_write"
627 write_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
629 foreign import ccall unsafe "__hscore_PrelHandle_write"
630 write_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
632 foreign import ccall safe "fdReady"
633 fdReady :: CInt -> CInt -> CInt -> Bool -> IO CInt
635 #else /* mingw32_HOST_OS.... */
637 readRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
638 readRawBuffer loc fd is_stream buf off len
639 | threaded = blockingReadRawBuffer loc fd is_stream buf off len
640 | otherwise = asyncReadRawBuffer loc fd is_stream buf off len
642 readRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
643 readRawBufferPtr loc fd is_stream buf off len
644 | threaded = blockingReadRawBufferPtr loc fd is_stream buf off len
645 | otherwise = asyncReadRawBufferPtr loc fd is_stream buf off len
647 writeRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
648 writeRawBuffer loc fd is_stream buf off len
649 | threaded = blockingWriteRawBuffer loc fd is_stream buf off len
650 | otherwise = asyncWriteRawBuffer loc fd is_stream buf off len
652 writeRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
653 writeRawBufferPtr loc fd is_stream buf off len
654 | threaded = blockingWriteRawBufferPtr loc fd is_stream buf off len
655 | otherwise = asyncWriteRawBufferPtr loc fd is_stream buf off len
657 -- ToDo: we don't have a non-blocking primitve read on Win32
658 readRawBufferNoBlock :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
659 readRawBufferNoBlock = readRawBuffer
661 -- Async versions of the read/write primitives, for the non-threaded RTS
663 asyncReadRawBuffer loc fd is_stream buf off len = do
664 (l, rc) <- asyncReadBA (fromIntegral fd) (if is_stream then 1 else 0)
665 (fromIntegral len) off buf
668 ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
669 else return (fromIntegral l)
671 asyncReadRawBufferPtr loc fd is_stream buf off len = do
672 (l, rc) <- asyncRead (fromIntegral fd) (if is_stream then 1 else 0)
673 (fromIntegral len) (buf `plusPtr` off)
676 ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
677 else return (fromIntegral l)
679 asyncWriteRawBuffer loc fd is_stream buf off len = do
680 (l, rc) <- asyncWriteBA (fromIntegral fd) (if is_stream then 1 else 0)
681 (fromIntegral len) off buf
684 ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
685 else return (fromIntegral l)
687 asyncWriteRawBufferPtr loc fd is_stream buf off len = do
688 (l, rc) <- asyncWrite (fromIntegral fd) (if is_stream then 1 else 0)
689 (fromIntegral len) (buf `plusPtr` off)
692 ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
693 else return (fromIntegral l)
695 -- Blocking versions of the read/write primitives, for the threaded RTS
697 blockingReadRawBuffer loc fd True buf off len =
698 throwErrnoIfMinus1Retry loc $
699 safe_recv_rawBuffer fd buf off len
700 blockingReadRawBuffer loc fd False buf off len =
701 throwErrnoIfMinus1Retry loc $
702 safe_read_rawBuffer fd buf off len
704 blockingReadRawBufferPtr loc fd True buf off len =
705 throwErrnoIfMinus1Retry loc $
706 safe_recv_off fd buf off len
707 blockingReadRawBufferPtr loc fd False buf off len =
708 throwErrnoIfMinus1Retry loc $
709 safe_read_off fd buf off len
711 blockingWriteRawBuffer loc fd True buf off len =
712 throwErrnoIfMinus1Retry loc $
713 safe_send_rawBuffer fd buf off len
714 blockingWriteRawBuffer loc fd False buf off len =
715 throwErrnoIfMinus1Retry loc $
716 safe_write_rawBuffer fd buf off len
718 blockingWriteRawBufferPtr loc fd True buf off len =
719 throwErrnoIfMinus1Retry loc $
720 safe_send_off fd buf off len
721 blockingWriteRawBufferPtr loc fd False buf off len =
722 throwErrnoIfMinus1Retry loc $
723 safe_write_off fd buf off len
725 -- NOTE: "safe" versions of the read/write calls for use by the threaded RTS.
726 -- These calls may block, but that's ok.
728 foreign import ccall safe "__hscore_PrelHandle_recv"
729 safe_recv_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
731 foreign import ccall safe "__hscore_PrelHandle_recv"
732 safe_recv_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
734 foreign import ccall safe "__hscore_PrelHandle_send"
735 safe_send_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
737 foreign import ccall safe "__hscore_PrelHandle_send"
738 safe_send_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
742 foreign import ccall "rtsSupportsBoundThreads" threaded :: Bool
744 foreign import ccall safe "__hscore_PrelHandle_read"
745 safe_read_rawBuffer :: FD -> RawBuffer -> Int -> CInt -> IO CInt
747 foreign import ccall safe "__hscore_PrelHandle_read"
748 safe_read_off :: FD -> Ptr CChar -> Int -> CInt -> IO CInt
750 foreign import ccall safe "__hscore_PrelHandle_write"
751 safe_write_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
753 foreign import ccall safe "__hscore_PrelHandle_write"
754 safe_write_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
756 -- ---------------------------------------------------------------------------
759 -- Three handles are allocated during program initialisation. The first
760 -- two manage input or output from the Haskell program's standard input
761 -- or output channel respectively. The third manages output to the
762 -- standard error channel. These handles are initially open.
768 -- | A handle managing input from the Haskell program's standard input channel.
770 stdin = unsafePerformIO $ do
771 -- ToDo: acquire lock
772 -- We don't set non-blocking mode on standard handles, because it may
773 -- confuse other applications attached to the same TTY/pipe
774 -- see Note [nonblock]
775 (buf, bmode) <- getBuffer fd_stdin ReadBuffer
776 mkStdHandle fd_stdin "<stdin>" ReadHandle buf bmode
778 -- | A handle managing output to the Haskell program's standard output channel.
780 stdout = unsafePerformIO $ do
781 -- ToDo: acquire lock
782 -- We don't set non-blocking mode on standard handles, because it may
783 -- confuse other applications attached to the same TTY/pipe
784 -- see Note [nonblock]
785 (buf, bmode) <- getBuffer fd_stdout WriteBuffer
786 mkStdHandle fd_stdout "<stdout>" WriteHandle buf bmode
788 -- | A handle managing output to the Haskell program's standard error channel.
790 stderr = unsafePerformIO $ do
791 -- ToDo: acquire lock
792 -- We don't set non-blocking mode on standard handles, because it may
793 -- confuse other applications attached to the same TTY/pipe
794 -- see Note [nonblock]
796 mkStdHandle fd_stderr "<stderr>" WriteHandle buf NoBuffering
798 -- ---------------------------------------------------------------------------
799 -- Opening and Closing Files
801 addFilePathToIOError fun fp (IOError h iot _ str _)
802 = IOError h iot fun str (Just fp)
804 -- | Computation 'openFile' @file mode@ allocates and returns a new, open
805 -- handle to manage the file @file@. It manages input if @mode@
806 -- is 'ReadMode', output if @mode@ is 'WriteMode' or 'AppendMode',
807 -- and both input and output if mode is 'ReadWriteMode'.
809 -- If the file does not exist and it is opened for output, it should be
810 -- created as a new file. If @mode@ is 'WriteMode' and the file
811 -- already exists, then it should be truncated to zero length.
812 -- Some operating systems delete empty files, so there is no guarantee
813 -- that the file will exist following an 'openFile' with @mode@
814 -- 'WriteMode' unless it is subsequently written to successfully.
815 -- The handle is positioned at the end of the file if @mode@ is
816 -- 'AppendMode', and otherwise at the beginning (in which case its
817 -- internal position is 0).
818 -- The initial buffer mode is implementation-dependent.
820 -- This operation may fail with:
822 -- * 'isAlreadyInUseError' if the file is already open and cannot be reopened;
824 -- * 'isDoesNotExistError' if the file does not exist; or
826 -- * 'isPermissionError' if the user does not have permission to open the file.
828 -- Note: if you will be working with files containing binary data, you'll want to
829 -- be using 'openBinaryFile'.
830 openFile :: FilePath -> IOMode -> IO Handle
833 (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE)
834 (\e -> ioError (addFilePathToIOError "openFile" fp e))
836 -- | Like 'openFile', but open the file in binary mode.
837 -- On Windows, reading a file in text mode (which is the default)
838 -- will translate CRLF to LF, and writing will translate LF to CRLF.
839 -- This is usually what you want with text files. With binary files
840 -- this is undesirable; also, as usual under Microsoft operating systems,
841 -- text mode treats control-Z as EOF. Binary mode turns off all special
842 -- treatment of end-of-line and end-of-file characters.
843 -- (See also 'hSetBinaryMode'.)
845 openBinaryFile :: FilePath -> IOMode -> IO Handle
846 openBinaryFile fp m =
848 (openFile' fp m True)
849 (\e -> ioError (addFilePathToIOError "openBinaryFile" fp e))
851 openFile' filepath mode binary =
852 withCString filepath $ \ f ->
855 oflags1 = case mode of
856 ReadMode -> read_flags
857 #ifdef mingw32_HOST_OS
858 WriteMode -> write_flags .|. o_TRUNC
860 WriteMode -> write_flags
862 ReadWriteMode -> rw_flags
863 AppendMode -> append_flags
869 oflags = oflags1 .|. binary_flags
872 -- the old implementation had a complicated series of three opens,
873 -- which is perhaps because we have to be careful not to open
874 -- directories. However, the man pages I've read say that open()
875 -- always returns EISDIR if the file is a directory and was opened
876 -- for writing, so I think we're ok with a single open() here...
877 fd <- throwErrnoIfMinus1Retry "openFile"
878 (c_open f (fromIntegral oflags) 0o666)
880 stat@(fd_type,_,_) <- fdStat fd
882 h <- fdToHandle_stat fd (Just stat) False filepath mode binary
883 `catchException` \e -> do c_close fd; throw e
884 -- NB. don't forget to close the FD if fdToHandle' fails, otherwise
886 -- ASSERT: if we just created the file, then fdToHandle' won't fail
887 -- (so we don't need to worry about removing the newly created file
888 -- in the event of an error).
890 #ifndef mingw32_HOST_OS
891 -- we want to truncate() if this is an open in WriteMode, but only
892 -- if the target is a RegularFile. ftruncate() fails on special files
894 if mode == WriteMode && fd_type == RegularFile
895 then throwErrnoIf (/=0) "openFile"
902 std_flags = o_NONBLOCK .|. o_NOCTTY
903 output_flags = std_flags .|. o_CREAT
904 read_flags = std_flags .|. o_RDONLY
905 write_flags = output_flags .|. o_WRONLY
906 rw_flags = output_flags .|. o_RDWR
907 append_flags = write_flags .|. o_APPEND
909 -- ---------------------------------------------------------------------------
912 fdToHandle_stat :: FD
913 -> Maybe (FDType, CDev, CIno)
920 fdToHandle_stat fd mb_stat is_socket filepath mode binary = do
921 -- turn on non-blocking mode
924 #ifdef mingw32_HOST_OS
925 -- On Windows, the is_stream flag indicates that the Handle is a socket
926 let is_stream = is_socket
928 -- On Unix, the is_stream flag indicates that the FD is non-blocking
932 let (ha_type, write) =
934 ReadMode -> ( ReadHandle, False )
935 WriteMode -> ( WriteHandle, True )
936 ReadWriteMode -> ( ReadWriteHandle, True )
937 AppendMode -> ( AppendHandle, True )
939 -- open() won't tell us if it was a directory if we only opened for
940 -- reading, so check again.
948 ioException (IOError Nothing InappropriateType "openFile"
949 "is a directory" Nothing)
951 -- regular files need to be locked
953 #ifndef mingw32_HOST_OS
954 r <- lockFile fd dev ino (fromBool write)
956 ioException (IOError Nothing ResourceBusy "openFile"
957 "file is locked" Nothing)
959 mkFileHandle fd is_stream filepath ha_type binary
962 -- only *Streams* can be DuplexHandles. Other read/write
963 -- Handles must share a buffer.
964 | ReadWriteHandle <- ha_type ->
965 mkDuplexHandle fd is_stream filepath binary
967 mkFileHandle fd is_stream filepath ha_type binary
970 mkFileHandle fd is_stream filepath ha_type binary
972 -- | Old API kept to avoid breaking clients
973 fdToHandle' :: FD -> Maybe FDType -> Bool -> FilePath -> IOMode -> Bool
975 fdToHandle' fd mb_type is_socket filepath mode binary
977 let mb_stat = case mb_type of
979 -- fdToHandle_stat will do the stat:
980 Just RegularFile -> Nothing
981 -- no stat required for streams etc.:
982 Just other -> Just (other,0,0)
983 fdToHandle_stat fd mb_stat is_socket filepath mode binary
985 fdToHandle :: FD -> IO Handle
988 let fd_str = "<file descriptor: " ++ show fd ++ ">"
989 fdToHandle_stat fd Nothing False{-XXX!-} fd_str mode True{-bin mode-}
992 #ifndef mingw32_HOST_OS
993 foreign import ccall unsafe "lockFile"
994 lockFile :: CInt -> CDev -> CIno -> CInt -> IO CInt
996 foreign import ccall unsafe "unlockFile"
997 unlockFile :: CInt -> IO CInt
1000 mkStdHandle :: FD -> FilePath -> HandleType -> IORef Buffer -> BufferMode
1002 mkStdHandle fd filepath ha_type buf bmode = do
1003 spares <- newIORef BufferListNil
1004 newFileHandle filepath (stdHandleFinalizer filepath)
1005 (Handle__ { haFD = fd,
1007 haIsBin = dEFAULT_OPEN_IN_BINARY_MODE,
1008 haIsStream = False, -- means FD is blocking on Unix
1009 haBufferMode = bmode,
1012 haOtherSide = Nothing
1015 mkFileHandle :: FD -> Bool -> FilePath -> HandleType -> Bool -> IO Handle
1016 mkFileHandle fd is_stream filepath ha_type binary = do
1017 (buf, bmode) <- getBuffer fd (initBufferState ha_type)
1019 #ifdef mingw32_HOST_OS
1020 -- On Windows, if this is a read/write handle and we are in text mode,
1021 -- turn off buffering. We don't correctly handle the case of switching
1022 -- from read mode to write mode on a buffered text-mode handle, see bug
1024 bmode <- case ha_type of
1025 ReadWriteHandle | not binary -> return NoBuffering
1026 _other -> return bmode
1029 spares <- newIORef BufferListNil
1030 newFileHandle filepath (handleFinalizer filepath)
1031 (Handle__ { haFD = fd,
1034 haIsStream = is_stream,
1035 haBufferMode = bmode,
1038 haOtherSide = Nothing
1041 mkDuplexHandle :: FD -> Bool -> FilePath -> Bool -> IO Handle
1042 mkDuplexHandle fd is_stream filepath binary = do
1043 (w_buf, w_bmode) <- getBuffer fd WriteBuffer
1044 w_spares <- newIORef BufferListNil
1046 Handle__ { haFD = fd,
1047 haType = WriteHandle,
1049 haIsStream = is_stream,
1050 haBufferMode = w_bmode,
1052 haBuffers = w_spares,
1053 haOtherSide = Nothing
1055 write_side <- newMVar w_handle_
1057 (r_buf, r_bmode) <- getBuffer fd ReadBuffer
1058 r_spares <- newIORef BufferListNil
1060 Handle__ { haFD = fd,
1061 haType = ReadHandle,
1063 haIsStream = is_stream,
1064 haBufferMode = r_bmode,
1066 haBuffers = r_spares,
1067 haOtherSide = Just write_side
1069 read_side <- newMVar r_handle_
1071 addMVarFinalizer write_side (handleFinalizer filepath write_side)
1072 return (DuplexHandle filepath read_side write_side)
1075 initBufferState ReadHandle = ReadBuffer
1076 initBufferState _ = WriteBuffer
1078 -- ---------------------------------------------------------------------------
1081 -- | Computation 'hClose' @hdl@ makes handle @hdl@ closed. Before the
1082 -- computation finishes, if @hdl@ is writable its buffer is flushed as
1084 -- Performing 'hClose' on a handle that has already been closed has no effect;
1085 -- doing so is not an error. All other operations on a closed handle will fail.
1086 -- If 'hClose' fails for any reason, any further operations (apart from
1087 -- 'hClose') on the handle will still fail as if @hdl@ had been successfully
1090 hClose :: Handle -> IO ()
1091 hClose h@(FileHandle _ m) = do
1092 mb_exc <- hClose' h m
1094 Nothing -> return ()
1096 hClose h@(DuplexHandle _ r w) = do
1097 mb_exc1 <- hClose' h w
1098 mb_exc2 <- hClose' h r
1099 case (do mb_exc1; mb_exc2) of
1100 Nothing -> return ()
1103 hClose' h m = withHandle' "hClose" h m $ hClose_help
1105 -- hClose_help is also called by lazyRead (in PrelIO) when EOF is read
1106 -- or an IO error occurs on a lazy stream. The semi-closed Handle is
1107 -- then closed immediately. We have to be careful with DuplexHandles
1108 -- though: we have to leave the closing to the finalizer in that case,
1109 -- because the write side may still be in use.
1110 hClose_help :: Handle__ -> IO (Handle__, Maybe Exception)
1111 hClose_help handle_ =
1112 case haType handle_ of
1113 ClosedHandle -> return (handle_,Nothing)
1114 _ -> do flushWriteBufferOnly handle_ -- interruptible
1115 hClose_handle_ handle_
1117 hClose_handle_ handle_ = do
1118 let fd = haFD handle_
1120 -- close the file descriptor, but not when this is the read
1121 -- side of a duplex handle.
1122 -- If an exception is raised by the close(), we want to continue
1123 -- to close the handle and release the lock if it has one, then
1124 -- we return the exception to the caller of hClose_help which can
1125 -- raise it if necessary.
1127 case haOtherSide handle_ of
1129 throwErrnoIfMinus1Retry_ "hClose"
1130 #ifdef mingw32_HOST_OS
1131 (closeFd (haIsStream handle_) fd)
1137 `catchException` \e -> return (Just e)
1139 Just _ -> return Nothing
1141 -- free the spare buffers
1142 writeIORef (haBuffers handle_) BufferListNil
1143 writeIORef (haBuffer handle_) noBuffer
1145 #ifndef mingw32_HOST_OS
1150 -- we must set the fd to -1, because the finalizer is going
1151 -- to run eventually and try to close/unlock it.
1152 return (handle_{ haFD = -1,
1153 haType = ClosedHandle
1157 {-# NOINLINE noBuffer #-}
1158 noBuffer = unsafePerformIO $ allocateBuffer 1 ReadBuffer
1160 -----------------------------------------------------------------------------
1161 -- Detecting and changing the size of a file
1163 -- | For a handle @hdl@ which attached to a physical file,
1164 -- 'hFileSize' @hdl@ returns the size of that file in 8-bit bytes.
1166 hFileSize :: Handle -> IO Integer
1168 withHandle_ "hFileSize" handle $ \ handle_ -> do
1169 case haType handle_ of
1170 ClosedHandle -> ioe_closedHandle
1171 SemiClosedHandle -> ioe_closedHandle
1172 _ -> do flushWriteBufferOnly handle_
1173 r <- fdFileSize (haFD handle_)
1176 else ioException (IOError Nothing InappropriateType "hFileSize"
1177 "not a regular file" Nothing)
1180 -- | 'hSetFileSize' @hdl@ @size@ truncates the physical file with handle @hdl@ to @size@ bytes.
1182 hSetFileSize :: Handle -> Integer -> IO ()
1183 hSetFileSize handle size =
1184 withHandle_ "hSetFileSize" handle $ \ handle_ -> do
1185 case haType handle_ of
1186 ClosedHandle -> ioe_closedHandle
1187 SemiClosedHandle -> ioe_closedHandle
1188 _ -> do flushWriteBufferOnly handle_
1189 throwErrnoIf (/=0) "hSetFileSize"
1190 (c_ftruncate (haFD handle_) (fromIntegral size))
1193 -- ---------------------------------------------------------------------------
1194 -- Detecting the End of Input
1196 -- | For a readable handle @hdl@, 'hIsEOF' @hdl@ returns
1197 -- 'True' if no further input can be taken from @hdl@ or for a
1198 -- physical file, if the current I\/O position is equal to the length of
1199 -- the file. Otherwise, it returns 'False'.
1201 hIsEOF :: Handle -> IO Bool
1204 (do hLookAhead handle; return False)
1205 (\e -> if isEOFError e then return True else ioError e)
1207 -- | The computation 'isEOF' is identical to 'hIsEOF',
1208 -- except that it works only on 'stdin'.
1211 isEOF = hIsEOF stdin
1213 -- ---------------------------------------------------------------------------
1216 -- | Computation 'hLookAhead' returns the next character from the handle
1217 -- without removing it from the input buffer, blocking until a character
1220 -- This operation may fail with:
1222 -- * 'isEOFError' if the end of file has been reached.
1224 hLookAhead :: Handle -> IO Char
1225 hLookAhead handle = do
1226 wantReadableHandle "hLookAhead" handle $ \handle_ -> do
1227 let ref = haBuffer handle_
1229 is_line = haBufferMode handle_ == LineBuffering
1230 buf <- readIORef ref
1232 -- fill up the read buffer if necessary
1233 new_buf <- if bufferEmpty buf
1234 then fillReadBuffer fd True (haIsStream handle_) buf
1237 writeIORef ref new_buf
1239 (c,_) <- readCharFromBuffer (bufBuf buf) (bufRPtr buf)
1242 -- ---------------------------------------------------------------------------
1243 -- Buffering Operations
1245 -- Three kinds of buffering are supported: line-buffering,
1246 -- block-buffering or no-buffering. See GHC.IOBase for definition and
1247 -- further explanation of what the type represent.
1249 -- | Computation 'hSetBuffering' @hdl mode@ sets the mode of buffering for
1250 -- handle @hdl@ on subsequent reads and writes.
1252 -- If the buffer mode is changed from 'BlockBuffering' or
1253 -- 'LineBuffering' to 'NoBuffering', then
1255 -- * if @hdl@ is writable, the buffer is flushed as for 'hFlush';
1257 -- * if @hdl@ is not writable, the contents of the buffer is discarded.
1259 -- This operation may fail with:
1261 -- * 'isPermissionError' if the handle has already been used for reading
1262 -- or writing and the implementation does not allow the buffering mode
1265 hSetBuffering :: Handle -> BufferMode -> IO ()
1266 hSetBuffering handle mode =
1267 withAllHandles__ "hSetBuffering" handle $ \ handle_ -> do
1268 case haType handle_ of
1269 ClosedHandle -> ioe_closedHandle
1272 - we flush the old buffer regardless of whether
1273 the new buffer could fit the contents of the old buffer
1275 - allow a handle's buffering to change even if IO has
1276 occurred (ANSI C spec. does not allow this, nor did
1277 the previous implementation of IO.hSetBuffering).
1278 - a non-standard extension is to allow the buffering
1279 of semi-closed handles to change [sof 6/98]
1283 let state = initBufferState (haType handle_)
1286 -- we always have a 1-character read buffer for
1287 -- unbuffered handles: it's needed to
1288 -- support hLookAhead.
1289 NoBuffering -> allocateBuffer 1 ReadBuffer
1290 LineBuffering -> allocateBuffer dEFAULT_BUFFER_SIZE state
1291 BlockBuffering Nothing -> allocateBuffer dEFAULT_BUFFER_SIZE state
1292 BlockBuffering (Just n) | n <= 0 -> ioe_bufsiz n
1293 | otherwise -> allocateBuffer n state
1294 writeIORef (haBuffer handle_) new_buf
1296 -- for input terminals we need to put the terminal into
1297 -- cooked or raw mode depending on the type of buffering.
1298 is_tty <- fdIsTTY (haFD handle_)
1299 when (is_tty && isReadableHandleType (haType handle_)) $
1301 #ifndef mingw32_HOST_OS
1302 -- 'raw' mode under win32 is a bit too specialised (and troublesome
1303 -- for most common uses), so simply disable its use here.
1304 NoBuffering -> setCooked (haFD handle_) False
1306 NoBuffering -> return ()
1308 _ -> setCooked (haFD handle_) True
1310 -- throw away spare buffers, they might be the wrong size
1311 writeIORef (haBuffers handle_) BufferListNil
1313 return (handle_{ haBufferMode = mode })
1315 -- -----------------------------------------------------------------------------
1318 -- | The action 'hFlush' @hdl@ causes any items buffered for output
1319 -- in handle @hdl@ to be sent immediately to the operating system.
1321 -- This operation may fail with:
1323 -- * 'isFullError' if the device is full;
1325 -- * 'isPermissionError' if a system resource limit would be exceeded.
1326 -- It is unspecified whether the characters in the buffer are discarded
1327 -- or retained under these circumstances.
1329 hFlush :: Handle -> IO ()
1331 wantWritableHandle "hFlush" handle $ \ handle_ -> do
1332 buf <- readIORef (haBuffer handle_)
1333 if bufferIsWritable buf && not (bufferEmpty buf)
1334 then do flushed_buf <- flushWriteBuffer (haFD handle_) (haIsStream handle_) buf
1335 writeIORef (haBuffer handle_) flushed_buf
1339 -- -----------------------------------------------------------------------------
1340 -- Repositioning Handles
1342 data HandlePosn = HandlePosn Handle HandlePosition
1344 instance Eq HandlePosn where
1345 (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
1347 instance Show HandlePosn where
1348 showsPrec p (HandlePosn h pos) =
1349 showsPrec p h . showString " at position " . shows pos
1351 -- HandlePosition is the Haskell equivalent of POSIX' off_t.
1352 -- We represent it as an Integer on the Haskell side, but
1353 -- cheat slightly in that hGetPosn calls upon a C helper
1354 -- that reports the position back via (merely) an Int.
1355 type HandlePosition = Integer
1357 -- | Computation 'hGetPosn' @hdl@ returns the current I\/O position of
1358 -- @hdl@ as a value of the abstract type 'HandlePosn'.
1360 hGetPosn :: Handle -> IO HandlePosn
1361 hGetPosn handle = do
1362 posn <- hTell handle
1363 return (HandlePosn handle posn)
1365 -- | If a call to 'hGetPosn' @hdl@ returns a position @p@,
1366 -- then computation 'hSetPosn' @p@ sets the position of @hdl@
1367 -- to the position it held at the time of the call to 'hGetPosn'.
1369 -- This operation may fail with:
1371 -- * 'isPermissionError' if a system resource limit would be exceeded.
1373 hSetPosn :: HandlePosn -> IO ()
1374 hSetPosn (HandlePosn h i) = hSeek h AbsoluteSeek i
1376 -- ---------------------------------------------------------------------------
1379 -- | A mode that determines the effect of 'hSeek' @hdl mode i@, as follows:
1381 = AbsoluteSeek -- ^ the position of @hdl@ is set to @i@.
1382 | RelativeSeek -- ^ the position of @hdl@ is set to offset @i@
1383 -- from the current position.
1384 | SeekFromEnd -- ^ the position of @hdl@ is set to offset @i@
1385 -- from the end of the file.
1386 deriving (Eq, Ord, Ix, Enum, Read, Show)
1389 - when seeking using `SeekFromEnd', positive offsets (>=0) means
1390 seeking at or past EOF.
1392 - we possibly deviate from the report on the issue of seeking within
1393 the buffer and whether to flush it or not. The report isn't exactly
1397 -- | Computation 'hSeek' @hdl mode i@ sets the position of handle
1398 -- @hdl@ depending on @mode@.
1399 -- The offset @i@ is given in terms of 8-bit bytes.
1401 -- If @hdl@ is block- or line-buffered, then seeking to a position which is not
1402 -- in the current buffer will first cause any items in the output buffer to be
1403 -- written to the device, and then cause the input buffer to be discarded.
1404 -- Some handles may not be seekable (see 'hIsSeekable'), or only support a
1405 -- subset of the possible positioning operations (for instance, it may only
1406 -- be possible to seek to the end of a tape, or to a positive offset from
1407 -- the beginning or current position).
1408 -- It is not possible to set a negative I\/O position, or for
1409 -- a physical file, an I\/O position beyond the current end-of-file.
1411 -- This operation may fail with:
1413 -- * 'isPermissionError' if a system resource limit would be exceeded.
1415 hSeek :: Handle -> SeekMode -> Integer -> IO ()
1416 hSeek handle mode offset =
1417 wantSeekableHandle "hSeek" handle $ \ handle_ -> do
1419 puts ("hSeek " ++ show (mode,offset) ++ "\n")
1421 let ref = haBuffer handle_
1422 buf <- readIORef ref
1428 throwErrnoIfMinus1Retry_ "hSeek"
1429 (c_lseek (haFD handle_) (fromIntegral offset) whence)
1432 whence = case mode of
1433 AbsoluteSeek -> sEEK_SET
1434 RelativeSeek -> sEEK_CUR
1435 SeekFromEnd -> sEEK_END
1437 if bufferIsWritable buf
1438 then do new_buf <- flushWriteBuffer fd (haIsStream handle_) buf
1439 writeIORef ref new_buf
1443 if mode == RelativeSeek && offset >= 0 && offset < fromIntegral (w - r)
1444 then writeIORef ref buf{ bufRPtr = r + fromIntegral offset }
1447 new_buf <- flushReadBuffer (haFD handle_) buf
1448 writeIORef ref new_buf
1452 hTell :: Handle -> IO Integer
1454 wantSeekableHandle "hGetPosn" handle $ \ handle_ -> do
1456 #if defined(mingw32_HOST_OS)
1457 -- urgh, on Windows we have to worry about \n -> \r\n translation,
1458 -- so we can't easily calculate the file position using the
1459 -- current buffer size. Just flush instead.
1462 let fd = haFD handle_
1463 posn <- fromIntegral `liftM`
1464 throwErrnoIfMinus1Retry "hGetPosn"
1465 (c_lseek fd 0 sEEK_CUR)
1467 let ref = haBuffer handle_
1468 buf <- readIORef ref
1471 | bufferIsWritable buf = posn + fromIntegral (bufWPtr buf)
1472 | otherwise = posn - fromIntegral (bufWPtr buf - bufRPtr buf)
1474 puts ("\nhGetPosn: (fd, posn, real_posn) = " ++ show (fd, posn, real_posn) ++ "\n")
1475 puts (" (bufWPtr, bufRPtr) = " ++ show (bufWPtr buf, bufRPtr buf) ++ "\n")
1479 -- -----------------------------------------------------------------------------
1480 -- Handle Properties
1482 -- A number of operations return information about the properties of a
1483 -- handle. Each of these operations returns `True' if the handle has
1484 -- the specified property, and `False' otherwise.
1486 hIsOpen :: Handle -> IO Bool
1488 withHandle_ "hIsOpen" handle $ \ handle_ -> do
1489 case haType handle_ of
1490 ClosedHandle -> return False
1491 SemiClosedHandle -> return False
1494 hIsClosed :: Handle -> IO Bool
1496 withHandle_ "hIsClosed" handle $ \ handle_ -> do
1497 case haType handle_ of
1498 ClosedHandle -> return True
1501 {- not defined, nor exported, but mentioned
1502 here for documentation purposes:
1504 hSemiClosed :: Handle -> IO Bool
1508 return (not (ho || hc))
1511 hIsReadable :: Handle -> IO Bool
1512 hIsReadable (DuplexHandle _ _ _) = return True
1513 hIsReadable handle =
1514 withHandle_ "hIsReadable" handle $ \ handle_ -> do
1515 case haType handle_ of
1516 ClosedHandle -> ioe_closedHandle
1517 SemiClosedHandle -> ioe_closedHandle
1518 htype -> return (isReadableHandleType htype)
1520 hIsWritable :: Handle -> IO Bool
1521 hIsWritable (DuplexHandle _ _ _) = return True
1522 hIsWritable handle =
1523 withHandle_ "hIsWritable" handle $ \ handle_ -> do
1524 case haType handle_ of
1525 ClosedHandle -> ioe_closedHandle
1526 SemiClosedHandle -> ioe_closedHandle
1527 htype -> return (isWritableHandleType htype)
1529 -- | Computation 'hGetBuffering' @hdl@ returns the current buffering mode
1532 hGetBuffering :: Handle -> IO BufferMode
1533 hGetBuffering handle =
1534 withHandle_ "hGetBuffering" handle $ \ handle_ -> do
1535 case haType handle_ of
1536 ClosedHandle -> ioe_closedHandle
1538 -- We're being non-standard here, and allow the buffering
1539 -- of a semi-closed handle to be queried. -- sof 6/98
1540 return (haBufferMode handle_) -- could be stricter..
1542 hIsSeekable :: Handle -> IO Bool
1543 hIsSeekable handle =
1544 withHandle_ "hIsSeekable" handle $ \ handle_ -> do
1545 case haType handle_ of
1546 ClosedHandle -> ioe_closedHandle
1547 SemiClosedHandle -> ioe_closedHandle
1548 AppendHandle -> return False
1549 _ -> do t <- fdType (haFD handle_)
1550 return ((t == RegularFile || t == RawDevice)
1551 && (haIsBin handle_ || tEXT_MODE_SEEK_ALLOWED))
1553 -- -----------------------------------------------------------------------------
1554 -- Changing echo status (Non-standard GHC extensions)
1556 -- | Set the echoing status of a handle connected to a terminal.
1558 hSetEcho :: Handle -> Bool -> IO ()
1559 hSetEcho handle on = do
1560 isT <- hIsTerminalDevice handle
1564 withHandle_ "hSetEcho" handle $ \ handle_ -> do
1565 case haType handle_ of
1566 ClosedHandle -> ioe_closedHandle
1567 _ -> setEcho (haFD handle_) on
1569 -- | Get the echoing status of a handle connected to a terminal.
1571 hGetEcho :: Handle -> IO Bool
1572 hGetEcho handle = do
1573 isT <- hIsTerminalDevice handle
1577 withHandle_ "hGetEcho" handle $ \ handle_ -> do
1578 case haType handle_ of
1579 ClosedHandle -> ioe_closedHandle
1580 _ -> getEcho (haFD handle_)
1582 -- | Is the handle connected to a terminal?
1584 hIsTerminalDevice :: Handle -> IO Bool
1585 hIsTerminalDevice handle = do
1586 withHandle_ "hIsTerminalDevice" handle $ \ handle_ -> do
1587 case haType handle_ of
1588 ClosedHandle -> ioe_closedHandle
1589 _ -> fdIsTTY (haFD handle_)
1591 -- -----------------------------------------------------------------------------
1594 -- | Select binary mode ('True') or text mode ('False') on a open handle.
1595 -- (See also 'openBinaryFile'.)
1597 hSetBinaryMode :: Handle -> Bool -> IO ()
1598 hSetBinaryMode handle bin =
1599 withAllHandles__ "hSetBinaryMode" handle $ \ handle_ ->
1600 do throwErrnoIfMinus1_ "hSetBinaryMode"
1601 (setmode (haFD handle_) bin)
1602 return handle_{haIsBin=bin}
1604 foreign import ccall unsafe "__hscore_setmode"
1605 setmode :: CInt -> Bool -> IO CInt
1607 -- -----------------------------------------------------------------------------
1608 -- Duplicating a Handle
1610 -- | Returns a duplicate of the original handle, with its own buffer.
1611 -- The two Handles will share a file pointer, however. The original
1612 -- handle's buffer is flushed, including discarding any input data,
1613 -- before the handle is duplicated.
1615 hDuplicate :: Handle -> IO Handle
1616 hDuplicate h@(FileHandle path m) = do
1617 new_h_ <- withHandle' "hDuplicate" h m (dupHandle h Nothing)
1618 newFileHandle path (handleFinalizer path) new_h_
1619 hDuplicate h@(DuplexHandle path r w) = do
1620 new_w_ <- withHandle' "hDuplicate" h w (dupHandle h Nothing)
1621 new_w <- newMVar new_w_
1622 new_r_ <- withHandle' "hDuplicate" h r (dupHandle h (Just new_w))
1623 new_r <- newMVar new_r_
1624 addMVarFinalizer new_w (handleFinalizer path new_w)
1625 return (DuplexHandle path new_r new_w)
1627 dupHandle :: Handle -> Maybe (MVar Handle__) -> Handle__
1628 -> IO (Handle__, Handle__)
1629 dupHandle h other_side h_ = do
1630 -- flush the buffer first, so we don't have to copy its contents
1632 new_fd <- case other_side of
1633 Nothing -> throwErrnoIfMinus1 "dupHandle" $ c_dup (haFD h_)
1634 Just r -> withHandle_' "dupHandle" h r (return . haFD)
1635 dupHandle_ other_side h_ new_fd
1637 dupHandleTo other_side hto_ h_ = do
1639 -- Windows' dup2 does not return the new descriptor, unlike Unix
1640 throwErrnoIfMinus1 "dupHandleTo" $
1641 c_dup2 (haFD h_) (haFD hto_)
1642 dupHandle_ other_side h_ (haFD hto_)
1644 dupHandle_ :: Maybe (MVar Handle__) -> Handle__ -> FD
1645 -> IO (Handle__, Handle__)
1646 dupHandle_ other_side h_ new_fd = do
1647 buffer <- allocateBuffer dEFAULT_BUFFER_SIZE (initBufferState (haType h_))
1648 ioref <- newIORef buffer
1649 ioref_buffers <- newIORef BufferListNil
1651 let new_handle_ = h_{ haFD = new_fd,
1653 haBuffers = ioref_buffers,
1654 haOtherSide = other_side }
1655 return (h_, new_handle_)
1657 -- -----------------------------------------------------------------------------
1658 -- Replacing a Handle
1661 Makes the second handle a duplicate of the first handle. The second
1662 handle will be closed first, if it is not already.
1664 This can be used to retarget the standard Handles, for example:
1666 > do h <- openFile "mystdout" WriteMode
1667 > hDuplicateTo h stdout
1670 hDuplicateTo :: Handle -> Handle -> IO ()
1671 hDuplicateTo h1@(FileHandle _ m1) h2@(FileHandle _ m2) = do
1672 withHandle__' "hDuplicateTo" h2 m2 $ \h2_ -> do
1673 _ <- hClose_help h2_
1674 withHandle' "hDuplicateTo" h1 m1 (dupHandleTo Nothing h2_)
1675 hDuplicateTo h1@(DuplexHandle _ r1 w1) h2@(DuplexHandle _ r2 w2) = do
1676 withHandle__' "hDuplicateTo" h2 w2 $ \w2_ -> do
1677 _ <- hClose_help w2_
1678 withHandle' "hDuplicateTo" h1 r1 (dupHandleTo Nothing w2_)
1679 withHandle__' "hDuplicateTo" h2 r2 $ \r2_ -> do
1680 _ <- hClose_help r2_
1681 withHandle' "hDuplicateTo" h1 r1 (dupHandleTo (Just w1) r2_)
1683 ioException (IOError (Just h1) IllegalOperation "hDuplicateTo"
1684 "handles are incompatible" Nothing)
1686 -- ---------------------------------------------------------------------------
1689 -- | 'hShow' is in the 'IO' monad, and gives more comprehensive output
1690 -- than the (pure) instance of 'Show' for 'Handle'.
1692 hShow :: Handle -> IO String
1693 hShow h@(FileHandle path _) = showHandle' path False h
1694 hShow h@(DuplexHandle path _ _) = showHandle' path True h
1696 showHandle' filepath is_duplex h =
1697 withHandle_ "showHandle" h $ \hdl_ ->
1699 showType | is_duplex = showString "duplex (read-write)"
1700 | otherwise = shows (haType hdl_)
1704 showHdl (haType hdl_)
1705 (showString "loc=" . showString filepath . showChar ',' .
1706 showString "type=" . showType . showChar ',' .
1707 showString "binary=" . shows (haIsBin hdl_) . showChar ',' .
1708 showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
1712 showHdl :: HandleType -> ShowS -> ShowS
1715 ClosedHandle -> shows ht . showString "}"
1718 showBufMode :: Buffer -> BufferMode -> ShowS
1719 showBufMode buf bmo =
1721 NoBuffering -> showString "none"
1722 LineBuffering -> showString "line"
1723 BlockBuffering (Just n) -> showString "block " . showParen True (shows n)
1724 BlockBuffering Nothing -> showString "block " . showParen True (shows def)
1729 -- ---------------------------------------------------------------------------
1732 #if defined(DEBUG_DUMP)
1733 puts :: String -> IO ()
1734 puts s = do write_rawBuffer 1 (unsafeCoerce# (packCString# s)) 0 (fromIntegral (length s))
1738 -- -----------------------------------------------------------------------------
1741 throwErrnoIfMinus1RetryOnBlock :: String -> IO CInt -> IO CInt -> IO CInt
1742 throwErrnoIfMinus1RetryOnBlock loc f on_block =
1745 if (res :: CInt) == -1
1749 then throwErrnoIfMinus1RetryOnBlock loc f on_block
1750 else if err == eWOULDBLOCK || err == eAGAIN
1755 -- -----------------------------------------------------------------------------
1756 -- wrappers to platform-specific constants:
1758 foreign import ccall unsafe "__hscore_supportsTextMode"
1759 tEXT_MODE_SEEK_ALLOWED :: Bool
1761 foreign import ccall unsafe "__hscore_bufsiz" dEFAULT_BUFFER_SIZE :: Int
1762 foreign import ccall unsafe "__hscore_seek_cur" sEEK_CUR :: CInt
1763 foreign import ccall unsafe "__hscore_seek_set" sEEK_SET :: CInt
1764 foreign import ccall unsafe "__hscore_seek_end" sEEK_END :: CInt