616884a9e6d3666982c06c1059cc897b32879fa2
[packages/base.git] / System / IO.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE CPP, NoImplicitPrelude #-}
3 {-# LANGUAGE ForeignFunctionInterface #-}
4
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module : System.IO
8 -- Copyright : (c) The University of Glasgow 2001
9 -- License : BSD-style (see the file libraries/base/LICENSE)
10 --
11 -- Maintainer : libraries@haskell.org
12 -- Stability : stable
13 -- Portability : portable
14 --
15 -- The standard IO library.
16 --
17 -----------------------------------------------------------------------------
18
19 module System.IO (
20 -- * The IO monad
21
22 IO,
23 fixIO,
24
25 -- * Files and handles
26
27 FilePath,
28
29 Handle, -- abstract, instance of: Eq, Show.
30
31 -- | GHC note: a 'Handle' will be automatically closed when the garbage
32 -- collector detects that it has become unreferenced by the program.
33 -- However, relying on this behaviour is not generally recommended:
34 -- the garbage collector is unpredictable. If possible, use
35 -- an explicit 'hClose' to close 'Handle's when they are no longer
36 -- required. GHC does not currently attempt to free up file
37 -- descriptors when they have run out, it is your responsibility to
38 -- ensure that this doesn't happen.
39
40 -- ** Standard handles
41
42 -- | Three handles are allocated during program initialisation,
43 -- and are initially open.
44
45 stdin, stdout, stderr,
46
47 -- * Opening and closing files
48
49 -- ** Opening files
50
51 withFile,
52 openFile,
53 IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
54
55 -- ** Closing files
56
57 hClose,
58
59 -- ** Special cases
60
61 -- | These functions are also exported by the "Prelude".
62
63 readFile,
64 writeFile,
65 appendFile,
66
67 -- ** File locking
68
69 -- $locking
70
71 -- * Operations on handles
72
73 -- ** Determining and changing the size of a file
74
75 hFileSize,
76 #ifdef __GLASGOW_HASKELL__
77 hSetFileSize,
78 #endif
79
80 -- ** Detecting the end of input
81
82 hIsEOF,
83 isEOF,
84
85 -- ** Buffering operations
86
87 BufferMode(NoBuffering,LineBuffering,BlockBuffering),
88 hSetBuffering,
89 hGetBuffering,
90 hFlush,
91
92 -- ** Repositioning handles
93
94 hGetPosn,
95 hSetPosn,
96 HandlePosn, -- abstract, instance of: Eq, Show.
97
98 hSeek,
99 SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
100 hTell,
101
102 -- ** Handle properties
103
104 hIsOpen, hIsClosed,
105 hIsReadable, hIsWritable,
106 hIsSeekable,
107
108 -- ** Terminal operations (not portable: GHC\/Hugs only)
109
110 hIsTerminalDevice,
111
112 hSetEcho,
113 hGetEcho,
114
115 -- ** Showing handle state (not portable: GHC only)
116
117 #ifdef __GLASGOW_HASKELL__
118 hShow,
119 #endif
120
121 -- * Text input and output
122
123 -- ** Text input
124
125 hWaitForInput,
126 hReady,
127 hGetChar,
128 hGetLine,
129 hLookAhead,
130 hGetContents,
131
132 -- ** Text output
133
134 hPutChar,
135 hPutStr,
136 hPutStrLn,
137 hPrint,
138
139 -- ** Special cases for standard input and output
140
141 -- | These functions are also exported by the "Prelude".
142
143 interact,
144 putChar,
145 putStr,
146 putStrLn,
147 print,
148 getChar,
149 getLine,
150 getContents,
151 readIO,
152 readLn,
153
154 -- * Binary input and output
155
156 withBinaryFile,
157 openBinaryFile,
158 hSetBinaryMode,
159 hPutBuf,
160 hGetBuf,
161 #if !defined(__HUGS__)
162 hGetBufSome,
163 hPutBufNonBlocking,
164 hGetBufNonBlocking,
165 #endif
166
167 -- * Temporary files
168
169 openTempFile,
170 openBinaryTempFile,
171 openTempFileWithDefaultPermissions,
172 openBinaryTempFileWithDefaultPermissions,
173
174 #if !defined(__HUGS__)
175 -- * Unicode encoding\/decoding
176
177 -- | A text-mode 'Handle' has an associated 'TextEncoding', which
178 -- is used to decode bytes into Unicode characters when reading,
179 -- and encode Unicode characters into bytes when writing.
180 --
181 -- The default 'TextEncoding' is the same as the default encoding
182 -- on your system, which is also available as 'localeEncoding'.
183 -- (GHC note: on Windows, we currently do not support double-byte
184 -- encodings; if the console\'s code page is unsupported, then
185 -- 'localeEncoding' will be 'latin1'.)
186 --
187 -- Encoding and decoding errors are always detected and reported,
188 -- except during lazy I/O ('hGetContents', 'getContents', and
189 -- 'readFile'), where a decoding error merely results in
190 -- termination of the character stream, as with other I/O errors.
191
192 hSetEncoding,
193 hGetEncoding,
194
195 -- ** Unicode encodings
196 TextEncoding,
197 latin1,
198 utf8, utf8_bom,
199 utf16, utf16le, utf16be,
200 utf32, utf32le, utf32be,
201 localeEncoding,
202 char8,
203 mkTextEncoding,
204 #endif
205
206 #if !defined(__HUGS__)
207 -- * Newline conversion
208
209 -- | In Haskell, a newline is always represented by the character
210 -- '\n'. However, in files and external character streams, a
211 -- newline may be represented by another character sequence, such
212 -- as '\r\n'.
213 --
214 -- A text-mode 'Handle' has an associated 'NewlineMode' that
215 -- specifies how to transate newline characters. The
216 -- 'NewlineMode' specifies the input and output translation
217 -- separately, so that for instance you can translate '\r\n'
218 -- to '\n' on input, but leave newlines as '\n' on output.
219 --
220 -- The default 'NewlineMode' for a 'Handle' is
221 -- 'nativeNewlineMode', which does no translation on Unix systems,
222 -- but translates '\r\n' to '\n' and back on Windows.
223 --
224 -- Binary-mode 'Handle's do no newline translation at all.
225 --
226 hSetNewlineMode,
227 Newline(..), nativeNewline,
228 NewlineMode(..),
229 noNewlineTranslation, universalNewlineMode, nativeNewlineMode,
230 #endif
231 ) where
232
233 import Control.Exception.Base
234
235 import Data.Bits
236 import Data.List
237 import Data.Maybe
238 import Foreign.C.Error
239 #ifdef mingw32_HOST_OS
240 import Foreign.C.String
241 #endif
242 import Foreign.C.Types
243 import System.Posix.Internals
244 import System.Posix.Types
245
246 #ifdef __GLASGOW_HASKELL__
247 import GHC.Base
248 import GHC.IO hiding ( bracket, onException )
249 import GHC.IO.IOMode
250 import GHC.IO.Handle.FD
251 import qualified GHC.IO.FD as FD
252 import GHC.IO.Handle
253 import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn )
254 import GHC.IO.Exception ( userError )
255 import GHC.IO.Encoding
256 import GHC.Num
257 import Text.Read
258 import GHC.Show
259 import GHC.MVar
260 #endif
261
262 #ifdef __HUGS__
263 import Hugs.IO
264 import Hugs.IOExts
265 import Hugs.IORef
266 import System.IO.Unsafe ( unsafeInterleaveIO )
267 #endif
268
269 -- -----------------------------------------------------------------------------
270 -- Standard IO
271
272 #ifdef __GLASGOW_HASKELL__
273 -- | Write a character to the standard output device
274 -- (same as 'hPutChar' 'stdout').
275
276 putChar :: Char -> IO ()
277 putChar c = hPutChar stdout c
278
279 -- | Write a string to the standard output device
280 -- (same as 'hPutStr' 'stdout').
281
282 putStr :: String -> IO ()
283 putStr s = hPutStr stdout s
284
285 -- | The same as 'putStr', but adds a newline character.
286
287 putStrLn :: String -> IO ()
288 putStrLn s = hPutStrLn stdout s
289
290 -- | The 'print' function outputs a value of any printable type to the
291 -- standard output device.
292 -- Printable types are those that are instances of class 'Show'; 'print'
293 -- converts values to strings for output using the 'show' operation and
294 -- adds a newline.
295 --
296 -- For example, a program to print the first 20 integers and their
297 -- powers of 2 could be written as:
298 --
299 -- > main = print ([(n, 2^n) | n <- [0..19]])
300
301 print :: Show a => a -> IO ()
302 print x = putStrLn (show x)
303
304 -- | Read a character from the standard input device
305 -- (same as 'hGetChar' 'stdin').
306
307 getChar :: IO Char
308 getChar = hGetChar stdin
309
310 -- | Read a line from the standard input device
311 -- (same as 'hGetLine' 'stdin').
312
313 getLine :: IO String
314 getLine = hGetLine stdin
315
316 -- | The 'getContents' operation returns all user input as a single string,
317 -- which is read lazily as it is needed
318 -- (same as 'hGetContents' 'stdin').
319
320 getContents :: IO String
321 getContents = hGetContents stdin
322
323 -- | The 'interact' function takes a function of type @String->String@
324 -- as its argument. The entire input from the standard input device is
325 -- passed to this function as its argument, and the resulting string is
326 -- output on the standard output device.
327
328 interact :: (String -> String) -> IO ()
329 interact f = do s <- getContents
330 putStr (f s)
331
332 -- | The 'readFile' function reads a file and
333 -- returns the contents of the file as a string.
334 -- The file is read lazily, on demand, as with 'getContents'.
335
336 readFile :: FilePath -> IO String
337 readFile name = openFile name ReadMode >>= hGetContents
338
339 -- | The computation 'writeFile' @file str@ function writes the string @str@,
340 -- to the file @file@.
341 writeFile :: FilePath -> String -> IO ()
342 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
343
344 -- | The computation 'appendFile' @file str@ function appends the string @str@,
345 -- to the file @file@.
346 --
347 -- Note that 'writeFile' and 'appendFile' write a literal string
348 -- to a file. To write a value of any printable type, as with 'print',
349 -- use the 'show' function to convert the value to a string first.
350 --
351 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
352
353 appendFile :: FilePath -> String -> IO ()
354 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
355
356 -- | The 'readLn' function combines 'getLine' and 'readIO'.
357
358 readLn :: Read a => IO a
359 readLn = do l <- getLine
360 r <- readIO l
361 return r
362
363 -- | The 'readIO' function is similar to 'read' except that it signals
364 -- parse failure to the 'IO' monad instead of terminating the program.
365
366 readIO :: Read a => String -> IO a
367 readIO s = case (do { (x,t) <- reads s ;
368 ("","") <- lex t ;
369 return x }) of
370 [x] -> return x
371 [] -> ioError (userError "Prelude.readIO: no parse")
372 _ -> ioError (userError "Prelude.readIO: ambiguous parse")
373
374 -- | The Unicode encoding of the current locale
375 --
376 -- This is the initial locale encoding: if it has been subsequently changed by
377 -- 'GHC.IO.Encoding.setLocaleEncoding' this value will not reflect that change.
378 localeEncoding :: TextEncoding
379 localeEncoding = initLocaleEncoding
380 #endif /* __GLASGOW_HASKELL__ */
381
382 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
383 -- available for input from handle @hdl@.
384 --
385 -- This operation may fail with:
386 --
387 -- * 'System.IO.Error.isEOFError' if the end of file has been reached.
388
389 hReady :: Handle -> IO Bool
390 hReady h = hWaitForInput h 0
391
392 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
393 -- given by the 'shows' function to the file or channel managed by @hdl@
394 -- and appends a newline.
395 --
396 -- This operation may fail with:
397 --
398 -- * 'System.IO.Error.isFullError' if the device is full; or
399 --
400 -- * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
401
402 hPrint :: Show a => Handle -> a -> IO ()
403 hPrint hdl = hPutStrLn hdl . show
404
405 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
406 -- the resulting handle to the computation @act@. The handle will be
407 -- closed on exit from 'withFile', whether by normal termination or by
408 -- raising an exception. If closing the handle raises an exception, then
409 -- this exception will be raised by 'withFile' rather than any exception
410 -- raised by 'act'.
411 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
412 withFile name mode = bracket (openFile name mode) hClose
413
414 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
415 -- and passes the resulting handle to the computation @act@. The handle
416 -- will be closed on exit from 'withBinaryFile', whether by normal
417 -- termination or by raising an exception.
418 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
419 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
420
421 -- ---------------------------------------------------------------------------
422 -- fixIO
423
424 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
425 fixIO :: (a -> IO a) -> IO a
426 fixIO k = do
427 m <- newEmptyMVar
428 ans <- unsafeInterleaveIO (takeMVar m)
429 result <- k ans
430 putMVar m result
431 return result
432
433 -- NOTE: we do our own explicit black holing here, because GHC's lazy
434 -- blackholing isn't enough. In an infinite loop, GHC may run the IO
435 -- computation a few times before it notices the loop, which is wrong.
436 --
437 -- NOTE2: the explicit black-holing with an IORef ran into trouble
438 -- with multiple threads (see #5421), so now we use an MVar. I'm
439 -- actually wondering whether we should use readMVar rather than
440 -- takeMVar, just in case it ends up being executed multiple times,
441 -- but even then it would have to be masked to protect against async
442 -- exceptions. Ugh. What we really need here is an IVar, or an
443 -- atomic readMVar, or even STM. All these seem like overkill.
444 --
445 -- See also System.IO.Unsafe.unsafeFixIO.
446 --
447 #endif
448
449 -- | The function creates a temporary file in ReadWrite mode.
450 -- The created file isn\'t deleted automatically, so you need to delete it manually.
451 --
452 -- The file is creates with permissions such that only the current
453 -- user can read\/write it.
454 --
455 -- With some exceptions (see below), the file will be created securely
456 -- in the sense that an attacker should not be able to cause
457 -- openTempFile to overwrite another file on the filesystem using your
458 -- credentials, by putting symbolic links (on Unix) in the place where
459 -- the temporary file is to be created. On Unix the @O_CREAT@ and
460 -- @O_EXCL@ flags are used to prevent this attack, but note that
461 -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you
462 -- rely on this behaviour it is best to use local filesystems only.
463 --
464 openTempFile :: FilePath -- ^ Directory in which to create the file
465 -> String -- ^ File name template. If the template is \"foo.ext\" then
466 -- the created file will be \"fooXXX.ext\" where XXX is some
467 -- random number.
468 -> IO (FilePath, Handle)
469 openTempFile tmp_dir template
470 = openTempFile' "openTempFile" tmp_dir template False 0o600
471
472 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
473 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
474 openBinaryTempFile tmp_dir template
475 = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600
476
477 -- | Like 'openTempFile', but uses the default file permissions
478 openTempFileWithDefaultPermissions :: FilePath -> String
479 -> IO (FilePath, Handle)
480 openTempFileWithDefaultPermissions tmp_dir template
481 = openTempFile' "openBinaryTempFile" tmp_dir template False 0o666
482
483 -- | Like 'openBinaryTempFile', but uses the default file permissions
484 openBinaryTempFileWithDefaultPermissions :: FilePath -> String
485 -> IO (FilePath, Handle)
486 openBinaryTempFileWithDefaultPermissions tmp_dir template
487 = openTempFile' "openBinaryTempFile" tmp_dir template True 0o666
488
489 openTempFile' :: String -> FilePath -> String -> Bool -> CMode
490 -> IO (FilePath, Handle)
491 openTempFile' loc tmp_dir template binary mode = do
492 pid <- c_getpid
493 findTempName pid
494 where
495 -- We split off the last extension, so we can use .foo.ext files
496 -- for temporary files (hidden on Unix OSes). Unfortunately we're
497 -- below filepath in the hierarchy here.
498 (prefix,suffix) =
499 case break (== '.') $ reverse template of
500 -- First case: template contains no '.'s. Just re-reverse it.
501 (rev_suffix, "") -> (reverse rev_suffix, "")
502 -- Second case: template contains at least one '.'. Strip the
503 -- dot from the prefix and prepend it to the suffix (if we don't
504 -- do this, the unique number will get added after the '.' and
505 -- thus be part of the extension, which is wrong.)
506 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
507 -- Otherwise, something is wrong, because (break (== '.')) should
508 -- always return a pair with either the empty string or a string
509 -- beginning with '.' as the second component.
510 _ -> error "bug in System.IO.openTempFile"
511
512 #if defined(__GLASGOW_HASKELL__)
513 findTempName x = do
514 r <- openNewFile filepath binary mode
515 case r of
516 FileExists -> findTempName (x + 1)
517 OpenNewError errno -> ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
518 NewFileCreated fd -> do
519 (fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-}
520 False{-is_socket-}
521 True{-is_nonblock-}
522
523 enc <- getLocaleEncoding
524 h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-} (Just enc)
525
526 return (filepath, h)
527 #else
528 h <- fdToHandle fd `onException` c_close fd
529 return (filepath, h)
530 #endif
531
532 where
533 filename = prefix ++ show x ++ suffix
534 filepath = tmp_dir `combine` filename
535
536 -- XXX bits copied from System.FilePath, since that's not available here
537 combine a b
538 | null b = a
539 | null a = b
540 | last a == pathSeparator = a ++ b
541 | otherwise = a ++ [pathSeparator] ++ b
542
543 #if __HUGS__
544 fdToHandle fd = openFd (fromIntegral fd) False ReadWriteMode binary
545 #endif
546
547 #if defined(__GLASGOW_HASKELL__)
548 data OpenNewFileResult
549 = NewFileCreated CInt
550 | FileExists
551 | OpenNewError Errno
552
553 openNewFile :: FilePath -> Bool -> CMode -> IO OpenNewFileResult
554 openNewFile filepath binary mode = do
555 let oflags1 = rw_flags .|. o_EXCL
556
557 binary_flags
558 | binary = o_BINARY
559 | otherwise = 0
560
561 oflags = oflags1 .|. binary_flags
562 fd <- withFilePath filepath $ \ f ->
563 c_open f oflags mode
564 if fd < 0
565 then do
566 errno <- getErrno
567 case errno of
568 _ | errno == eEXIST -> return FileExists
569 # ifdef mingw32_HOST_OS
570 -- If c_open throws EACCES on windows, it could mean that filepath is a
571 -- directory. In this case, we want to return FileExists so that the
572 -- enclosing openTempFile can try again instead of failing outright.
573 -- See bug #4968.
574 _ | errno == eACCES -> do
575 withCString filepath $ \path -> do
576 -- There is a race here: the directory might have been moved or
577 -- deleted between the c_open call and the next line, but there
578 -- doesn't seem to be any direct way to detect that the c_open call
579 -- failed because of an existing directory.
580 exists <- c_fileExists path
581 return $ if exists
582 then FileExists
583 else OpenNewError errno
584 # endif
585 _ -> return (OpenNewError errno)
586 else return (NewFileCreated fd)
587
588 # ifdef mingw32_HOST_OS
589 foreign import ccall "file_exists" c_fileExists :: CString -> IO Bool
590 # endif
591 #endif
592
593 -- XXX Should use filepath library
594 pathSeparator :: Char
595 #ifdef mingw32_HOST_OS
596 pathSeparator = '\\'
597 #else
598 pathSeparator = '/'
599 #endif
600
601 -- XXX Copied from GHC.Handle
602 std_flags, output_flags, rw_flags :: CInt
603 std_flags = o_NONBLOCK .|. o_NOCTTY
604 output_flags = std_flags .|. o_CREAT
605 rw_flags = output_flags .|. o_RDWR
606
607 -- $locking
608 -- Implementations should enforce as far as possible, at least locally to the
609 -- Haskell process, multiple-reader single-writer locking on files.
610 -- That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/. If any
611 -- open or semi-closed handle is managing a file for output, no new
612 -- handle can be allocated for that file. If any open or semi-closed
613 -- handle is managing a file for input, new handles can only be allocated
614 -- if they do not manage output. Whether two files are the same is
615 -- implementation-dependent, but they should normally be the same if they
616 -- have the same absolute path name and neither has been renamed, for
617 -- example.
618 --
619 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
620 -- the file until the entire contents of the file have been consumed.
621 -- It follows that an attempt to write to a file (using 'writeFile', for
622 -- example) that was earlier opened by 'readFile' will usually result in
623 -- failure with 'System.IO.Error.isAlreadyInUseError'.
624