1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : GHC.IO.Handle.FD
5 -- Copyright : (c) The University of Glasgow, 1994-2008
6 -- License : see libraries/base/LICENSE
8 -- Maintainer : libraries@haskell.org
9 -- Stability : internal
10 -- Portability : non-portable
12 -- Handle operations implemented by file descriptors (FDs)
14 -----------------------------------------------------------------------------
16 module GHC.IO.Handle.FD (
17 stdin, stdout, stderr,
18 openFile, openBinaryFile,
19 mkHandleFromFD, fdToHandle, fdToHandle',
28 -- import Control.Monad
29 import Foreign.C.Types
32 import GHC.IO.Encoding
33 -- import GHC.IO.Exception
34 import GHC.IO.Device as IODevice
35 import GHC.IO.Exception
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
44 -- ---------------------------------------------------------------------------
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.
52 -- | A handle managing input from the Haskell program's standard input channel.
54 stdin = unsafePerformIO $ do
56 setBinaryMode FD.stdin
57 mkHandle FD.stdin "<stdin>" ReadHandle True (Just localeEncoding)
58 nativeNewlineMode{-translate newlines-}
59 (Just stdHandleFinalizer) Nothing
61 -- | A handle managing output to the Haskell program's standard output channel.
63 stdout = unsafePerformIO $ do
65 setBinaryMode FD.stdout
66 mkHandle FD.stdout "<stdout>" WriteHandle True (Just localeEncoding)
67 nativeNewlineMode{-translate newlines-}
68 (Just stdHandleFinalizer) Nothing
70 -- | A handle managing output to the Haskell program's standard error channel.
72 stderr = unsafePerformIO $ do
74 setBinaryMode FD.stderr
75 mkHandle FD.stderr "<stderr>" WriteHandle False{-stderr is unbuffered-}
77 nativeNewlineMode{-translate newlines-}
78 (Just stdHandleFinalizer) Nothing
80 stdHandleFinalizer :: FilePath -> MVar Handle__ -> IO ()
81 stdHandleFinalizer fp m = do
84 putMVar m (ioe_finalizedHandle fp)
86 -- We have to put the FDs into binary mode on Windows to avoid the newline
87 -- translation that the CRT IO library does.
88 setBinaryMode :: FD -> IO ()
89 #ifdef mingw32_HOST_OS
90 setBinaryMode fd = do _ <- setmode (fdFD fd) True
93 setBinaryMode _ = return ()
96 #ifdef mingw32_HOST_OS
97 foreign import ccall unsafe "__hscore_setmode"
98 setmode :: CInt -> Bool -> IO CInt
101 -- ---------------------------------------------------------------------------
104 -- | The computation 'isEOF' is identical to 'hIsEOF',
105 -- except that it works only on 'stdin'.
110 -- ---------------------------------------------------------------------------
111 -- Opening and Closing Files
113 addFilePathToIOError :: String -> FilePath -> IOException -> IOException
114 addFilePathToIOError fun fp ioe
115 = ioe{ ioe_location = fun, ioe_filename = Just fp }
117 -- | Computation 'openFile' @file mode@ allocates and returns a new, open
118 -- handle to manage the file @file@. It manages input if @mode@
119 -- is 'ReadMode', output if @mode@ is 'WriteMode' or 'AppendMode',
120 -- and both input and output if mode is 'ReadWriteMode'.
122 -- If the file does not exist and it is opened for output, it should be
123 -- created as a new file. If @mode@ is 'WriteMode' and the file
124 -- already exists, then it should be truncated to zero length.
125 -- Some operating systems delete empty files, so there is no guarantee
126 -- that the file will exist following an 'openFile' with @mode@
127 -- 'WriteMode' unless it is subsequently written to successfully.
128 -- The handle is positioned at the end of the file if @mode@ is
129 -- 'AppendMode', and otherwise at the beginning (in which case its
130 -- internal position is 0).
131 -- The initial buffer mode is implementation-dependent.
133 -- This operation may fail with:
135 -- * 'isAlreadyInUseError' if the file is already open and cannot be reopened;
137 -- * 'isDoesNotExistError' if the file does not exist; or
139 -- * 'isPermissionError' if the user does not have permission to open the file.
141 -- Note: if you will be working with files containing binary data, you'll want to
142 -- be using 'openBinaryFile'.
143 openFile :: FilePath -> IOMode -> IO Handle
146 (openFile' fp im dEFAULT_OPEN_IN_BINARY_MODE)
147 (\e -> ioError (addFilePathToIOError "openFile" fp e))
149 -- | Like 'openFile', but open the file in binary mode.
150 -- On Windows, reading a file in text mode (which is the default)
151 -- will translate CRLF to LF, and writing will translate LF to CRLF.
152 -- This is usually what you want with text files. With binary files
153 -- this is undesirable; also, as usual under Microsoft operating systems,
154 -- text mode treats control-Z as EOF. Binary mode turns off all special
155 -- treatment of end-of-line and end-of-file characters.
156 -- (See also 'hSetBinaryMode'.)
158 openBinaryFile :: FilePath -> IOMode -> IO Handle
159 openBinaryFile fp m =
161 (openFile' fp m True)
162 (\e -> ioError (addFilePathToIOError "openBinaryFile" fp e))
164 openFile' :: String -> IOMode -> Bool -> IO Handle
165 openFile' filepath iomode binary = do
166 -- first open the file to get an FD
167 (fd, fd_type) <- FD.openFile filepath iomode
169 let mb_codec = if binary then Nothing else Just localeEncoding
171 -- then use it to make a Handle
172 mkHandleFromFD fd fd_type filepath iomode True{-non-blocking-} mb_codec
173 `onException` IODevice.close fd
174 -- NB. don't forget to close the FD if mkHandleFromFD fails, otherwise
176 -- ASSERT: if we just created the file, then fdToHandle' won't fail
177 -- (so we don't need to worry about removing the newly created file
178 -- in the event of an error).
181 -- ---------------------------------------------------------------------------
182 -- Converting file descriptors to Handles
187 -> FilePath -- a string describing this file descriptor (e.g. the filename)
189 -> Bool -- non_blocking (*sets* non-blocking mode on the FD)
190 -> Maybe TextEncoding
193 mkHandleFromFD fd0 fd_type filepath iomode set_non_blocking mb_codec
195 #ifndef mingw32_HOST_OS
196 -- turn on non-blocking mode
197 fd <- if set_non_blocking
198 then FD.setNonBlockingMode fd0 True
201 let _ = set_non_blocking -- warning suppression
205 let nl | isJust mb_codec = nativeNewlineMode
206 | otherwise = noNewlineTranslation
210 ioException (IOError Nothing InappropriateType "openFile"
211 "is a directory" Nothing Nothing)
214 -- only *Streams* can be DuplexHandles. Other read/write
215 -- Handles must share a buffer.
216 | ReadWriteMode <- iomode ->
217 mkDuplexHandle fd filepath mb_codec nl
221 mkFileHandle fd filepath iomode mb_codec nl
223 -- | Old API kept to avoid breaking clients
225 -> Maybe IODeviceType
226 -> Bool -- is_socket on Win, non-blocking on Unix
231 fdToHandle' fdint mb_type is_socket filepath iomode binary = do
232 let mb_stat = case mb_type of
234 -- mkFD will do the stat:
235 Just RegularFile -> Nothing
236 -- no stat required for streams etc.:
237 Just other -> Just (other,0,0)
238 (fd,fd_type) <- FD.mkFD (fromIntegral fdint) iomode mb_stat
241 mkHandleFromFD fd fd_type filepath iomode is_socket
242 (if binary then Nothing else Just localeEncoding)
245 -- | Turn an existing file descriptor into a Handle. This is used by
246 -- various external libraries to make Handles.
248 -- Makes a binary Handle. This is for historical reasons; it should
249 -- probably be a text Handle with the default encoding and newline
250 -- translation instead.
251 fdToHandle :: Posix.FD -> IO Handle
252 fdToHandle fdint = do
253 iomode <- Posix.fdGetMode (fromIntegral fdint)
254 (fd,fd_type) <- FD.mkFD (fromIntegral fdint) iomode Nothing
256 -- NB. the is_socket flag is False, meaning that:
257 -- on Windows we're guessing this is not a socket (XXX)
259 -- file descriptors that we get from external sources are
260 -- not put into non-blocking mode, becuase that would affect
261 -- other users of the file descriptor
262 let fd_str = "<file descriptor: " ++ show fd ++ ">"
263 mkHandleFromFD fd fd_type fd_str iomode False{-non-block-}
266 -- ---------------------------------------------------------------------------
267 -- Are files opened by default in text or binary mode, if the user doesn't
270 dEFAULT_OPEN_IN_BINARY_MODE :: Bool
271 dEFAULT_OPEN_IN_BINARY_MODE = False