Add errno to the IOError type
[ghc-base.git] / GHC / Handle.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude -#include "HsBase.h" #-}
2 {-# OPTIONS_GHC -fno-warn-unused-matches #-}
3 {-# OPTIONS_GHC -fno-warn-unused-binds #-}
4 {-# OPTIONS_HADDOCK hide #-}
5
6 #undef DEBUG_DUMP
7 #undef DEBUG
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module      :  GHC.Handle
12 -- Copyright   :  (c) The University of Glasgow, 1994-2001
13 -- License     :  see libraries/base/LICENSE
14 -- 
15 -- Maintainer  :  libraries@haskell.org
16 -- Stability   :  internal
17 -- Portability :  non-portable
18 --
19 -- This module defines the basic operations on I\/O \"handles\".
20 --
21 -----------------------------------------------------------------------------
22
23 -- #hide
24 module GHC.Handle (
25   withHandle, withHandle', withHandle_,
26   wantWritableHandle, wantReadableHandle, wantSeekableHandle,
27
28   newEmptyBuffer, allocateBuffer, readCharFromBuffer, writeCharIntoBuffer,
29   flushWriteBufferOnly, flushWriteBuffer, flushReadBuffer,
30   fillReadBuffer, fillReadBufferWithoutBlocking,
31   readRawBuffer, readRawBufferPtr,
32   readRawBufferNoBlock, readRawBufferPtrNoBlock,
33   writeRawBuffer, writeRawBufferPtr,
34
35 #ifndef mingw32_HOST_OS
36   unlockFile,
37 #endif
38
39   ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable,
40
41   stdin, stdout, stderr,
42   IOMode(..), openFile, openBinaryFile, fdToHandle_stat, fdToHandle, fdToHandle',
43   hFileSize, hSetFileSize, hIsEOF, isEOF, hLookAhead, hLookAhead', hSetBuffering, hSetBinaryMode,
44   hFlush, hDuplicate, hDuplicateTo,
45
46   hClose, hClose_help,
47
48   HandlePosition, HandlePosn(..), hGetPosn, hSetPosn,
49   SeekMode(..), hSeek, hTell,
50
51   hIsOpen, hIsClosed, hIsReadable, hIsWritable, hGetBuffering, hIsSeekable,
52   hSetEcho, hGetEcho, hIsTerminalDevice,
53
54   hShow,
55
56 #ifdef DEBUG_DUMP
57   puts,
58 #endif
59
60  ) where
61
62 import Control.Monad
63 import Data.Maybe
64 import Foreign
65 import Foreign.C
66 import System.IO.Error
67 import System.Posix.Internals
68 import System.Posix.Types
69
70 import GHC.Real
71
72 import GHC.Arr
73 import GHC.Base
74 import GHC.Read         ( Read )
75 import GHC.List
76 import GHC.IOBase
77 import GHC.Exception
78 import GHC.Enum
79 import GHC.Num          ( Integer, Num(..) )
80 import GHC.Show
81 #if defined(DEBUG_DUMP)
82 import GHC.Pack
83 #endif
84
85 import GHC.Conc
86
87 -- -----------------------------------------------------------------------------
88 -- TODO:
89
90 -- hWaitForInput blocks (should use a timeout)
91
92 -- unbuffered hGetLine is a bit dodgy
93
94 -- hSetBuffering: can't change buffering on a stream, 
95 --      when the read buffer is non-empty? (no way to flush the buffer)
96
97 -- ---------------------------------------------------------------------------
98 -- Are files opened by default in text or binary mode, if the user doesn't
99 -- specify?
100
101 dEFAULT_OPEN_IN_BINARY_MODE :: Bool
102 dEFAULT_OPEN_IN_BINARY_MODE = False
103
104 -- ---------------------------------------------------------------------------
105 -- Creating a new handle
106
107 newFileHandle :: FilePath -> (MVar Handle__ -> IO ()) -> Handle__ -> IO Handle
108 newFileHandle filepath finalizer hc = do
109   m <- newMVar hc
110   addMVarFinalizer m (finalizer m)
111   return (FileHandle filepath m)
112
113 -- ---------------------------------------------------------------------------
114 -- Working with Handles
115
116 {-
117 In the concurrent world, handles are locked during use.  This is done
118 by wrapping an MVar around the handle which acts as a mutex over
119 operations on the handle.
120
121 To avoid races, we use the following bracketing operations.  The idea
122 is to obtain the lock, do some operation and replace the lock again,
123 whether the operation succeeded or failed.  We also want to handle the
124 case where the thread receives an exception while processing the IO
125 operation: in these cases we also want to relinquish the lock.
126
127 There are three versions of @withHandle@: corresponding to the three
128 possible combinations of:
129
130         - the operation may side-effect the handle
131         - the operation may return a result
132
133 If the operation generates an error or an exception is raised, the
134 original handle is always replaced [ this is the case at the moment,
135 but we might want to revisit this in the future --SDM ].
136 -}
137
138 {-# INLINE withHandle #-}
139 withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a
140 withHandle fun h@(FileHandle _ m)     act = withHandle' fun h m act
141 withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act
142
143 withHandle' :: String -> Handle -> MVar Handle__
144    -> (Handle__ -> IO (Handle__,a)) -> IO a
145 withHandle' fun h m act =
146    block $ do
147    h_ <- takeMVar m
148    checkBufferInvariants h_
149    (h',v)  <- (act h_ `catchAny` \err -> putMVar m h_ >> throw err)
150               `catchException` \ex -> ioError (augmentIOError ex fun h)
151    checkBufferInvariants h'
152    putMVar m h'
153    return v
154
155 {-# INLINE withHandle_ #-}
156 withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a
157 withHandle_ fun h@(FileHandle _ m)     act = withHandle_' fun h m act
158 withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act
159
160 withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a
161 withHandle_' fun h m act =
162    block $ do
163    h_ <- takeMVar m
164    checkBufferInvariants h_
165    v  <- (act h_ `catchAny` \err -> putMVar m h_ >> throw err)
166          `catchException` \ex -> ioError (augmentIOError ex fun h)
167    checkBufferInvariants h_
168    putMVar m h_
169    return v
170
171 withAllHandles__ :: String -> Handle -> (Handle__ -> IO Handle__) -> IO ()
172 withAllHandles__ fun h@(FileHandle _ m)     act = withHandle__' fun h m act
173 withAllHandles__ fun h@(DuplexHandle _ r w) act = do
174   withHandle__' fun h r act
175   withHandle__' fun h w act
176
177 withHandle__' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO Handle__)
178               -> IO ()
179 withHandle__' fun h m act =
180    block $ do
181    h_ <- takeMVar m
182    checkBufferInvariants h_
183    h'  <- (act h_ `catchAny` \err -> putMVar m h_ >> throw err)
184           `catchException` \ex -> ioError (augmentIOError ex fun h)
185    checkBufferInvariants h'
186    putMVar m h'
187    return ()
188
189 augmentIOError :: IOException -> String -> Handle -> IOException
190 augmentIOError ioe@IOError{ ioe_filename = fp } fun h
191   = ioe { ioe_handle = Just h, ioe_location = fun, ioe_filename = filepath }
192   where filepath
193           | Just _ <- fp = fp
194           | otherwise = case h of
195                           FileHandle path _     -> Just path
196                           DuplexHandle path _ _ -> Just path
197
198 -- ---------------------------------------------------------------------------
199 -- Wrapper for write operations.
200
201 wantWritableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
202 wantWritableHandle fun h@(FileHandle _ m) act
203   = wantWritableHandle' fun h m act
204 wantWritableHandle fun h@(DuplexHandle _ _ m) act
205   = wantWritableHandle' fun h m act
206   -- ToDo: in the Duplex case, we don't need to checkWritableHandle
207
208 wantWritableHandle'
209         :: String -> Handle -> MVar Handle__
210         -> (Handle__ -> IO a) -> IO a
211 wantWritableHandle' fun h m act
212    = withHandle_' fun h m (checkWritableHandle act)
213
214 checkWritableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
215 checkWritableHandle act handle_
216   = case haType handle_ of
217       ClosedHandle         -> ioe_closedHandle
218       SemiClosedHandle     -> ioe_closedHandle
219       ReadHandle           -> ioe_notWritable
220       ReadWriteHandle      -> do
221                 let ref = haBuffer handle_
222                 buf <- readIORef ref
223                 new_buf <-
224                   if not (bufferIsWritable buf)
225                      then do b <- flushReadBuffer (haFD handle_) buf
226                              return b{ bufState=WriteBuffer }
227                      else return buf
228                 writeIORef ref new_buf
229                 act handle_
230       _other               -> act handle_
231
232 -- ---------------------------------------------------------------------------
233 -- Wrapper for read operations.
234
235 wantReadableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
236 wantReadableHandle fun h@(FileHandle  _ m)   act
237   = wantReadableHandle' fun h m act
238 wantReadableHandle fun h@(DuplexHandle _ m _) act
239   = wantReadableHandle' fun h m act
240   -- ToDo: in the Duplex case, we don't need to checkReadableHandle
241
242 wantReadableHandle'
243         :: String -> Handle -> MVar Handle__
244         -> (Handle__ -> IO a) -> IO a
245 wantReadableHandle' fun h m act
246   = withHandle_' fun h m (checkReadableHandle act)
247
248 checkReadableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
249 checkReadableHandle act handle_ =
250     case haType handle_ of
251       ClosedHandle         -> ioe_closedHandle
252       SemiClosedHandle     -> ioe_closedHandle
253       AppendHandle         -> ioe_notReadable
254       WriteHandle          -> ioe_notReadable
255       ReadWriteHandle      -> do
256         let ref = haBuffer handle_
257         buf <- readIORef ref
258         when (bufferIsWritable buf) $ do
259            new_buf <- flushWriteBuffer (haFD handle_) (haIsStream handle_) buf
260            writeIORef ref new_buf{ bufState=ReadBuffer }
261         act handle_
262       _other               -> act handle_
263
264 -- ---------------------------------------------------------------------------
265 -- Wrapper for seek operations.
266
267 wantSeekableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a
268 wantSeekableHandle fun h@(DuplexHandle _ _ _) _act =
269   ioException (IOError (Just h) IllegalOperation fun
270                    "handle is not seekable" Nothing Nothing)
271 wantSeekableHandle fun h@(FileHandle _ m) act =
272   withHandle_' fun h m (checkSeekableHandle act)
273
274 checkSeekableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a
275 checkSeekableHandle act handle_ =
276     case haType handle_ of
277       ClosedHandle      -> ioe_closedHandle
278       SemiClosedHandle  -> ioe_closedHandle
279       AppendHandle      -> ioe_notSeekable
280       _  | haIsBin handle_ || tEXT_MODE_SEEK_ALLOWED -> act handle_
281          | otherwise                                 -> ioe_notSeekable_notBin
282
283 -- -----------------------------------------------------------------------------
284 -- Handy IOErrors
285
286 ioe_closedHandle, ioe_EOF,
287   ioe_notReadable, ioe_notWritable,
288   ioe_notSeekable, ioe_notSeekable_notBin :: IO a
289
290 ioe_closedHandle = ioException
291    (IOError Nothing IllegalOperation ""
292         "handle is closed" Nothing Nothing)
293 ioe_EOF = ioException
294    (IOError Nothing EOF "" "" Nothing Nothing)
295 ioe_notReadable = ioException
296    (IOError Nothing IllegalOperation ""
297         "handle is not open for reading" Nothing Nothing)
298 ioe_notWritable = ioException
299    (IOError Nothing IllegalOperation ""
300         "handle is not open for writing" Nothing Nothing)
301 ioe_notSeekable = ioException
302    (IOError Nothing IllegalOperation ""
303         "handle is not seekable" Nothing Nothing)
304 ioe_notSeekable_notBin = ioException
305    (IOError Nothing IllegalOperation ""
306       "seek operations on text-mode handles are not allowed on this platform"
307         Nothing Nothing)
308
309 ioe_finalizedHandle :: FilePath -> Handle__
310 ioe_finalizedHandle fp = throw
311    (IOError Nothing IllegalOperation ""
312         "handle is finalized" Nothing (Just fp))
313
314 ioe_bufsiz :: Int -> IO a
315 ioe_bufsiz n = ioException
316    (IOError Nothing InvalidArgument "hSetBuffering"
317         ("illegal buffer size " ++ showsPrec 9 n []) Nothing Nothing)
318                                 -- 9 => should be parens'ified.
319
320 -- -----------------------------------------------------------------------------
321 -- Handle Finalizers
322
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.
328
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.
335
336 stdHandleFinalizer :: FilePath -> MVar Handle__ -> IO ()
337 stdHandleFinalizer fp m = do
338   h_ <- takeMVar m
339   flushWriteBufferOnly h_
340   putMVar m (ioe_finalizedHandle fp)
341
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_ `catchAny` \_ -> return ()
348                 -- ignore errors and async exceptions, and close the
349                 -- descriptor anyway...
350               hClose_handle_ handle_
351               return ()
352   putMVar m (ioe_finalizedHandle fp)
353
354 -- ---------------------------------------------------------------------------
355 -- Grimy buffer operations
356
357 checkBufferInvariants :: Handle__ -> IO ()
358 #ifdef DEBUG
359 checkBufferInvariants h_ = do
360  let ref = haBuffer h_
361  Buffer{ bufWPtr=w, bufRPtr=r, bufSize=size, bufState=state } <- readIORef ref
362  if not (
363         size > 0
364         && r <= w
365         && w <= size
366         && ( r /= w || (r == 0 && w == 0) )
367         && ( state /= WriteBuffer || r == 0 )
368         && ( state /= WriteBuffer || w < size ) -- write buffer is never full
369      )
370    then error "buffer invariant violation"
371    else return ()
372 #else
373 checkBufferInvariants _ = return ()
374 #endif
375
376 newEmptyBuffer :: RawBuffer -> BufferState -> Int -> Buffer
377 newEmptyBuffer b state size
378   = Buffer{ bufBuf=b, bufRPtr=0, bufWPtr=0, bufSize=size, bufState=state }
379
380 allocateBuffer :: Int -> BufferState -> IO Buffer
381 allocateBuffer sz@(I# size) state = IO $ \s -> 
382    -- We sometimes need to pass the address of this buffer to
383    -- a "safe" foreign call, hence it must be immovable.
384   case newPinnedByteArray# size s of { (# s', b #) ->
385   (# s', newEmptyBuffer b state sz #) }
386
387 writeCharIntoBuffer :: RawBuffer -> Int -> Char -> IO Int
388 writeCharIntoBuffer slab (I# off) (C# c)
389   = IO $ \s -> case writeCharArray# slab off c s of 
390                s' -> (# s', I# (off +# 1#) #)
391
392 readCharFromBuffer :: RawBuffer -> Int -> IO (Char, Int)
393 readCharFromBuffer slab (I# off)
394   = IO $ \s -> case readCharArray# slab off s of 
395                  (# s', c #) -> (# s', (C# c, I# (off +# 1#)) #)
396
397 getBuffer :: FD -> BufferState -> IO (IORef Buffer, BufferMode)
398 getBuffer fd state = do
399   buffer <- allocateBuffer dEFAULT_BUFFER_SIZE state
400   ioref  <- newIORef buffer
401   is_tty <- fdIsTTY fd
402
403   let buffer_mode 
404          | is_tty    = LineBuffering 
405          | otherwise = BlockBuffering Nothing
406
407   return (ioref, buffer_mode)
408
409 mkUnBuffer :: IO (IORef Buffer)
410 mkUnBuffer = do
411   buffer <- allocateBuffer 1 ReadBuffer
412   newIORef buffer
413
414 -- flushWriteBufferOnly flushes the buffer iff it contains pending write data.
415 flushWriteBufferOnly :: Handle__ -> IO ()
416 flushWriteBufferOnly h_ = do
417   let fd = haFD h_
418       ref = haBuffer h_
419   buf <- readIORef ref
420   new_buf <- if bufferIsWritable buf 
421                 then flushWriteBuffer fd (haIsStream h_) buf 
422                 else return buf
423   writeIORef ref new_buf
424
425 -- flushBuffer syncs the file with the buffer, including moving the
426 -- file pointer backwards in the case of a read buffer.
427 flushBuffer :: Handle__ -> IO ()
428 flushBuffer h_ = do
429   let ref = haBuffer h_
430   buf <- readIORef ref
431
432   flushed_buf <-
433     case bufState buf of
434       ReadBuffer  -> flushReadBuffer  (haFD h_) buf
435       WriteBuffer -> flushWriteBuffer (haFD h_) (haIsStream h_) buf
436
437   writeIORef ref flushed_buf
438
439 -- When flushing a read buffer, we seek backwards by the number of
440 -- characters in the buffer.  The file descriptor must therefore be
441 -- seekable: attempting to flush the read buffer on an unseekable
442 -- handle is not allowed.
443
444 flushReadBuffer :: FD -> Buffer -> IO Buffer
445 flushReadBuffer fd buf
446   | bufferEmpty buf = return buf
447   | otherwise = do
448      let off = negate (bufWPtr buf - bufRPtr buf)
449 #    ifdef DEBUG_DUMP
450      puts ("flushReadBuffer: new file offset = " ++ show off ++ "\n")
451 #    endif
452      throwErrnoIfMinus1Retry "flushReadBuffer"
453          (c_lseek fd (fromIntegral off) sEEK_CUR)
454      return buf{ bufWPtr=0, bufRPtr=0 }
455
456 flushWriteBuffer :: FD -> Bool -> Buffer -> IO Buffer
457 flushWriteBuffer fd is_stream buf@Buffer{ bufBuf=b, bufRPtr=r, bufWPtr=w }  =
458   seq fd $ do -- strictness hack
459   let bytes = w - r
460 #ifdef DEBUG_DUMP
461   puts ("flushWriteBuffer, fd=" ++ show fd ++ ", bytes=" ++ show bytes ++ "\n")
462 #endif
463   if bytes == 0
464      then return (buf{ bufRPtr=0, bufWPtr=0 })
465      else do
466   res <- writeRawBuffer "flushWriteBuffer" fd is_stream b 
467                         (fromIntegral r) (fromIntegral bytes)
468   let res' = fromIntegral res
469   if res' < bytes 
470      then flushWriteBuffer fd is_stream (buf{ bufRPtr = r + res' })
471      else return buf{ bufRPtr=0, bufWPtr=0 }
472
473 fillReadBuffer :: FD -> Bool -> Bool -> Buffer -> IO Buffer
474 fillReadBuffer fd is_line is_stream
475       buf@Buffer{ bufBuf=b, bufRPtr=r, bufWPtr=w, bufSize=size } =
476   -- buffer better be empty:
477   assert (r == 0 && w == 0) $ do
478   fillReadBufferLoop fd is_line is_stream buf b w size
479
480 -- For a line buffer, we just get the first chunk of data to arrive,
481 -- and don't wait for the whole buffer to be full (but we *do* wait
482 -- until some data arrives).  This isn't really line buffering, but it
483 -- appears to be what GHC has done for a long time, and I suspect it
484 -- is more useful than line buffering in most cases.
485
486 fillReadBufferLoop :: FD -> Bool -> Bool -> Buffer -> RawBuffer -> Int -> Int
487                    -> IO Buffer
488 fillReadBufferLoop fd is_line is_stream buf b w size = do
489   let bytes = size - w
490   if bytes == 0  -- buffer full?
491      then return buf{ bufRPtr=0, bufWPtr=w }
492      else do
493 #ifdef DEBUG_DUMP
494   puts ("fillReadBufferLoop: bytes = " ++ show bytes ++ "\n")
495 #endif
496   res <- readRawBuffer "fillReadBuffer" fd is_stream b
497                        (fromIntegral w) (fromIntegral bytes)
498   let res' = fromIntegral res
499 #ifdef DEBUG_DUMP
500   puts ("fillReadBufferLoop:  res' = " ++ show res' ++ "\n")
501 #endif
502   if res' == 0
503      then if w == 0
504              then ioe_EOF
505              else return buf{ bufRPtr=0, bufWPtr=w }
506      else if res' < bytes && not is_line
507              then fillReadBufferLoop fd is_line is_stream buf b (w+res') size
508              else return buf{ bufRPtr=0, bufWPtr=w+res' }
509  
510
511 fillReadBufferWithoutBlocking :: FD -> Bool -> Buffer -> IO Buffer
512 fillReadBufferWithoutBlocking fd is_stream
513       buf@Buffer{ bufBuf=b, bufRPtr=r, bufWPtr=w, bufSize=size } =
514   -- buffer better be empty:
515   assert (r == 0 && w == 0) $ do
516 #ifdef DEBUG_DUMP
517   puts ("fillReadBufferLoopNoBlock: bytes = " ++ show size ++ "\n")
518 #endif
519   res <- readRawBufferNoBlock "fillReadBuffer" fd is_stream b
520                        0 (fromIntegral size)
521   let res' = fromIntegral res
522 #ifdef DEBUG_DUMP
523   puts ("fillReadBufferLoopNoBlock:  res' = " ++ show res' ++ "\n")
524 #endif
525   return buf{ bufRPtr=0, bufWPtr=res' }
526  
527 -- Low level routines for reading/writing to (raw)buffers:
528
529 #ifndef mingw32_HOST_OS
530
531 {-
532 NOTE [nonblock]:
533
534 Unix has broken semantics when it comes to non-blocking I/O: you can
535 set the O_NONBLOCK flag on an FD, but it applies to the all other FDs
536 attached to the same underlying file, pipe or TTY; there's no way to
537 have private non-blocking behaviour for an FD.  See bug #724.
538
539 We fix this by only setting O_NONBLOCK on FDs that we create; FDs that
540 come from external sources or are exposed externally are left in
541 blocking mode.  This solution has some problems though.  We can't
542 completely simulate a non-blocking read without O_NONBLOCK: several
543 cases are wrong here.  The cases that are wrong:
544
545   * reading/writing to a blocking FD in non-threaded mode.
546     In threaded mode, we just make a safe call to read().  
547     In non-threaded mode we call select() before attempting to read,
548     but that leaves a small race window where the data can be read
549     from the file descriptor before we issue our blocking read().
550   * readRawBufferNoBlock for a blocking FD
551
552 NOTE [2363]:
553
554 In the threaded RTS we could just make safe calls to read()/write()
555 for file descriptors in blocking mode without worrying about blocking
556 other threads, but the problem with this is that the thread will be
557 uninterruptible while it is blocked in the foreign call.  See #2363.
558 So now we always call fdReady() before reading, and if fdReady
559 indicates that there's no data, we call threadWaitRead.
560
561 -}
562
563 readRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
564 readRawBuffer loc fd is_nonblock buf off len
565   | is_nonblock  = unsafe_read -- unsafe is ok, it can't block
566   | otherwise    = do r <- throwErrnoIfMinus1 loc 
567                                 (unsafe_fdReady (fromIntegral fd) 0 0 0)
568                       if r /= 0
569                         then read
570                         else do threadWaitRead (fromIntegral fd); read
571   where
572     do_read call = throwErrnoIfMinus1RetryMayBlock loc call 
573                             (threadWaitRead (fromIntegral fd))
574     read        = if threaded then safe_read else unsafe_read
575     unsafe_read = do_read (read_rawBuffer fd buf off len)
576     safe_read   = do_read (safe_read_rawBuffer fd buf off len)
577
578 readRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
579 readRawBufferPtr loc fd is_nonblock buf off len
580   | is_nonblock  = unsafe_read -- unsafe is ok, it can't block
581   | otherwise    = do r <- throwErrnoIfMinus1 loc 
582                                 (unsafe_fdReady (fromIntegral fd) 0 0 0)
583                       if r /= 0 
584                         then read
585                         else do threadWaitRead (fromIntegral fd); read
586   where
587     do_read call = throwErrnoIfMinus1RetryMayBlock loc call 
588                             (threadWaitRead (fromIntegral fd))
589     read        = if threaded then safe_read else unsafe_read
590     unsafe_read = do_read (read_off fd buf off len)
591     safe_read   = do_read (safe_read_off fd buf off len)
592
593 readRawBufferNoBlock :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
594 readRawBufferNoBlock loc fd is_nonblock buf off len
595   | is_nonblock  = unsafe_read -- unsafe is ok, it can't block
596   | otherwise    = do r <- unsafe_fdReady (fromIntegral fd) 0 0 0
597                       if r /= 0 then safe_read
598                                 else return 0
599        -- XXX see note [nonblock]
600  where
601    do_read call = throwErrnoIfMinus1RetryOnBlock loc call (return 0)
602    unsafe_read  = do_read (read_rawBuffer fd buf off len)
603    safe_read    = do_read (safe_read_rawBuffer fd buf off len)
604
605 readRawBufferPtrNoBlock :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
606 readRawBufferPtrNoBlock loc fd is_nonblock buf off len
607   | is_nonblock  = unsafe_read -- unsafe is ok, it can't block
608   | otherwise    = do r <- unsafe_fdReady (fromIntegral fd) 0 0 0
609                       if r /= 0 then safe_read
610                                 else return 0
611        -- XXX see note [nonblock]
612  where
613    do_read call = throwErrnoIfMinus1RetryOnBlock loc call (return 0)
614    unsafe_read  = do_read (read_off fd buf off len)
615    safe_read    = do_read (safe_read_off fd buf off len)
616
617 writeRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
618 writeRawBuffer loc fd is_nonblock buf off len
619   | is_nonblock = unsafe_write -- unsafe is ok, it can't block
620   | otherwise   = do r <- unsafe_fdReady (fromIntegral fd) 1 0 0
621                      if r /= 0 
622                         then write
623                         else do threadWaitWrite (fromIntegral fd); write
624   where  
625     do_write call = throwErrnoIfMinus1RetryMayBlock loc call
626                         (threadWaitWrite (fromIntegral fd)) 
627     write        = if threaded then safe_write else unsafe_write
628     unsafe_write = do_write (write_rawBuffer fd buf off len)
629     safe_write   = do_write (safe_write_rawBuffer (fromIntegral fd) buf off len)
630
631 writeRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
632 writeRawBufferPtr loc fd is_nonblock buf off len
633   | is_nonblock = unsafe_write -- unsafe is ok, it can't block
634   | otherwise   = do r <- unsafe_fdReady (fromIntegral fd) 1 0 0
635                      if r /= 0 
636                         then write
637                         else do threadWaitWrite (fromIntegral fd); write
638   where
639     do_write call = throwErrnoIfMinus1RetryMayBlock loc call
640                         (threadWaitWrite (fromIntegral fd)) 
641     write         = if threaded then safe_write else unsafe_write
642     unsafe_write  = do_write (write_off fd buf off len)
643     safe_write    = do_write (safe_write_off (fromIntegral fd) buf off len)
644
645 foreign import ccall unsafe "__hscore_PrelHandle_read"
646    read_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
647
648 foreign import ccall unsafe "__hscore_PrelHandle_read"
649    read_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
650
651 foreign import ccall unsafe "__hscore_PrelHandle_write"
652    write_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
653
654 foreign import ccall unsafe "__hscore_PrelHandle_write"
655    write_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
656
657 foreign import ccall unsafe "fdReady"
658   unsafe_fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
659
660 #else /* mingw32_HOST_OS.... */
661
662 readRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
663 readRawBuffer loc fd is_stream buf off len
664   | threaded  = blockingReadRawBuffer loc fd is_stream buf off len
665   | otherwise = asyncReadRawBuffer loc fd is_stream buf off len
666
667 readRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
668 readRawBufferPtr loc fd is_stream buf off len
669   | threaded  = blockingReadRawBufferPtr loc fd is_stream buf off len
670   | otherwise = asyncReadRawBufferPtr loc fd is_stream buf off len
671
672 writeRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
673 writeRawBuffer loc fd is_stream buf off len
674   | threaded =  blockingWriteRawBuffer loc fd is_stream buf off len
675   | otherwise = asyncWriteRawBuffer    loc fd is_stream buf off len
676
677 writeRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
678 writeRawBufferPtr loc fd is_stream buf off len
679   | threaded  = blockingWriteRawBufferPtr loc fd is_stream buf off len
680   | otherwise = asyncWriteRawBufferPtr    loc fd is_stream buf off len
681
682 -- ToDo: we don't have a non-blocking primitve read on Win32
683 readRawBufferNoBlock :: String -> FD -> Bool -> RawBuffer -> Int -> CInt -> IO CInt
684 readRawBufferNoBlock = readRawBuffer
685
686 readRawBufferPtrNoBlock :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt -> IO CInt
687 readRawBufferPtrNoBlock = readRawBufferPtr
688 -- Async versions of the read/write primitives, for the non-threaded RTS
689
690 asyncReadRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt
691                    -> IO CInt
692 asyncReadRawBuffer loc fd is_stream buf off len = do
693     (l, rc) <- asyncReadBA (fromIntegral fd) (if is_stream then 1 else 0) 
694                  (fromIntegral len) off buf
695     if l == (-1)
696       then 
697         ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
698       else return (fromIntegral l)
699
700 asyncReadRawBufferPtr :: String -> FD -> Bool -> Ptr CChar -> Int -> CInt
701                       -> IO CInt
702 asyncReadRawBufferPtr loc fd is_stream buf off len = do
703     (l, rc) <- asyncRead (fromIntegral fd) (if is_stream then 1 else 0) 
704                         (fromIntegral len) (buf `plusPtr` off)
705     if l == (-1)
706       then 
707         ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
708       else return (fromIntegral l)
709
710 asyncWriteRawBuffer :: String -> FD -> Bool -> RawBuffer -> Int -> CInt
711                     -> IO CInt
712 asyncWriteRawBuffer loc fd is_stream buf off len = do
713     (l, rc) <- asyncWriteBA (fromIntegral fd) (if is_stream then 1 else 0) 
714                         (fromIntegral len) off buf
715     if l == (-1)
716       then 
717         ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
718       else return (fromIntegral l)
719
720 asyncWriteRawBufferPtr :: String -> FD -> Bool -> CString -> Int -> CInt
721                        -> IO CInt
722 asyncWriteRawBufferPtr loc fd is_stream buf off len = do
723     (l, rc) <- asyncWrite (fromIntegral fd) (if is_stream then 1 else 0) 
724                   (fromIntegral len) (buf `plusPtr` off)
725     if l == (-1)
726       then 
727         ioError (errnoToIOError loc (Errno (fromIntegral rc)) Nothing Nothing)
728       else return (fromIntegral l)
729
730 -- Blocking versions of the read/write primitives, for the threaded RTS
731
732 blockingReadRawBuffer :: String -> CInt -> Bool -> RawBuffer -> Int -> CInt
733                       -> IO CInt
734 blockingReadRawBuffer loc fd True buf off len = 
735   throwErrnoIfMinus1Retry loc $
736     safe_recv_rawBuffer fd buf off len
737 blockingReadRawBuffer loc fd False buf off len = 
738   throwErrnoIfMinus1Retry loc $
739     safe_read_rawBuffer fd buf off len
740
741 blockingReadRawBufferPtr :: String -> CInt -> Bool -> CString -> Int -> CInt
742                          -> IO CInt
743 blockingReadRawBufferPtr loc fd True buf off len = 
744   throwErrnoIfMinus1Retry loc $
745     safe_recv_off fd buf off len
746 blockingReadRawBufferPtr loc fd False buf off len = 
747   throwErrnoIfMinus1Retry loc $
748     safe_read_off fd buf off len
749
750 blockingWriteRawBuffer :: String -> CInt -> Bool -> RawBuffer -> Int -> CInt
751                        -> IO CInt
752 blockingWriteRawBuffer loc fd True buf off len = 
753   throwErrnoIfMinus1Retry loc $
754     safe_send_rawBuffer fd buf off len
755 blockingWriteRawBuffer loc fd False buf off len = 
756   throwErrnoIfMinus1Retry loc $
757     safe_write_rawBuffer fd buf off len
758
759 blockingWriteRawBufferPtr :: String -> CInt -> Bool -> CString -> Int -> CInt
760                           -> IO CInt
761 blockingWriteRawBufferPtr loc fd True buf off len = 
762   throwErrnoIfMinus1Retry loc $
763     safe_send_off fd buf off len
764 blockingWriteRawBufferPtr loc fd False buf off len = 
765   throwErrnoIfMinus1Retry loc $
766     safe_write_off fd buf off len
767
768 -- NOTE: "safe" versions of the read/write calls for use by the threaded RTS.
769 -- These calls may block, but that's ok.
770
771 foreign import ccall safe "__hscore_PrelHandle_recv"
772    safe_recv_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
773
774 foreign import ccall safe "__hscore_PrelHandle_recv"
775    safe_recv_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
776
777 foreign import ccall safe "__hscore_PrelHandle_send"
778    safe_send_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
779
780 foreign import ccall safe "__hscore_PrelHandle_send"
781    safe_send_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
782
783 #endif
784
785 foreign import ccall "rtsSupportsBoundThreads" threaded :: Bool
786
787 foreign import ccall safe "__hscore_PrelHandle_read"
788    safe_read_rawBuffer :: FD -> RawBuffer -> Int -> CInt -> IO CInt
789
790 foreign import ccall safe "__hscore_PrelHandle_read"
791    safe_read_off :: FD -> Ptr CChar -> Int -> CInt -> IO CInt
792
793 foreign import ccall safe "__hscore_PrelHandle_write"
794    safe_write_rawBuffer :: CInt -> RawBuffer -> Int -> CInt -> IO CInt
795
796 foreign import ccall safe "__hscore_PrelHandle_write"
797    safe_write_off :: CInt -> Ptr CChar -> Int -> CInt -> IO CInt
798
799 -- ---------------------------------------------------------------------------
800 -- Standard Handles
801
802 -- Three handles are allocated during program initialisation.  The first
803 -- two manage input or output from the Haskell program's standard input
804 -- or output channel respectively.  The third manages output to the
805 -- standard error channel. These handles are initially open.
806
807 fd_stdin, fd_stdout, fd_stderr :: FD
808 fd_stdin  = 0
809 fd_stdout = 1
810 fd_stderr = 2
811
812 -- | A handle managing input from the Haskell program's standard input channel.
813 stdin :: Handle
814 stdin = unsafePerformIO $ do
815    -- ToDo: acquire lock
816    -- We don't set non-blocking mode on standard handles, because it may
817    -- confuse other applications attached to the same TTY/pipe
818    -- see Note [nonblock]
819    (buf, bmode) <- getBuffer fd_stdin ReadBuffer
820    mkStdHandle fd_stdin "<stdin>" ReadHandle buf bmode
821
822 -- | A handle managing output to the Haskell program's standard output channel.
823 stdout :: Handle
824 stdout = unsafePerformIO $ do
825    -- ToDo: acquire lock
826    -- We don't set non-blocking mode on standard handles, because it may
827    -- confuse other applications attached to the same TTY/pipe
828    -- see Note [nonblock]
829    (buf, bmode) <- getBuffer fd_stdout WriteBuffer
830    mkStdHandle fd_stdout "<stdout>" WriteHandle buf bmode
831
832 -- | A handle managing output to the Haskell program's standard error channel.
833 stderr :: Handle
834 stderr = unsafePerformIO $ do
835     -- ToDo: acquire lock
836    -- We don't set non-blocking mode on standard handles, because it may
837    -- confuse other applications attached to the same TTY/pipe
838    -- see Note [nonblock]
839    buf <- mkUnBuffer
840    mkStdHandle fd_stderr "<stderr>" WriteHandle buf NoBuffering
841
842 -- ---------------------------------------------------------------------------
843 -- Opening and Closing Files
844
845 addFilePathToIOError :: String -> FilePath -> IOException -> IOException
846 addFilePathToIOError fun fp ioe
847   = ioe{ ioe_location = fun, ioe_filename = Just fp }
848
849 -- | Computation 'openFile' @file mode@ allocates and returns a new, open
850 -- handle to manage the file @file@.  It manages input if @mode@
851 -- is 'ReadMode', output if @mode@ is 'WriteMode' or 'AppendMode',
852 -- and both input and output if mode is 'ReadWriteMode'.
853 --
854 -- If the file does not exist and it is opened for output, it should be
855 -- created as a new file.  If @mode@ is 'WriteMode' and the file
856 -- already exists, then it should be truncated to zero length.
857 -- Some operating systems delete empty files, so there is no guarantee
858 -- that the file will exist following an 'openFile' with @mode@
859 -- 'WriteMode' unless it is subsequently written to successfully.
860 -- The handle is positioned at the end of the file if @mode@ is
861 -- 'AppendMode', and otherwise at the beginning (in which case its
862 -- internal position is 0).
863 -- The initial buffer mode is implementation-dependent.
864 --
865 -- This operation may fail with:
866 --
867 --  * 'isAlreadyInUseError' if the file is already open and cannot be reopened;
868 --
869 --  * 'isDoesNotExistError' if the file does not exist; or
870 --
871 --  * 'isPermissionError' if the user does not have permission to open the file.
872 --
873 -- Note: if you will be working with files containing binary data, you'll want to
874 -- be using 'openBinaryFile'.
875 openFile :: FilePath -> IOMode -> IO Handle
876 openFile fp im = 
877   catch 
878     (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE)
879     (\e -> ioError (addFilePathToIOError "openFile" fp e))
880
881 -- | Like 'openFile', but open the file in binary mode.
882 -- On Windows, reading a file in text mode (which is the default)
883 -- will translate CRLF to LF, and writing will translate LF to CRLF.
884 -- This is usually what you want with text files.  With binary files
885 -- this is undesirable; also, as usual under Microsoft operating systems,
886 -- text mode treats control-Z as EOF.  Binary mode turns off all special
887 -- treatment of end-of-line and end-of-file characters.
888 -- (See also 'hSetBinaryMode'.)
889
890 openBinaryFile :: FilePath -> IOMode -> IO Handle
891 openBinaryFile fp m =
892   catch
893     (openFile' fp m True)
894     (\e -> ioError (addFilePathToIOError "openBinaryFile" fp e))
895
896 openFile' :: String -> IOMode -> Bool -> IO Handle
897 openFile' filepath mode binary =
898   withCString filepath $ \ f ->
899
900     let 
901       oflags1 = case mode of
902                   ReadMode      -> read_flags
903 #ifdef mingw32_HOST_OS
904                   WriteMode     -> write_flags .|. o_TRUNC
905 #else
906                   WriteMode     -> write_flags
907 #endif
908                   ReadWriteMode -> rw_flags
909                   AppendMode    -> append_flags
910
911       binary_flags
912           | binary    = o_BINARY
913           | otherwise = 0
914
915       oflags = oflags1 .|. binary_flags
916     in do
917
918     -- the old implementation had a complicated series of three opens,
919     -- which is perhaps because we have to be careful not to open
920     -- directories.  However, the man pages I've read say that open()
921     -- always returns EISDIR if the file is a directory and was opened
922     -- for writing, so I think we're ok with a single open() here...
923     fd <- throwErrnoIfMinus1Retry "openFile"
924                 (c_open f (fromIntegral oflags) 0o666)
925
926     stat@(fd_type,_,_) <- fdStat fd
927
928     h <- fdToHandle_stat fd (Just stat) False filepath mode binary
929             `catchAny` \e -> do c_close fd; throw e
930         -- NB. don't forget to close the FD if fdToHandle' fails, otherwise
931         -- this FD leaks.
932         -- ASSERT: if we just created the file, then fdToHandle' won't fail
933         -- (so we don't need to worry about removing the newly created file
934         --  in the event of an error).
935
936 #ifndef mingw32_HOST_OS
937         -- we want to truncate() if this is an open in WriteMode, but only
938         -- if the target is a RegularFile.  ftruncate() fails on special files
939         -- like /dev/null.
940     if mode == WriteMode && fd_type == RegularFile
941       then throwErrnoIf (/=0) "openFile" 
942               (c_ftruncate fd 0)
943       else return 0
944 #endif
945     return h
946
947
948 std_flags, output_flags, read_flags, write_flags, rw_flags,
949     append_flags :: CInt
950 std_flags    = o_NONBLOCK   .|. o_NOCTTY
951 output_flags = std_flags    .|. o_CREAT
952 read_flags   = std_flags    .|. o_RDONLY 
953 write_flags  = output_flags .|. o_WRONLY
954 rw_flags     = output_flags .|. o_RDWR
955 append_flags = write_flags  .|. o_APPEND
956
957 -- ---------------------------------------------------------------------------
958 -- fdToHandle
959
960 fdToHandle_stat :: FD
961             -> Maybe (FDType, CDev, CIno)
962             -> Bool
963             -> FilePath
964             -> IOMode
965             -> Bool
966             -> IO Handle
967
968 fdToHandle_stat fd mb_stat is_socket filepath mode binary = do
969
970 #ifdef mingw32_HOST_OS
971     -- On Windows, the is_socket flag indicates that the Handle is a socket
972 #else
973     -- On Unix, the is_socket flag indicates that the FD can be made non-blocking
974     let non_blocking = is_socket
975
976     when non_blocking $ setNonBlockingFD fd
977     -- turn on non-blocking mode
978 #endif
979
980     let (ha_type, write) =
981           case mode of
982             ReadMode      -> ( ReadHandle,      False )
983             WriteMode     -> ( WriteHandle,     True )
984             ReadWriteMode -> ( ReadWriteHandle, True )
985             AppendMode    -> ( AppendHandle,    True )
986
987     -- open() won't tell us if it was a directory if we only opened for
988     -- reading, so check again.
989     (fd_type,dev,ino) <- 
990       case mb_stat of
991         Just x  -> return x
992         Nothing -> fdStat fd
993
994     case fd_type of
995         Directory -> 
996            ioException (IOError Nothing InappropriateType "openFile"
997                            "is a directory" Nothing Nothing) 
998
999         -- regular files need to be locked
1000         RegularFile -> do
1001 #ifndef mingw32_HOST_OS
1002            -- On Windows we use explicit exclusion via sopen() to implement
1003            -- this locking (see __hscore_open()); on Unix we have to
1004            -- implment it in the RTS.
1005            r <- lockFile fd dev ino (fromBool write)
1006            when (r == -1)  $
1007                 ioException (IOError Nothing ResourceBusy "openFile"
1008                                    "file is locked" Nothing Nothing)
1009 #endif
1010            mkFileHandle fd is_socket filepath ha_type binary
1011
1012         Stream
1013            -- only *Streams* can be DuplexHandles.  Other read/write
1014            -- Handles must share a buffer.
1015            | ReadWriteHandle <- ha_type -> 
1016                 mkDuplexHandle fd is_socket filepath binary
1017            | otherwise ->
1018                 mkFileHandle   fd is_socket filepath ha_type binary
1019
1020         RawDevice -> 
1021                 mkFileHandle fd is_socket filepath ha_type binary
1022
1023 -- | Old API kept to avoid breaking clients
1024 fdToHandle' :: FD -> Maybe FDType -> Bool -> FilePath  -> IOMode -> Bool
1025             -> IO Handle
1026 fdToHandle' fd mb_type is_socket filepath mode binary
1027  = do
1028        let mb_stat = case mb_type of
1029                         Nothing          -> Nothing
1030                           -- fdToHandle_stat will do the stat:
1031                         Just RegularFile -> Nothing
1032                           -- no stat required for streams etc.:
1033                         Just other       -> Just (other,0,0)
1034        fdToHandle_stat fd mb_stat is_socket filepath mode binary
1035
1036 fdToHandle :: FD -> IO Handle
1037 fdToHandle fd = do
1038    mode <- fdGetMode fd
1039    let fd_str = "<file descriptor: " ++ show fd ++ ">"
1040    fdToHandle_stat fd Nothing False fd_str mode True{-bin mode-}
1041         -- NB. the is_socket flag is False, meaning that:
1042         --  on Unix the file descriptor will *not* be put in non-blocking mode
1043         --  on Windows we're guessing this is not a socket (XXX)
1044
1045 #ifndef mingw32_HOST_OS
1046 foreign import ccall unsafe "lockFile"
1047   lockFile :: CInt -> CDev -> CIno -> CInt -> IO CInt
1048
1049 foreign import ccall unsafe "unlockFile"
1050   unlockFile :: CInt -> IO CInt
1051 #endif
1052
1053 mkStdHandle :: FD -> FilePath -> HandleType -> IORef Buffer -> BufferMode
1054         -> IO Handle
1055 mkStdHandle fd filepath ha_type buf bmode = do
1056    spares <- newIORef BufferListNil
1057    newFileHandle filepath (stdHandleFinalizer filepath)
1058             (Handle__ { haFD = fd,
1059                         haType = ha_type,
1060                         haIsBin = dEFAULT_OPEN_IN_BINARY_MODE,
1061                         haIsStream = False, -- means FD is blocking on Unix
1062                         haBufferMode = bmode,
1063                         haBuffer = buf,
1064                         haBuffers = spares,
1065                         haOtherSide = Nothing
1066                       })
1067
1068 mkFileHandle :: FD -> Bool -> FilePath -> HandleType -> Bool -> IO Handle
1069 mkFileHandle fd is_stream filepath ha_type binary = do
1070   (buf, bmode) <- getBuffer fd (initBufferState ha_type)
1071
1072 #ifdef mingw32_HOST_OS
1073   -- On Windows, if this is a read/write handle and we are in text mode,
1074   -- turn off buffering.  We don't correctly handle the case of switching
1075   -- from read mode to write mode on a buffered text-mode handle, see bug
1076   -- \#679.
1077   bmode2 <- case ha_type of
1078                  ReadWriteHandle | not binary -> return NoBuffering
1079                  _other                       -> return bmode
1080 #else
1081   let bmode2 = bmode
1082 #endif
1083
1084   spares <- newIORef BufferListNil
1085   newFileHandle filepath (handleFinalizer filepath)
1086             (Handle__ { haFD = fd,
1087                         haType = ha_type,
1088                         haIsBin = binary,
1089                         haIsStream = is_stream,
1090                         haBufferMode = bmode2,
1091                         haBuffer = buf,
1092                         haBuffers = spares,
1093                         haOtherSide = Nothing
1094                       })
1095
1096 mkDuplexHandle :: FD -> Bool -> FilePath -> Bool -> IO Handle
1097 mkDuplexHandle fd is_stream filepath binary = do
1098   (w_buf, w_bmode) <- getBuffer fd WriteBuffer
1099   w_spares <- newIORef BufferListNil
1100   let w_handle_ = 
1101              Handle__ { haFD = fd,
1102                         haType = WriteHandle,
1103                         haIsBin = binary,
1104                         haIsStream = is_stream,
1105                         haBufferMode = w_bmode,
1106                         haBuffer = w_buf,
1107                         haBuffers = w_spares,
1108                         haOtherSide = Nothing
1109                       }
1110   write_side <- newMVar w_handle_
1111
1112   (r_buf, r_bmode) <- getBuffer fd ReadBuffer
1113   r_spares <- newIORef BufferListNil
1114   let r_handle_ = 
1115              Handle__ { haFD = fd,
1116                         haType = ReadHandle,
1117                         haIsBin = binary,
1118                         haIsStream = is_stream,
1119                         haBufferMode = r_bmode,
1120                         haBuffer = r_buf,
1121                         haBuffers = r_spares,
1122                         haOtherSide = Just write_side
1123                       }
1124   read_side <- newMVar r_handle_
1125
1126   addMVarFinalizer write_side (handleFinalizer filepath write_side)
1127   return (DuplexHandle filepath read_side write_side)
1128    
1129 initBufferState :: HandleType -> BufferState
1130 initBufferState ReadHandle = ReadBuffer
1131 initBufferState _          = WriteBuffer
1132
1133 -- ---------------------------------------------------------------------------
1134 -- Closing a handle
1135
1136 -- | Computation 'hClose' @hdl@ makes handle @hdl@ closed.  Before the
1137 -- computation finishes, if @hdl@ is writable its buffer is flushed as
1138 -- for 'hFlush'.
1139 -- Performing 'hClose' on a handle that has already been closed has no effect; 
1140 -- doing so is not an error.  All other operations on a closed handle will fail.
1141 -- If 'hClose' fails for any reason, any further operations (apart from
1142 -- 'hClose') on the handle will still fail as if @hdl@ had been successfully
1143 -- closed.
1144
1145 hClose :: Handle -> IO ()
1146 hClose h@(FileHandle _ m)     = do 
1147   mb_exc <- hClose' h m
1148   case mb_exc of
1149     Nothing -> return ()
1150     Just e  -> throwIO e
1151 hClose h@(DuplexHandle _ r w) = do
1152   mb_exc1 <- hClose' h w
1153   mb_exc2 <- hClose' h r
1154   case (do mb_exc1; mb_exc2) of
1155      Nothing -> return ()
1156      Just e  -> throwIO e
1157
1158 hClose' :: Handle -> MVar Handle__ -> IO (Maybe SomeException)
1159 hClose' h m = withHandle' "hClose" h m $ hClose_help
1160
1161 -- hClose_help is also called by lazyRead (in PrelIO) when EOF is read
1162 -- or an IO error occurs on a lazy stream.  The semi-closed Handle is
1163 -- then closed immediately.  We have to be careful with DuplexHandles
1164 -- though: we have to leave the closing to the finalizer in that case,
1165 -- because the write side may still be in use.
1166 hClose_help :: Handle__ -> IO (Handle__, Maybe SomeException)
1167 hClose_help handle_ =
1168   case haType handle_ of 
1169       ClosedHandle -> return (handle_,Nothing)
1170       _ -> do flushWriteBufferOnly handle_ -- interruptible
1171               hClose_handle_ handle_
1172
1173 hClose_handle_ :: Handle__ -> IO (Handle__, Maybe SomeException)
1174 hClose_handle_ handle_ = do
1175     let fd = haFD handle_
1176
1177     -- close the file descriptor, but not when this is the read
1178     -- side of a duplex handle.
1179     -- If an exception is raised by the close(), we want to continue
1180     -- to close the handle and release the lock if it has one, then 
1181     -- we return the exception to the caller of hClose_help which can
1182     -- raise it if necessary.
1183     maybe_exception <- 
1184       case haOtherSide handle_ of
1185         Nothing -> (do
1186                       throwErrnoIfMinus1Retry_ "hClose" 
1187 #ifdef mingw32_HOST_OS
1188                                 (closeFd (haIsStream handle_) fd)
1189 #else
1190                                 (c_close fd)
1191 #endif
1192                       return Nothing
1193                     )
1194                      `catchException` \e -> return (Just e)
1195
1196         Just _  -> return Nothing
1197
1198     -- free the spare buffers
1199     writeIORef (haBuffers handle_) BufferListNil
1200     writeIORef (haBuffer  handle_) noBuffer
1201   
1202 #ifndef mingw32_HOST_OS
1203     -- unlock it
1204     unlockFile fd
1205 #endif
1206
1207     -- we must set the fd to -1, because the finalizer is going
1208     -- to run eventually and try to close/unlock it.
1209     return (handle_{ haFD        = -1, 
1210                      haType      = ClosedHandle
1211                    },
1212             maybe_exception)
1213
1214 {-# NOINLINE noBuffer #-}
1215 noBuffer :: Buffer
1216 noBuffer = unsafePerformIO $ allocateBuffer 1 ReadBuffer
1217
1218 -----------------------------------------------------------------------------
1219 -- Detecting and changing the size of a file
1220
1221 -- | For a handle @hdl@ which attached to a physical file,
1222 -- 'hFileSize' @hdl@ returns the size of that file in 8-bit bytes.
1223
1224 hFileSize :: Handle -> IO Integer
1225 hFileSize handle =
1226     withHandle_ "hFileSize" handle $ \ handle_ -> do
1227     case haType handle_ of 
1228       ClosedHandle              -> ioe_closedHandle
1229       SemiClosedHandle          -> ioe_closedHandle
1230       _ -> do flushWriteBufferOnly handle_
1231               r <- fdFileSize (haFD handle_)
1232               if r /= -1
1233                  then return r
1234                  else ioException (IOError Nothing InappropriateType "hFileSize"
1235                                    "not a regular file" Nothing Nothing)
1236
1237
1238 -- | 'hSetFileSize' @hdl@ @size@ truncates the physical file with handle @hdl@ to @size@ bytes.
1239
1240 hSetFileSize :: Handle -> Integer -> IO ()
1241 hSetFileSize handle size =
1242     withHandle_ "hSetFileSize" handle $ \ handle_ -> do
1243     case haType handle_ of 
1244       ClosedHandle              -> ioe_closedHandle
1245       SemiClosedHandle          -> ioe_closedHandle
1246       _ -> do flushWriteBufferOnly handle_
1247               throwErrnoIf (/=0) "hSetFileSize" 
1248                  (c_ftruncate (haFD handle_) (fromIntegral size))
1249               return ()
1250
1251 -- ---------------------------------------------------------------------------
1252 -- Detecting the End of Input
1253
1254 -- | For a readable handle @hdl@, 'hIsEOF' @hdl@ returns
1255 -- 'True' if no further input can be taken from @hdl@ or for a
1256 -- physical file, if the current I\/O position is equal to the length of
1257 -- the file.  Otherwise, it returns 'False'.
1258 --
1259 -- NOTE: 'hIsEOF' may block, because it is the same as calling
1260 -- 'hLookAhead' and checking for an EOF exception.
1261
1262 hIsEOF :: Handle -> IO Bool
1263 hIsEOF handle =
1264   catch
1265      (do hLookAhead handle; return False)
1266      (\e -> if isEOFError e then return True else ioError e)
1267
1268 -- | The computation 'isEOF' is identical to 'hIsEOF',
1269 -- except that it works only on 'stdin'.
1270
1271 isEOF :: IO Bool
1272 isEOF = hIsEOF stdin
1273
1274 -- ---------------------------------------------------------------------------
1275 -- Looking ahead
1276
1277 -- | Computation 'hLookAhead' returns the next character from the handle
1278 -- without removing it from the input buffer, blocking until a character
1279 -- is available.
1280 --
1281 -- This operation may fail with:
1282 --
1283 --  * 'isEOFError' if the end of file has been reached.
1284
1285 hLookAhead :: Handle -> IO Char
1286 hLookAhead handle =
1287   wantReadableHandle "hLookAhead"  handle hLookAhead'
1288
1289 hLookAhead' :: Handle__ -> IO Char
1290 hLookAhead' handle_ = do
1291   let ref     = haBuffer handle_
1292       fd      = haFD handle_
1293   buf <- readIORef ref
1294
1295   -- fill up the read buffer if necessary
1296   new_buf <- if bufferEmpty buf
1297                 then fillReadBuffer fd True (haIsStream handle_) buf
1298                 else return buf
1299
1300   writeIORef ref new_buf
1301
1302   (c,_) <- readCharFromBuffer (bufBuf buf) (bufRPtr buf)
1303   return c
1304
1305 -- ---------------------------------------------------------------------------
1306 -- Buffering Operations
1307
1308 -- Three kinds of buffering are supported: line-buffering,
1309 -- block-buffering or no-buffering.  See GHC.IOBase for definition and
1310 -- further explanation of what the type represent.
1311
1312 -- | Computation 'hSetBuffering' @hdl mode@ sets the mode of buffering for
1313 -- handle @hdl@ on subsequent reads and writes.
1314 --
1315 -- If the buffer mode is changed from 'BlockBuffering' or
1316 -- 'LineBuffering' to 'NoBuffering', then
1317 --
1318 --  * if @hdl@ is writable, the buffer is flushed as for 'hFlush';
1319 --
1320 --  * if @hdl@ is not writable, the contents of the buffer is discarded.
1321 --
1322 -- This operation may fail with:
1323 --
1324 --  * 'isPermissionError' if the handle has already been used for reading
1325 --    or writing and the implementation does not allow the buffering mode
1326 --    to be changed.
1327
1328 hSetBuffering :: Handle -> BufferMode -> IO ()
1329 hSetBuffering handle mode =
1330   withAllHandles__ "hSetBuffering" handle $ \ handle_ -> do
1331   case haType handle_ of
1332     ClosedHandle -> ioe_closedHandle
1333     _ -> do
1334          {- Note:
1335             - we flush the old buffer regardless of whether
1336               the new buffer could fit the contents of the old buffer 
1337               or not.
1338             - allow a handle's buffering to change even if IO has
1339               occurred (ANSI C spec. does not allow this, nor did
1340               the previous implementation of IO.hSetBuffering).
1341             - a non-standard extension is to allow the buffering
1342               of semi-closed handles to change [sof 6/98]
1343           -}
1344           flushBuffer handle_
1345
1346           let state = initBufferState (haType handle_)
1347           new_buf <-
1348             case mode of
1349                 -- we always have a 1-character read buffer for 
1350                 -- unbuffered  handles: it's needed to 
1351                 -- support hLookAhead.
1352               NoBuffering            -> allocateBuffer 1 ReadBuffer
1353               LineBuffering          -> allocateBuffer dEFAULT_BUFFER_SIZE state
1354               BlockBuffering Nothing -> allocateBuffer dEFAULT_BUFFER_SIZE state
1355               BlockBuffering (Just n) | n <= 0    -> ioe_bufsiz n
1356                                       | otherwise -> allocateBuffer n state
1357           writeIORef (haBuffer handle_) new_buf
1358
1359           -- for input terminals we need to put the terminal into
1360           -- cooked or raw mode depending on the type of buffering.
1361           is_tty <- fdIsTTY (haFD handle_)
1362           when (is_tty && isReadableHandleType (haType handle_)) $
1363                 case mode of
1364 #ifndef mingw32_HOST_OS
1365         -- 'raw' mode under win32 is a bit too specialised (and troublesome
1366         -- for most common uses), so simply disable its use here.
1367                   NoBuffering -> setCooked (haFD handle_) False
1368 #else
1369                   NoBuffering -> return ()
1370 #endif
1371                   _           -> setCooked (haFD handle_) True
1372
1373           -- throw away spare buffers, they might be the wrong size
1374           writeIORef (haBuffers handle_) BufferListNil
1375
1376           return (handle_{ haBufferMode = mode })
1377
1378 -- -----------------------------------------------------------------------------
1379 -- hFlush
1380
1381 -- | The action 'hFlush' @hdl@ causes any items buffered for output
1382 -- in handle @hdl@ to be sent immediately to the operating system.
1383 --
1384 -- This operation may fail with:
1385 --
1386 --  * 'isFullError' if the device is full;
1387 --
1388 --  * 'isPermissionError' if a system resource limit would be exceeded.
1389 --    It is unspecified whether the characters in the buffer are discarded
1390 --    or retained under these circumstances.
1391
1392 hFlush :: Handle -> IO () 
1393 hFlush handle =
1394    wantWritableHandle "hFlush" handle $ \ handle_ -> do
1395    buf <- readIORef (haBuffer handle_)
1396    if bufferIsWritable buf && not (bufferEmpty buf)
1397         then do flushed_buf <- flushWriteBuffer (haFD handle_) (haIsStream handle_) buf
1398                 writeIORef (haBuffer handle_) flushed_buf
1399         else return ()
1400
1401
1402 -- -----------------------------------------------------------------------------
1403 -- Repositioning Handles
1404
1405 data HandlePosn = HandlePosn Handle HandlePosition
1406
1407 instance Eq HandlePosn where
1408     (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
1409
1410 instance Show HandlePosn where
1411    showsPrec p (HandlePosn h pos) = 
1412         showsPrec p h . showString " at position " . shows pos
1413
1414   -- HandlePosition is the Haskell equivalent of POSIX' off_t.
1415   -- We represent it as an Integer on the Haskell side, but
1416   -- cheat slightly in that hGetPosn calls upon a C helper
1417   -- that reports the position back via (merely) an Int.
1418 type HandlePosition = Integer
1419
1420 -- | Computation 'hGetPosn' @hdl@ returns the current I\/O position of
1421 -- @hdl@ as a value of the abstract type 'HandlePosn'.
1422
1423 hGetPosn :: Handle -> IO HandlePosn
1424 hGetPosn handle = do
1425     posn <- hTell handle
1426     return (HandlePosn handle posn)
1427
1428 -- | If a call to 'hGetPosn' @hdl@ returns a position @p@,
1429 -- then computation 'hSetPosn' @p@ sets the position of @hdl@
1430 -- to the position it held at the time of the call to 'hGetPosn'.
1431 --
1432 -- This operation may fail with:
1433 --
1434 --  * 'isPermissionError' if a system resource limit would be exceeded.
1435
1436 hSetPosn :: HandlePosn -> IO () 
1437 hSetPosn (HandlePosn h i) = hSeek h AbsoluteSeek i
1438
1439 -- ---------------------------------------------------------------------------
1440 -- hSeek
1441
1442 -- | A mode that determines the effect of 'hSeek' @hdl mode i@, as follows:
1443 data SeekMode
1444   = AbsoluteSeek        -- ^ the position of @hdl@ is set to @i@.
1445   | RelativeSeek        -- ^ the position of @hdl@ is set to offset @i@
1446                         -- from the current position.
1447   | SeekFromEnd         -- ^ the position of @hdl@ is set to offset @i@
1448                         -- from the end of the file.
1449     deriving (Eq, Ord, Ix, Enum, Read, Show)
1450
1451 {- Note: 
1452  - when seeking using `SeekFromEnd', positive offsets (>=0) means
1453    seeking at or past EOF.
1454
1455  - we possibly deviate from the report on the issue of seeking within
1456    the buffer and whether to flush it or not.  The report isn't exactly
1457    clear here.
1458 -}
1459
1460 -- | Computation 'hSeek' @hdl mode i@ sets the position of handle
1461 -- @hdl@ depending on @mode@.
1462 -- The offset @i@ is given in terms of 8-bit bytes.
1463 --
1464 -- If @hdl@ is block- or line-buffered, then seeking to a position which is not
1465 -- in the current buffer will first cause any items in the output buffer to be
1466 -- written to the device, and then cause the input buffer to be discarded.
1467 -- Some handles may not be seekable (see 'hIsSeekable'), or only support a
1468 -- subset of the possible positioning operations (for instance, it may only
1469 -- be possible to seek to the end of a tape, or to a positive offset from
1470 -- the beginning or current position).
1471 -- It is not possible to set a negative I\/O position, or for
1472 -- a physical file, an I\/O position beyond the current end-of-file.
1473 --
1474 -- This operation may fail with:
1475 --
1476 --  * 'isPermissionError' if a system resource limit would be exceeded.
1477
1478 hSeek :: Handle -> SeekMode -> Integer -> IO () 
1479 hSeek handle mode offset =
1480     wantSeekableHandle "hSeek" handle $ \ handle_ -> do
1481 #   ifdef DEBUG_DUMP
1482     puts ("hSeek " ++ show (mode,offset) ++ "\n")
1483 #   endif
1484     let ref = haBuffer handle_
1485     buf <- readIORef ref
1486     let r = bufRPtr buf
1487         w = bufWPtr buf
1488         fd = haFD handle_
1489
1490     let do_seek =
1491           throwErrnoIfMinus1Retry_ "hSeek"
1492             (c_lseek (haFD handle_) (fromIntegral offset) whence)
1493
1494         whence :: CInt
1495         whence = case mode of
1496                    AbsoluteSeek -> sEEK_SET
1497                    RelativeSeek -> sEEK_CUR
1498                    SeekFromEnd  -> sEEK_END
1499
1500     if bufferIsWritable buf
1501         then do new_buf <- flushWriteBuffer fd (haIsStream handle_) buf
1502                 writeIORef ref new_buf
1503                 do_seek
1504         else do
1505
1506     if mode == RelativeSeek && offset >= 0 && offset < fromIntegral (w - r)
1507         then writeIORef ref buf{ bufRPtr = r + fromIntegral offset }
1508         else do 
1509
1510     new_buf <- flushReadBuffer (haFD handle_) buf
1511     writeIORef ref new_buf
1512     do_seek
1513
1514
1515 hTell :: Handle -> IO Integer
1516 hTell handle = 
1517     wantSeekableHandle "hGetPosn" handle $ \ handle_ -> do
1518
1519 #if defined(mingw32_HOST_OS)
1520         -- urgh, on Windows we have to worry about \n -> \r\n translation, 
1521         -- so we can't easily calculate the file position using the
1522         -- current buffer size.  Just flush instead.
1523       flushBuffer handle_
1524 #endif
1525       let fd = haFD handle_
1526       posn <- fromIntegral `liftM`
1527                 throwErrnoIfMinus1Retry "hGetPosn"
1528                    (c_lseek fd 0 sEEK_CUR)
1529
1530       let ref = haBuffer handle_
1531       buf <- readIORef ref
1532
1533       let real_posn 
1534            | bufferIsWritable buf = posn + fromIntegral (bufWPtr buf)
1535            | otherwise = posn - fromIntegral (bufWPtr buf - bufRPtr buf)
1536 #     ifdef DEBUG_DUMP
1537       puts ("\nhGetPosn: (fd, posn, real_posn) = " ++ show (fd, posn, real_posn) ++ "\n")
1538       puts ("   (bufWPtr, bufRPtr) = " ++ show (bufWPtr buf, bufRPtr buf) ++ "\n")
1539 #     endif
1540       return real_posn
1541
1542 -- -----------------------------------------------------------------------------
1543 -- Handle Properties
1544
1545 -- A number of operations return information about the properties of a
1546 -- handle.  Each of these operations returns `True' if the handle has
1547 -- the specified property, and `False' otherwise.
1548
1549 hIsOpen :: Handle -> IO Bool
1550 hIsOpen handle =
1551     withHandle_ "hIsOpen" handle $ \ handle_ -> do
1552     case haType handle_ of 
1553       ClosedHandle         -> return False
1554       SemiClosedHandle     -> return False
1555       _                    -> return True
1556
1557 hIsClosed :: Handle -> IO Bool
1558 hIsClosed handle =
1559     withHandle_ "hIsClosed" handle $ \ handle_ -> do
1560     case haType handle_ of 
1561       ClosedHandle         -> return True
1562       _                    -> return False
1563
1564 {- not defined, nor exported, but mentioned
1565    here for documentation purposes:
1566
1567     hSemiClosed :: Handle -> IO Bool
1568     hSemiClosed h = do
1569        ho <- hIsOpen h
1570        hc <- hIsClosed h
1571        return (not (ho || hc))
1572 -}
1573
1574 hIsReadable :: Handle -> IO Bool
1575 hIsReadable (DuplexHandle _ _ _) = return True
1576 hIsReadable handle =
1577     withHandle_ "hIsReadable" handle $ \ handle_ -> do
1578     case haType handle_ of 
1579       ClosedHandle         -> ioe_closedHandle
1580       SemiClosedHandle     -> ioe_closedHandle
1581       htype                -> return (isReadableHandleType htype)
1582
1583 hIsWritable :: Handle -> IO Bool
1584 hIsWritable (DuplexHandle _ _ _) = return True
1585 hIsWritable handle =
1586     withHandle_ "hIsWritable" handle $ \ handle_ -> do
1587     case haType handle_ of 
1588       ClosedHandle         -> ioe_closedHandle
1589       SemiClosedHandle     -> ioe_closedHandle
1590       htype                -> return (isWritableHandleType htype)
1591
1592 -- | Computation 'hGetBuffering' @hdl@ returns the current buffering mode
1593 -- for @hdl@.
1594
1595 hGetBuffering :: Handle -> IO BufferMode
1596 hGetBuffering handle = 
1597     withHandle_ "hGetBuffering" handle $ \ handle_ -> do
1598     case haType handle_ of 
1599       ClosedHandle         -> ioe_closedHandle
1600       _ -> 
1601            -- We're being non-standard here, and allow the buffering
1602            -- of a semi-closed handle to be queried.   -- sof 6/98
1603           return (haBufferMode handle_)  -- could be stricter..
1604
1605 hIsSeekable :: Handle -> IO Bool
1606 hIsSeekable handle =
1607     withHandle_ "hIsSeekable" handle $ \ handle_ -> do
1608     case haType handle_ of 
1609       ClosedHandle         -> ioe_closedHandle
1610       SemiClosedHandle     -> ioe_closedHandle
1611       AppendHandle         -> return False
1612       _                    -> do t <- fdType (haFD handle_)
1613                                  return ((t == RegularFile    || t == RawDevice)
1614                                          && (haIsBin handle_  || tEXT_MODE_SEEK_ALLOWED))
1615
1616 -- -----------------------------------------------------------------------------
1617 -- Changing echo status (Non-standard GHC extensions)
1618
1619 -- | Set the echoing status of a handle connected to a terminal.
1620
1621 hSetEcho :: Handle -> Bool -> IO ()
1622 hSetEcho handle on = do
1623     isT   <- hIsTerminalDevice handle
1624     if not isT
1625      then return ()
1626      else
1627       withHandle_ "hSetEcho" handle $ \ handle_ -> do
1628       case haType handle_ of 
1629          ClosedHandle -> ioe_closedHandle
1630          _            -> setEcho (haFD handle_) on
1631
1632 -- | Get the echoing status of a handle connected to a terminal.
1633
1634 hGetEcho :: Handle -> IO Bool
1635 hGetEcho handle = do
1636     isT   <- hIsTerminalDevice handle
1637     if not isT
1638      then return False
1639      else
1640        withHandle_ "hGetEcho" handle $ \ handle_ -> do
1641        case haType handle_ of 
1642          ClosedHandle -> ioe_closedHandle
1643          _            -> getEcho (haFD handle_)
1644
1645 -- | Is the handle connected to a terminal?
1646
1647 hIsTerminalDevice :: Handle -> IO Bool
1648 hIsTerminalDevice handle = do
1649     withHandle_ "hIsTerminalDevice" handle $ \ handle_ -> do
1650      case haType handle_ of 
1651        ClosedHandle -> ioe_closedHandle
1652        _            -> fdIsTTY (haFD handle_)
1653
1654 -- -----------------------------------------------------------------------------
1655 -- hSetBinaryMode
1656
1657 -- | Select binary mode ('True') or text mode ('False') on a open handle.
1658 -- (See also 'openBinaryFile'.)
1659
1660 hSetBinaryMode :: Handle -> Bool -> IO ()
1661 hSetBinaryMode handle bin =
1662   withAllHandles__ "hSetBinaryMode" handle $ \ handle_ ->
1663     do throwErrnoIfMinus1_ "hSetBinaryMode"
1664           (setmode (haFD handle_) bin)
1665        return handle_{haIsBin=bin}
1666   
1667 foreign import ccall unsafe "__hscore_setmode"
1668   setmode :: CInt -> Bool -> IO CInt
1669
1670 -- -----------------------------------------------------------------------------
1671 -- Duplicating a Handle
1672
1673 -- | Returns a duplicate of the original handle, with its own buffer.
1674 -- The two Handles will share a file pointer, however.  The original
1675 -- handle's buffer is flushed, including discarding any input data,
1676 -- before the handle is duplicated.
1677
1678 hDuplicate :: Handle -> IO Handle
1679 hDuplicate h@(FileHandle path m) = do
1680   new_h_ <- withHandle' "hDuplicate" h m (dupHandle h Nothing)
1681   newFileHandle path (handleFinalizer path) new_h_
1682 hDuplicate h@(DuplexHandle path r w) = do
1683   new_w_ <- withHandle' "hDuplicate" h w (dupHandle h Nothing)
1684   new_w <- newMVar new_w_
1685   new_r_ <- withHandle' "hDuplicate" h r (dupHandle h (Just new_w))
1686   new_r <- newMVar new_r_
1687   addMVarFinalizer new_w (handleFinalizer path new_w)
1688   return (DuplexHandle path new_r new_w)
1689
1690 dupHandle :: Handle -> Maybe (MVar Handle__) -> Handle__
1691           -> IO (Handle__, Handle__)
1692 dupHandle h other_side h_ = do
1693   -- flush the buffer first, so we don't have to copy its contents
1694   flushBuffer h_
1695   new_fd <- case other_side of
1696                 Nothing -> throwErrnoIfMinus1 "dupHandle" $ c_dup (haFD h_)
1697                 Just r -> withHandle_' "dupHandle" h r (return . haFD)
1698   dupHandle_ other_side h_ new_fd
1699
1700 dupHandleTo :: Maybe (MVar Handle__) -> Handle__ -> Handle__
1701             -> IO (Handle__, Handle__)
1702 dupHandleTo other_side hto_ h_ = do
1703   flushBuffer h_
1704   -- Windows' dup2 does not return the new descriptor, unlike Unix
1705   throwErrnoIfMinus1 "dupHandleTo" $ 
1706         c_dup2 (haFD h_) (haFD hto_)
1707   dupHandle_ other_side h_ (haFD hto_)
1708
1709 dupHandle_ :: Maybe (MVar Handle__) -> Handle__ -> FD
1710            -> IO (Handle__, Handle__)
1711 dupHandle_ other_side h_ new_fd = do
1712   buffer <- allocateBuffer dEFAULT_BUFFER_SIZE (initBufferState (haType h_))
1713   ioref <- newIORef buffer
1714   ioref_buffers <- newIORef BufferListNil
1715
1716   let new_handle_ = h_{ haFD = new_fd, 
1717                         haBuffer = ioref, 
1718                         haBuffers = ioref_buffers,
1719                         haOtherSide = other_side }
1720   return (h_, new_handle_)
1721
1722 -- -----------------------------------------------------------------------------
1723 -- Replacing a Handle
1724
1725 {- |
1726 Makes the second handle a duplicate of the first handle.  The second 
1727 handle will be closed first, if it is not already.
1728
1729 This can be used to retarget the standard Handles, for example:
1730
1731 > do h <- openFile "mystdout" WriteMode
1732 >    hDuplicateTo h stdout
1733 -}
1734
1735 hDuplicateTo :: Handle -> Handle -> IO ()
1736 hDuplicateTo h1@(FileHandle _ m1) h2@(FileHandle _ m2)  = do
1737  withHandle__' "hDuplicateTo" h2 m2 $ \h2_ -> do
1738    _ <- hClose_help h2_
1739    withHandle' "hDuplicateTo" h1 m1 (dupHandleTo Nothing h2_)
1740 hDuplicateTo h1@(DuplexHandle _ r1 w1) h2@(DuplexHandle _ r2 w2)  = do
1741  withHandle__' "hDuplicateTo" h2 w2  $ \w2_ -> do
1742    _ <- hClose_help w2_
1743    withHandle' "hDuplicateTo" h1 r1 (dupHandleTo Nothing w2_)
1744  withHandle__' "hDuplicateTo" h2 r2  $ \r2_ -> do
1745    _ <- hClose_help r2_
1746    withHandle' "hDuplicateTo" h1 r1 (dupHandleTo (Just w1) r2_)
1747 hDuplicateTo h1 _ =
1748    ioException (IOError (Just h1) IllegalOperation "hDuplicateTo" 
1749                 "handles are incompatible" Nothing Nothing)
1750
1751 -- ---------------------------------------------------------------------------
1752 -- showing Handles.
1753 --
1754 -- | 'hShow' is in the 'IO' monad, and gives more comprehensive output
1755 -- than the (pure) instance of 'Show' for 'Handle'.
1756
1757 hShow :: Handle -> IO String
1758 hShow h@(FileHandle path _) = showHandle' path False h
1759 hShow h@(DuplexHandle path _ _) = showHandle' path True h
1760
1761 showHandle' :: String -> Bool -> Handle -> IO String
1762 showHandle' filepath is_duplex h = 
1763   withHandle_ "showHandle" h $ \hdl_ ->
1764     let
1765      showType | is_duplex = showString "duplex (read-write)"
1766               | otherwise = shows (haType hdl_)
1767     in
1768     return 
1769       (( showChar '{' . 
1770         showHdl (haType hdl_) 
1771             (showString "loc=" . showString filepath . showChar ',' .
1772              showString "type=" . showType . showChar ',' .
1773              showString "binary=" . shows (haIsBin hdl_) . showChar ',' .
1774              showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
1775       ) "")
1776    where
1777
1778     showHdl :: HandleType -> ShowS -> ShowS
1779     showHdl ht cont = 
1780        case ht of
1781         ClosedHandle  -> shows ht . showString "}"
1782         _ -> cont
1783
1784     showBufMode :: Buffer -> BufferMode -> ShowS
1785     showBufMode buf bmo =
1786       case bmo of
1787         NoBuffering   -> showString "none"
1788         LineBuffering -> showString "line"
1789         BlockBuffering (Just n) -> showString "block " . showParen True (shows n)
1790         BlockBuffering Nothing  -> showString "block " . showParen True (shows def)
1791       where
1792        def :: Int 
1793        def = bufSize buf
1794
1795 -- ---------------------------------------------------------------------------
1796 -- debugging
1797
1798 #if defined(DEBUG_DUMP)
1799 puts :: String -> IO ()
1800 puts s = do write_rawBuffer 1 (unsafeCoerce# (packCString# s)) 0 (fromIntegral (length s))
1801             return ()
1802 #endif
1803
1804 -- -----------------------------------------------------------------------------
1805 -- utils
1806
1807 throwErrnoIfMinus1RetryOnBlock  :: String -> IO CInt -> IO CInt -> IO CInt
1808 throwErrnoIfMinus1RetryOnBlock loc f on_block  = 
1809   do
1810     res <- f
1811     if (res :: CInt) == -1
1812       then do
1813         err <- getErrno
1814         if err == eINTR
1815           then throwErrnoIfMinus1RetryOnBlock loc f on_block
1816           else if err == eWOULDBLOCK || err == eAGAIN
1817                  then do on_block
1818                  else throwErrno loc
1819       else return res
1820
1821 -- -----------------------------------------------------------------------------
1822 -- wrappers to platform-specific constants:
1823
1824 foreign import ccall unsafe "__hscore_supportsTextMode"
1825   tEXT_MODE_SEEK_ALLOWED :: Bool
1826
1827 foreign import ccall unsafe "__hscore_bufsiz"   dEFAULT_BUFFER_SIZE :: Int
1828 foreign import ccall unsafe "__hscore_seek_cur" sEEK_CUR :: CInt
1829 foreign import ccall unsafe "__hscore_seek_set" sEEK_SET :: CInt
1830 foreign import ccall unsafe "__hscore_seek_end" sEEK_END :: CInt