add NOINLINE pragmas for stdin/stdout/stderr
[ghc-base.git] / GHC / IO / Handle / FD.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  GHC.IO.Handle.FD
5 -- Copyright   :  (c) The University of Glasgow, 1994-2008
6 -- License     :  see libraries/base/LICENSE
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  internal
10 -- Portability :  non-portable
11 --
12 -- Handle operations implemented by file descriptors (FDs)
13 --
14 -----------------------------------------------------------------------------
15
16 module GHC.IO.Handle.FD ( 
17   stdin, stdout, stderr,
18   openFile, openBinaryFile,
19   mkHandleFromFD, fdToHandle, fdToHandle',
20   isEOF
21  ) where
22
23 import GHC.Base
24 import GHC.Num
25 import GHC.Real
26 import GHC.Show
27 import Data.Maybe
28 -- import Control.Monad
29 import Foreign.C.Types
30 import GHC.MVar
31 import GHC.IO
32 import GHC.IO.Encoding
33 -- import GHC.IO.Exception
34 import GHC.IO.Device as IODevice
35 import GHC.IO.Exception
36 import GHC.IO.IOMode
37 import GHC.IO.Handle
38 import GHC.IO.Handle.Types
39 import GHC.IO.Handle.Internals
40 import GHC.IO.FD (FD(..))
41 import qualified GHC.IO.FD as FD
42 import qualified System.Posix.Internals as Posix
43
44 -- ---------------------------------------------------------------------------
45 -- Standard Handles
46
47 -- Three handles are allocated during program initialisation.  The first
48 -- two manage input or output from the Haskell program's standard input
49 -- or output channel respectively.  The third manages output to the
50 -- standard error channel. These handles are initially open.
51
52 -- | A handle managing input from the Haskell program's standard input channel.
53 stdin :: Handle
54 {-# NOINLINE stdin #-}
55 stdin = unsafePerformIO $ do
56    -- ToDo: acquire lock
57    setBinaryMode FD.stdin
58    mkHandle FD.stdin "<stdin>" ReadHandle True (Just localeEncoding)
59                 nativeNewlineMode{-translate newlines-}
60                 (Just stdHandleFinalizer) Nothing
61
62 -- | A handle managing output to the Haskell program's standard output channel.
63 stdout :: Handle
64 {-# NOINLINE stdout #-}
65 stdout = unsafePerformIO $ do
66    -- ToDo: acquire lock
67    setBinaryMode FD.stdout
68    mkHandle FD.stdout "<stdout>" WriteHandle True (Just localeEncoding)
69                 nativeNewlineMode{-translate newlines-}
70                 (Just stdHandleFinalizer) Nothing
71
72 -- | A handle managing output to the Haskell program's standard error channel.
73 stderr :: Handle
74 {-# NOINLINE stderr #-}
75 stderr = unsafePerformIO $ do
76     -- ToDo: acquire lock
77    setBinaryMode FD.stderr
78    mkHandle FD.stderr "<stderr>" WriteHandle False{-stderr is unbuffered-} 
79                 (Just localeEncoding)
80                 nativeNewlineMode{-translate newlines-}
81                 (Just stdHandleFinalizer) Nothing
82
83 stdHandleFinalizer :: FilePath -> MVar Handle__ -> IO ()
84 stdHandleFinalizer fp m = do
85   h_ <- takeMVar m
86   flushWriteBuffer h_
87   putMVar m (ioe_finalizedHandle fp)
88
89 -- We have to put the FDs into binary mode on Windows to avoid the newline
90 -- translation that the CRT IO library does.
91 setBinaryMode :: FD -> IO ()
92 #ifdef mingw32_HOST_OS
93 setBinaryMode fd = do _ <- setmode (fdFD fd) True
94                       return ()
95 #else
96 setBinaryMode _ = return ()
97 #endif
98
99 #ifdef mingw32_HOST_OS
100 foreign import ccall unsafe "__hscore_setmode"
101   setmode :: CInt -> Bool -> IO CInt
102 #endif
103
104 -- ---------------------------------------------------------------------------
105 -- isEOF
106
107 -- | The computation 'isEOF' is identical to 'hIsEOF',
108 -- except that it works only on 'stdin'.
109
110 isEOF :: IO Bool
111 isEOF = hIsEOF stdin
112
113 -- ---------------------------------------------------------------------------
114 -- Opening and Closing Files
115
116 addFilePathToIOError :: String -> FilePath -> IOException -> IOException
117 addFilePathToIOError fun fp ioe
118   = ioe{ ioe_location = fun, ioe_filename = Just fp }
119
120 -- | Computation 'openFile' @file mode@ allocates and returns a new, open
121 -- handle to manage the file @file@.  It manages input if @mode@
122 -- is 'ReadMode', output if @mode@ is 'WriteMode' or 'AppendMode',
123 -- and both input and output if mode is 'ReadWriteMode'.
124 --
125 -- If the file does not exist and it is opened for output, it should be
126 -- created as a new file.  If @mode@ is 'WriteMode' and the file
127 -- already exists, then it should be truncated to zero length.
128 -- Some operating systems delete empty files, so there is no guarantee
129 -- that the file will exist following an 'openFile' with @mode@
130 -- 'WriteMode' unless it is subsequently written to successfully.
131 -- The handle is positioned at the end of the file if @mode@ is
132 -- 'AppendMode', and otherwise at the beginning (in which case its
133 -- internal position is 0).
134 -- The initial buffer mode is implementation-dependent.
135 --
136 -- This operation may fail with:
137 --
138 --  * 'isAlreadyInUseError' if the file is already open and cannot be reopened;
139 --
140 --  * 'isDoesNotExistError' if the file does not exist; or
141 --
142 --  * 'isPermissionError' if the user does not have permission to open the file.
143 --
144 -- Note: if you will be working with files containing binary data, you'll want to
145 -- be using 'openBinaryFile'.
146 openFile :: FilePath -> IOMode -> IO Handle
147 openFile fp im = 
148   catchException
149     (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE)
150     (\e -> ioError (addFilePathToIOError "openFile" fp e))
151
152 -- | Like 'openFile', but open the file in binary mode.
153 -- On Windows, reading a file in text mode (which is the default)
154 -- will translate CRLF to LF, and writing will translate LF to CRLF.
155 -- This is usually what you want with text files.  With binary files
156 -- this is undesirable; also, as usual under Microsoft operating systems,
157 -- text mode treats control-Z as EOF.  Binary mode turns off all special
158 -- treatment of end-of-line and end-of-file characters.
159 -- (See also 'hSetBinaryMode'.)
160
161 openBinaryFile :: FilePath -> IOMode -> IO Handle
162 openBinaryFile fp m =
163   catchException
164     (openFile' fp m True)
165     (\e -> ioError (addFilePathToIOError "openBinaryFile" fp e))
166
167 openFile' :: String -> IOMode -> Bool -> IO Handle
168 openFile' filepath iomode binary = do
169   -- first open the file to get an FD
170   (fd, fd_type) <- FD.openFile filepath iomode
171
172   let mb_codec = if binary then Nothing else Just localeEncoding
173
174   -- then use it to make a Handle
175   mkHandleFromFD fd fd_type filepath iomode True{-non-blocking-} mb_codec
176             `onException` IODevice.close fd
177         -- NB. don't forget to close the FD if mkHandleFromFD fails, otherwise
178         -- this FD leaks.
179         -- ASSERT: if we just created the file, then fdToHandle' won't fail
180         -- (so we don't need to worry about removing the newly created file
181         --  in the event of an error).
182
183
184 -- ---------------------------------------------------------------------------
185 -- Converting file descriptors to Handles
186
187 mkHandleFromFD
188    :: FD
189    -> IODeviceType
190    -> FilePath -- a string describing this file descriptor (e.g. the filename)
191    -> IOMode
192    -> Bool -- non_blocking (*sets* non-blocking mode on the FD)
193    -> Maybe TextEncoding
194    -> IO Handle
195
196 mkHandleFromFD fd0 fd_type filepath iomode set_non_blocking mb_codec
197   = do
198 #ifndef mingw32_HOST_OS
199     -- turn on non-blocking mode
200     fd <- if set_non_blocking 
201              then FD.setNonBlockingMode fd0 True
202              else return fd0
203 #else
204     let _ = set_non_blocking -- warning suppression
205     fd <- return fd0
206 #endif
207
208     let nl | isJust mb_codec = nativeNewlineMode
209            | otherwise       = noNewlineTranslation
210
211     case fd_type of
212         Directory -> 
213            ioException (IOError Nothing InappropriateType "openFile"
214                            "is a directory" Nothing Nothing)
215
216         Stream
217            -- only *Streams* can be DuplexHandles.  Other read/write
218            -- Handles must share a buffer.
219            | ReadWriteMode <- iomode -> 
220                 mkDuplexHandle fd filepath mb_codec nl
221                    
222
223         _other -> 
224            mkFileHandle fd filepath iomode mb_codec nl
225
226 -- | Old API kept to avoid breaking clients
227 fdToHandle' :: CInt
228             -> Maybe IODeviceType
229             -> Bool -- is_socket on Win, non-blocking on Unix
230             -> FilePath
231             -> IOMode
232             -> Bool -- binary
233             -> IO Handle
234 fdToHandle' fdint mb_type is_socket filepath iomode binary = do
235   let mb_stat = case mb_type of
236                         Nothing          -> Nothing
237                           -- mkFD will do the stat:
238                         Just RegularFile -> Nothing
239                           -- no stat required for streams etc.:
240                         Just other       -> Just (other,0,0)
241   (fd,fd_type) <- FD.mkFD (fromIntegral fdint) iomode mb_stat
242                        is_socket
243                        is_socket
244   mkHandleFromFD fd fd_type filepath iomode is_socket
245                        (if binary then Nothing else Just localeEncoding)
246
247
248 -- | Turn an existing file descriptor into a Handle.  This is used by
249 -- various external libraries to make Handles.
250 --
251 -- Makes a binary Handle.  This is for historical reasons; it should
252 -- probably be a text Handle with the default encoding and newline
253 -- translation instead.
254 fdToHandle :: Posix.FD -> IO Handle
255 fdToHandle fdint = do
256    iomode <- Posix.fdGetMode (fromIntegral fdint)
257    (fd,fd_type) <- FD.mkFD (fromIntegral fdint) iomode Nothing
258             False{-is_socket-} 
259               -- NB. the is_socket flag is False, meaning that:
260               --  on Windows we're guessing this is not a socket (XXX)
261             False{-is_nonblock-}
262               -- file descriptors that we get from external sources are
263               -- not put into non-blocking mode, becuase that would affect
264               -- other users of the file descriptor
265    let fd_str = "<file descriptor: " ++ show fd ++ ">"
266    mkHandleFromFD fd fd_type fd_str iomode False{-non-block-} 
267                   Nothing -- bin mode
268
269 -- ---------------------------------------------------------------------------
270 -- Are files opened by default in text or binary mode, if the user doesn't
271 -- specify?
272
273 dEFAULT_OPEN_IN_BINARY_MODE :: Bool
274 dEFAULT_OPEN_IN_BINARY_MODE = False