Fix the build on Windows
[ghc-base.git] / System / Posix / Internals.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 {-# OPTIONS_GHC -fno-warn-unused-binds #-}
3 {-# OPTIONS_HADDOCK hide #-}
4
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module      :  System.Posix.Internals
8 -- Copyright   :  (c) The University of Glasgow, 1992-2002
9 -- License     :  see libraries/base/LICENSE
10 -- 
11 -- Maintainer  :  cvs-ghc@haskell.org
12 -- Stability   :  internal
13 -- Portability :  non-portable (requires POSIX)
14 --
15 -- POSIX support layer for the standard libraries.
16 -- This library is built on *every* platform, including Win32.
17 --
18 -- Non-posix compliant in order to support the following features:
19 --      * S_ISSOCK (no sockets in POSIX)
20 --
21 -----------------------------------------------------------------------------
22
23 -- #hide
24 module System.Posix.Internals where
25
26 #include "HsBaseConfig.h"
27
28 #if ! (defined(mingw32_HOST_OS) || defined(__MINGW32__))
29 import Control.Monad
30 #endif
31 import System.Posix.Types
32
33 import Foreign
34 import Foreign.C
35
36 import Data.Bits
37 import Data.Maybe
38 import System.IO.Error
39
40 #if __GLASGOW_HASKELL__
41 import GHC.Base
42 import GHC.Num
43 import GHC.Real
44 import GHC.IOBase
45 #elif __HUGS__
46 import Hugs.Prelude (IOException(..), IOErrorType(..))
47 import Hugs.IO (IOMode(..))
48 #else
49 import System.IO
50 #endif
51
52 #ifdef __HUGS__
53 {-# CFILES cbits/PrelIOUtils.c cbits/dirUtils.c cbits/consUtils.c #-}
54 #endif
55
56 -- ---------------------------------------------------------------------------
57 -- Types
58
59 type CDir       = ()
60 type CDirent    = ()
61 type CFLock     = ()
62 type CGroup     = ()
63 type CLconv     = ()
64 type CPasswd    = ()
65 type CSigaction = ()
66 type CSigset    = ()
67 type CStat      = ()
68 type CTermios   = ()
69 type CTm        = ()
70 type CTms       = ()
71 type CUtimbuf   = ()
72 type CUtsname   = ()
73
74 #ifndef __GLASGOW_HASKELL__
75 type FD = CInt
76 #endif
77
78 -- ---------------------------------------------------------------------------
79 -- stat()-related stuff
80
81 fdFileSize :: FD -> IO Integer
82 fdFileSize fd = 
83   allocaBytes sizeof_stat $ \ p_stat -> do
84     throwErrnoIfMinus1Retry "fileSize" $
85         c_fstat fd p_stat
86     c_mode <- st_mode p_stat :: IO CMode 
87     if not (s_isreg c_mode)
88         then return (-1)
89         else do
90     c_size <- st_size p_stat
91     return (fromIntegral c_size)
92
93 data FDType  = Directory | Stream | RegularFile | RawDevice
94                deriving (Eq)
95
96 fileType :: FilePath -> IO FDType
97 fileType file =
98   allocaBytes sizeof_stat $ \ p_stat -> do
99   withCString file $ \p_file -> do
100     throwErrnoIfMinus1Retry "fileType" $
101       c_stat p_file p_stat
102     statGetType p_stat
103
104 -- NOTE: On Win32 platforms, this will only work with file descriptors
105 -- referring to file handles. i.e., it'll fail for socket FDs.
106 fdStat :: FD -> IO (FDType, CDev, CIno)
107 fdStat fd = 
108   allocaBytes sizeof_stat $ \ p_stat -> do
109     throwErrnoIfMinus1Retry "fdType" $
110         c_fstat fd p_stat
111     ty <- statGetType p_stat
112     dev <- st_dev p_stat
113     ino <- st_ino p_stat
114     return (ty,dev,ino)
115     
116 fdType :: FD -> IO FDType
117 fdType fd = do (ty,_,_) <- fdStat fd; return ty
118
119 statGetType :: Ptr CStat -> IO FDType
120 statGetType p_stat = do
121   c_mode <- st_mode p_stat :: IO CMode
122   case () of
123       _ | s_isdir c_mode        -> return Directory
124         | s_isfifo c_mode || s_issock c_mode || s_ischr  c_mode
125                                 -> return Stream
126         | s_isreg c_mode        -> return RegularFile
127          -- Q: map char devices to RawDevice too?
128         | s_isblk c_mode        -> return RawDevice
129         | otherwise             -> ioError ioe_unknownfiletype
130     
131 ioe_unknownfiletype :: IOException
132 ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"
133                         "unknown file type"
134 #if __GLASGOW_HASKELL__
135                         Nothing
136 #endif
137                         Nothing
138
139 #if __GLASGOW_HASKELL__ && (defined(mingw32_HOST_OS) || defined(__MINGW32__))
140 closeFd :: Bool -> CInt -> IO CInt
141 closeFd isStream fd 
142   | isStream  = c_closesocket fd
143   | otherwise = c_close fd
144
145 foreign import stdcall unsafe "HsBase.h closesocket"
146    c_closesocket :: CInt -> IO CInt
147 #endif
148
149 fdGetMode :: FD -> IO IOMode
150 #if defined(mingw32_HOST_OS) || defined(__MINGW32__)
151 fdGetMode _ = do
152     -- We don't have a way of finding out which flags are set on FDs
153     -- on Windows, so make a handle that thinks that anything goes.
154     let flags = o_RDWR
155 #else
156 fdGetMode fd = do
157     flags <- throwErrnoIfMinus1Retry "fdGetMode" 
158                 (c_fcntl_read fd const_f_getfl)
159 #endif
160     let
161        wH  = (flags .&. o_WRONLY) /= 0
162        aH  = (flags .&. o_APPEND) /= 0
163        rwH = (flags .&. o_RDWR) /= 0
164
165        mode
166          | wH && aH  = AppendMode
167          | wH        = WriteMode
168          | rwH       = ReadWriteMode
169          | otherwise = ReadMode
170           
171     return mode
172
173 -- ---------------------------------------------------------------------------
174 -- Terminal-related stuff
175
176 fdIsTTY :: FD -> IO Bool
177 fdIsTTY fd = c_isatty fd >>= return.toBool
178
179 #if defined(HTYPE_TCFLAG_T)
180
181 setEcho :: FD -> Bool -> IO ()
182 setEcho fd on = do
183   tcSetAttr fd $ \ p_tios -> do
184     lflag <- c_lflag p_tios :: IO CTcflag
185     let new_lflag
186          | on        = lflag .|. fromIntegral const_echo
187          | otherwise = lflag .&. complement (fromIntegral const_echo)
188     poke_c_lflag p_tios (new_lflag :: CTcflag)
189
190 getEcho :: FD -> IO Bool
191 getEcho fd = do
192   tcSetAttr fd $ \ p_tios -> do
193     lflag <- c_lflag p_tios :: IO CTcflag
194     return ((lflag .&. fromIntegral const_echo) /= 0)
195
196 setCooked :: FD -> Bool -> IO ()
197 setCooked fd cooked = 
198   tcSetAttr fd $ \ p_tios -> do
199
200     -- turn on/off ICANON
201     lflag <- c_lflag p_tios :: IO CTcflag
202     let new_lflag | cooked    = lflag .|. (fromIntegral const_icanon)
203                   | otherwise = lflag .&. complement (fromIntegral const_icanon)
204     poke_c_lflag p_tios (new_lflag :: CTcflag)
205
206     -- set VMIN & VTIME to 1/0 respectively
207     when (not cooked) $ do
208             c_cc <- ptr_c_cc p_tios
209             let vmin  = (c_cc `plusPtr` (fromIntegral const_vmin))  :: Ptr Word8
210                 vtime = (c_cc `plusPtr` (fromIntegral const_vtime)) :: Ptr Word8
211             poke vmin  1
212             poke vtime 0
213
214 tcSetAttr :: FD -> (Ptr CTermios -> IO a) -> IO a
215 tcSetAttr fd fun = do
216      allocaBytes sizeof_termios  $ \p_tios -> do
217         throwErrnoIfMinus1Retry "tcSetAttr"
218            (c_tcgetattr fd p_tios)
219
220 #ifdef __GLASGOW_HASKELL__
221         -- Save a copy of termios, if this is a standard file descriptor.
222         -- These terminal settings are restored in hs_exit().
223         when (fd <= 2) $ do
224           p <- get_saved_termios fd
225           when (p == nullPtr) $ do
226              saved_tios <- mallocBytes sizeof_termios
227              copyBytes saved_tios p_tios sizeof_termios
228              set_saved_termios fd saved_tios
229 #endif
230
231         -- tcsetattr() when invoked by a background process causes the process
232         -- to be sent SIGTTOU regardless of whether the process has TOSTOP set
233         -- in its terminal flags (try it...).  This function provides a
234         -- wrapper which temporarily blocks SIGTTOU around the call, making it
235         -- transparent.
236         allocaBytes sizeof_sigset_t $ \ p_sigset -> do
237         allocaBytes sizeof_sigset_t $ \ p_old_sigset -> do
238              c_sigemptyset p_sigset
239              c_sigaddset   p_sigset const_sigttou
240              c_sigprocmask const_sig_block p_sigset p_old_sigset
241              r <- fun p_tios  -- do the business
242              throwErrnoIfMinus1Retry_ "tcSetAttr" $
243                  c_tcsetattr fd const_tcsanow p_tios
244              c_sigprocmask const_sig_setmask p_old_sigset nullPtr
245              return r
246
247 #ifdef __GLASGOW_HASKELL__
248 foreign import ccall unsafe "HsBase.h __hscore_get_saved_termios"
249    get_saved_termios :: CInt -> IO (Ptr CTermios)
250
251 foreign import ccall unsafe "HsBase.h __hscore_set_saved_termios"
252    set_saved_termios :: CInt -> (Ptr CTermios) -> IO ()
253 #endif
254
255 #else
256
257 -- 'raw' mode for Win32 means turn off 'line input' (=> buffering and
258 -- character translation for the console.) The Win32 API for doing
259 -- this is GetConsoleMode(), which also requires echoing to be disabled
260 -- when turning off 'line input' processing. Notice that turning off
261 -- 'line input' implies enter/return is reported as '\r' (and it won't
262 -- report that character until another character is input..odd.) This
263 -- latter feature doesn't sit too well with IO actions like IO.hGetLine..
264 -- consider yourself warned.
265 setCooked :: FD -> Bool -> IO ()
266 setCooked fd cooked = do
267   x <- set_console_buffering fd (if cooked then 1 else 0)
268   if (x /= 0)
269    then ioError (ioe_unk_error "setCooked" "failed to set buffering")
270    else return ()
271
272 ioe_unk_error :: String -> String -> IOException
273 ioe_unk_error loc msg 
274  = ioeSetErrorString (mkIOError OtherError loc Nothing Nothing) msg
275
276 -- Note: echoing goes hand in hand with enabling 'line input' / raw-ness
277 -- for Win32 consoles, hence setEcho ends up being the inverse of setCooked.
278 setEcho :: FD -> Bool -> IO ()
279 setEcho fd on = do
280   x <- set_console_echo fd (if on then 1 else 0)
281   if (x /= 0)
282    then ioError (ioe_unk_error "setEcho" "failed to set echoing")
283    else return ()
284
285 getEcho :: FD -> IO Bool
286 getEcho fd = do
287   r <- get_console_echo fd
288   if (r == (-1))
289    then ioError (ioe_unk_error "getEcho" "failed to get echoing")
290    else return (r == 1)
291
292 foreign import ccall unsafe "consUtils.h set_console_buffering__"
293    set_console_buffering :: CInt -> CInt -> IO CInt
294
295 foreign import ccall unsafe "consUtils.h set_console_echo__"
296    set_console_echo :: CInt -> CInt -> IO CInt
297
298 foreign import ccall unsafe "consUtils.h get_console_echo__"
299    get_console_echo :: CInt -> IO CInt
300
301 #endif
302
303 -- ---------------------------------------------------------------------------
304 -- Turning on non-blocking for a file descriptor
305
306 setNonBlockingFD :: FD -> IO ()
307 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
308 setNonBlockingFD fd = do
309   flags <- throwErrnoIfMinus1Retry "setNonBlockingFD"
310                  (c_fcntl_read fd const_f_getfl)
311   -- An error when setting O_NONBLOCK isn't fatal: on some systems 
312   -- there are certain file handles on which this will fail (eg. /dev/null
313   -- on FreeBSD) so we throw away the return code from fcntl_write.
314   unless (testBit flags (fromIntegral o_NONBLOCK)) $ do
315     c_fcntl_write fd const_f_setfl (fromIntegral (flags .|. o_NONBLOCK))
316     return ()
317 #else
318
319 -- bogus defns for win32
320 setNonBlockingFD _ = return ()
321
322 #endif
323
324 -- -----------------------------------------------------------------------------
325 -- foreign imports
326
327 foreign import ccall unsafe "HsBase.h access"
328    c_access :: CString -> CInt -> IO CInt
329
330 foreign import ccall unsafe "HsBase.h chmod"
331    c_chmod :: CString -> CMode -> IO CInt
332
333 foreign import ccall unsafe "HsBase.h close"
334    c_close :: CInt -> IO CInt
335
336 foreign import ccall unsafe "HsBase.h closedir" 
337    c_closedir :: Ptr CDir -> IO CInt
338
339 foreign import ccall unsafe "HsBase.h creat"
340    c_creat :: CString -> CMode -> IO CInt
341
342 foreign import ccall unsafe "HsBase.h dup"
343    c_dup :: CInt -> IO CInt
344
345 foreign import ccall unsafe "HsBase.h dup2"
346    c_dup2 :: CInt -> CInt -> IO CInt
347
348 foreign import ccall unsafe "HsBase.h __hscore_fstat"
349    c_fstat :: CInt -> Ptr CStat -> IO CInt
350
351 foreign import ccall unsafe "HsBase.h isatty"
352    c_isatty :: CInt -> IO CInt
353
354 #if defined(mingw32_HOST_OS) || defined(__MINGW32__)
355 foreign import ccall unsafe "HsBase.h __hscore_lseek"
356    c_lseek :: CInt -> Int64 -> CInt -> IO Int64
357 #else
358 foreign import ccall unsafe "HsBase.h __hscore_lseek"
359    c_lseek :: CInt -> COff -> CInt -> IO COff
360 #endif
361
362 foreign import ccall unsafe "HsBase.h __hscore_lstat"
363    lstat :: CString -> Ptr CStat -> IO CInt
364
365 foreign import ccall unsafe "HsBase.h __hscore_open"
366    c_open :: CString -> CInt -> CMode -> IO CInt
367
368 foreign import ccall unsafe "HsBase.h opendir" 
369    c_opendir :: CString  -> IO (Ptr CDir)
370
371 foreign import ccall unsafe "HsBase.h __hscore_mkdir"
372    mkdir :: CString -> CInt -> IO CInt
373
374 foreign import ccall unsafe "HsBase.h read" 
375    c_read :: CInt -> Ptr CChar -> CSize -> IO CSsize
376
377 foreign import ccall unsafe "HsBase.h rewinddir"
378    c_rewinddir :: Ptr CDir -> IO ()
379
380 foreign import ccall unsafe "HsBase.h __hscore_stat"
381    c_stat :: CString -> Ptr CStat -> IO CInt
382
383 foreign import ccall unsafe "HsBase.h umask"
384    c_umask :: CMode -> IO CMode
385
386 foreign import ccall unsafe "HsBase.h write" 
387    c_write :: CInt -> Ptr CChar -> CSize -> IO CSsize
388
389 foreign import ccall unsafe "HsBase.h __hscore_ftruncate"
390    c_ftruncate :: CInt -> COff -> IO CInt
391
392 foreign import ccall unsafe "HsBase.h unlink"
393    c_unlink :: CString -> IO CInt
394
395 foreign import ccall unsafe "HsBase.h getpid"
396    c_getpid :: IO CPid
397
398 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
399 foreign import ccall unsafe "HsBase.h fcntl"
400    c_fcntl_read  :: CInt -> CInt -> IO CInt
401
402 foreign import ccall unsafe "HsBase.h fcntl"
403    c_fcntl_write :: CInt -> CInt -> CLong -> IO CInt
404
405 foreign import ccall unsafe "HsBase.h fcntl"
406    c_fcntl_lock  :: CInt -> CInt -> Ptr CFLock -> IO CInt
407
408 foreign import ccall unsafe "HsBase.h fork"
409    c_fork :: IO CPid 
410
411 foreign import ccall unsafe "HsBase.h link"
412    c_link :: CString -> CString -> IO CInt
413
414 foreign import ccall unsafe "HsBase.h mkfifo"
415    c_mkfifo :: CString -> CMode -> IO CInt
416
417 foreign import ccall unsafe "HsBase.h pipe"
418    c_pipe :: Ptr CInt -> IO CInt
419
420 foreign import ccall unsafe "HsBase.h __hscore_sigemptyset"
421    c_sigemptyset :: Ptr CSigset -> IO CInt
422
423 foreign import ccall unsafe "HsBase.h __hscore_sigaddset"
424    c_sigaddset :: Ptr CSigset -> CInt -> IO CInt
425
426 foreign import ccall unsafe "HsBase.h sigprocmask"
427    c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt
428
429 foreign import ccall unsafe "HsBase.h tcgetattr"
430    c_tcgetattr :: CInt -> Ptr CTermios -> IO CInt
431
432 foreign import ccall unsafe "HsBase.h tcsetattr"
433    c_tcsetattr :: CInt -> CInt -> Ptr CTermios -> IO CInt
434
435 foreign import ccall unsafe "HsBase.h utime"
436    c_utime :: CString -> Ptr CUtimbuf -> IO CInt
437
438 foreign import ccall unsafe "HsBase.h waitpid"
439    c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid
440 #endif
441
442 -- traversing directories
443 foreign import ccall unsafe "dirUtils.h __hscore_readdir"
444   readdir  :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt
445  
446 foreign import ccall unsafe "HsBase.h __hscore_free_dirent"
447   freeDirEnt  :: Ptr CDirent -> IO ()
448  
449 foreign import ccall unsafe "HsBase.h __hscore_end_of_dir"
450   end_of_dir :: CInt
451  
452 foreign import ccall unsafe "HsBase.h __hscore_d_name"
453   d_name :: Ptr CDirent -> IO CString
454
455 -- POSIX flags only:
456 foreign import ccall unsafe "HsBase.h __hscore_o_rdonly" o_RDONLY :: CInt
457 foreign import ccall unsafe "HsBase.h __hscore_o_wronly" o_WRONLY :: CInt
458 foreign import ccall unsafe "HsBase.h __hscore_o_rdwr"   o_RDWR   :: CInt
459 foreign import ccall unsafe "HsBase.h __hscore_o_append" o_APPEND :: CInt
460 foreign import ccall unsafe "HsBase.h __hscore_o_creat"  o_CREAT  :: CInt
461 foreign import ccall unsafe "HsBase.h __hscore_o_excl"   o_EXCL   :: CInt
462 foreign import ccall unsafe "HsBase.h __hscore_o_trunc"  o_TRUNC  :: CInt
463
464 -- non-POSIX flags.
465 foreign import ccall unsafe "HsBase.h __hscore_o_noctty"   o_NOCTTY   :: CInt
466 foreign import ccall unsafe "HsBase.h __hscore_o_nonblock" o_NONBLOCK :: CInt
467 foreign import ccall unsafe "HsBase.h __hscore_o_binary"   o_BINARY   :: CInt
468
469 foreign import ccall unsafe "HsBase.h __hscore_s_isreg"  c_s_isreg  :: CMode -> CInt
470 foreign import ccall unsafe "HsBase.h __hscore_s_ischr"  c_s_ischr  :: CMode -> CInt
471 foreign import ccall unsafe "HsBase.h __hscore_s_isblk"  c_s_isblk  :: CMode -> CInt
472 foreign import ccall unsafe "HsBase.h __hscore_s_isdir"  c_s_isdir  :: CMode -> CInt
473 foreign import ccall unsafe "HsBase.h __hscore_s_isfifo" c_s_isfifo :: CMode -> CInt
474
475 s_isreg  :: CMode -> Bool
476 s_isreg cm = c_s_isreg cm /= 0
477 s_ischr  :: CMode -> Bool
478 s_ischr cm = c_s_ischr cm /= 0
479 s_isblk  :: CMode -> Bool
480 s_isblk cm = c_s_isblk cm /= 0
481 s_isdir  :: CMode -> Bool
482 s_isdir cm = c_s_isdir cm /= 0
483 s_isfifo :: CMode -> Bool
484 s_isfifo cm = c_s_isfifo cm /= 0
485
486 foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int
487 foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime
488 #ifdef mingw32_HOST_OS
489 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO Int64
490 #else
491 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff
492 #endif
493 foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode
494 foreign import ccall unsafe "HsBase.h __hscore_st_dev" st_dev :: Ptr CStat -> IO CDev
495 foreign import ccall unsafe "HsBase.h __hscore_st_ino" st_ino :: Ptr CStat -> IO CIno
496
497 foreign import ccall unsafe "HsBase.h __hscore_echo"         const_echo :: CInt
498 foreign import ccall unsafe "HsBase.h __hscore_tcsanow"      const_tcsanow :: CInt
499 foreign import ccall unsafe "HsBase.h __hscore_icanon"       const_icanon :: CInt
500 foreign import ccall unsafe "HsBase.h __hscore_vmin"         const_vmin   :: CInt
501 foreign import ccall unsafe "HsBase.h __hscore_vtime"        const_vtime  :: CInt
502 foreign import ccall unsafe "HsBase.h __hscore_sigttou"      const_sigttou :: CInt
503 foreign import ccall unsafe "HsBase.h __hscore_sig_block"    const_sig_block :: CInt
504 foreign import ccall unsafe "HsBase.h __hscore_sig_setmask"  const_sig_setmask :: CInt
505 foreign import ccall unsafe "HsBase.h __hscore_f_getfl"      const_f_getfl :: CInt
506 foreign import ccall unsafe "HsBase.h __hscore_f_setfl"      const_f_setfl :: CInt
507
508 #if defined(HTYPE_TCFLAG_T)
509 foreign import ccall unsafe "HsBase.h __hscore_sizeof_termios"  sizeof_termios :: Int
510 foreign import ccall unsafe "HsBase.h __hscore_sizeof_sigset_t" sizeof_sigset_t :: Int
511
512 foreign import ccall unsafe "HsBase.h __hscore_lflag" c_lflag :: Ptr CTermios -> IO CTcflag
513 foreign import ccall unsafe "HsBase.h __hscore_poke_lflag" poke_c_lflag :: Ptr CTermios -> CTcflag -> IO ()
514 foreign import ccall unsafe "HsBase.h __hscore_ptr_c_cc" ptr_c_cc  :: Ptr CTermios -> IO (Ptr Word8)
515 #endif
516
517 s_issock :: CMode -> Bool
518 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
519 s_issock cmode = c_s_issock cmode /= 0
520 foreign import ccall unsafe "HsBase.h __hscore_s_issock" c_s_issock :: CMode -> CInt
521 #else
522 s_issock _ = False
523 #endif