4276874999cfe396d1e61d543fce5272ea7b5247
[ghc-hetmet.git] / ghc / compiler / main / SysTools.lhs
1 -----------------------------------------------------------------------------
2 -- Access to system tools: gcc, cp, rm etc
3 --
4 -- (c) The University of Glasgow 2000
5 --
6 -----------------------------------------------------------------------------
7
8 \begin{code}
9 module SysTools (
10         -- Initialisation
11         initSysTools,
12         setPgm,                 -- String -> IO ()
13                                 -- Command-line override
14         setDryRun,
15
16         packageConfigPath,      -- IO String    
17                                 -- Where package.conf is
18
19         -- Interface to system tools
20         runUnlit, runCpp, runCc, -- [String] -> IO ()
21         runMangle, runSplit,     -- [String] -> IO ()
22         runAs, runLink,          -- [String] -> IO ()
23         runMkDLL,
24
25         touch,                  -- String -> String -> IO ()
26         copy,                   -- String -> String -> String -> IO ()
27         
28         -- Temporary-file management
29         setTmpDir,
30         newTempName,
31         cleanTempFiles, cleanTempFilesExcept, removeTmpFiles,
32         addFilesToClean,
33
34         -- System interface
35         getProcessID,           -- IO Int
36         system,                 -- String -> IO Int
37
38         -- Misc
39         showGhcUsage,           -- IO ()        Shows usage message and exits
40         getSysMan               -- IO String    Parallel system only
41
42  ) where
43
44 import DriverUtil
45 import Config
46 import Outputable
47 import Panic            ( progName, GhcException(..) )
48 import Util             ( global )
49 import CmdLineOpts      ( dynFlag, verbosity )
50
51 import Exception        ( throwDyn, catchAllIO )
52 import IO
53 import Directory        ( doesFileExist, removeFile )
54 import IOExts           ( IORef, readIORef, writeIORef )
55 import Monad            ( when, unless )
56 import System           ( system, ExitCode(..), exitWith, getEnv )
57     
58 #include "../includes/config.h"
59
60 #if !defined(mingw32_TARGET_OS)
61 import qualified Posix
62 #else
63 import Win32DLL
64 import List             ( isPrefixOf )
65 #endif
66
67 import List             ( isSuffixOf )
68
69 #include "HsVersions.h"
70
71 \end{code}
72
73
74                 The configuration story
75                 ~~~~~~~~~~~~~~~~~~~~~~~
76
77 GHC needs various support files (library packages, RTS etc), plus
78 various auxiliary programs (cp, gcc, etc).  It finds these in one
79 of two places:
80
81 * When running as an *installed program*, GHC finds most of this support
82   stuff in the installed library tree.  The path to this tree is passed
83   to GHC via the -B flag, and given to initSysTools .
84
85 * When running *in-place* in a build tree, GHC finds most of this support
86   stuff in the build tree.  The path to the build tree is, again passed
87   to GHC via -B. 
88
89 GHC tells which of the two is the case by seeing whether package.conf
90 is in TopDir [installed] or in TopDir/ghc/driver [inplace] (what a hack).
91
92
93 SysTools.initSysProgs figures out exactly where all the auxiliary programs
94 are, and initialises mutable variables to make it easy to call them.
95 To to this, it makes use of definitions in Config.hs, which is a Haskell
96 file containing variables whose value is figured out by the build system.
97
98 Config.hs contains two sorts of things
99
100   cGCC,         The *names* of the programs
101   cCPP            e.g.  cGCC = gcc
102   cUNLIT                cCPP = gcc -E
103   etc           They do *not* include paths
104                                 
105
106   cUNLIT_DIR    The *path* to the directory containing unlit, split etc
107   cSPLIT_DIR    *relative* to the root of the build tree,
108                 for use when running *in-place* in a build tree (only)
109                 
110
111
112 ---------------------------------------------
113 NOTES for an ALTERNATIVE scheme (i.e *not* what is currently implemented):
114
115 Another hair-brained scheme for simplifying the current tool location
116 nightmare in GHC: Simon originally suggested using another
117 configuration file along the lines of GCC's specs file - which is fine
118 except that it means adding code to read yet another configuration
119 file.  What I didn't notice is that the current package.conf is
120 general enough to do this:
121
122 Package
123     {name = "tools",    import_dirs = [],  source_dirs = [],
124      library_dirs = [], hs_libraries = [], extra_libraries = [],
125      include_dirs = [], c_includes = [],   package_deps = [],
126      extra_ghc_opts = ["-pgmc/usr/bin/gcc","-pgml${libdir}/bin/unlit", ... etc.],
127      extra_cc_opts = [], extra_ld_opts = []}
128
129 Which would have the advantage that we get to collect together in one
130 place the path-specific package stuff with the path-specific tool
131 stuff.
132                 End of NOTES
133 ---------------------------------------------
134
135
136 %************************************************************************
137 %*                                                                      *
138 \subsection{Global variables to contain system programs}
139 %*                                                                      *
140 %************************************************************************
141
142 All these pathnames are maintained IN THE NATIVE FORMAT OF THE HOST MACHINE.
143 (See remarks under pathnames below)
144
145 \begin{code}
146 GLOBAL_VAR(v_Pgm_L,     error "pgm_L",   String)        -- unlit
147 GLOBAL_VAR(v_Pgm_P,     error "pgm_P",   String)        -- cpp
148 GLOBAL_VAR(v_Pgm_c,     error "pgm_c",   String)        -- gcc
149 GLOBAL_VAR(v_Pgm_m,     error "pgm_m",   String)        -- asm code mangler
150 GLOBAL_VAR(v_Pgm_s,     error "pgm_s",   String)        -- asm code splitter
151 GLOBAL_VAR(v_Pgm_a,     error "pgm_a",   String)        -- as
152 GLOBAL_VAR(v_Pgm_l,     error "pgm_l",   String)        -- ld
153 GLOBAL_VAR(v_Pgm_MkDLL, error "pgm_dll", String)        -- mkdll
154
155 GLOBAL_VAR(v_Pgm_T,    error "pgm_T",    String)        -- touch
156 GLOBAL_VAR(v_Pgm_CP,   error "pgm_CP",   String)        -- cp
157
158 GLOBAL_VAR(v_Path_package_config, error "path_package_config", String)
159 GLOBAL_VAR(v_Path_usage,          error "ghc_usage.txt",       String)
160
161 -- Parallel system only
162 GLOBAL_VAR(v_Pgm_sysman, error "pgm_sysman", String)    -- system manager
163 \end{code}
164
165
166 %************************************************************************
167 %*                                                                      *
168 \subsection{Initialisation}
169 %*                                                                      *
170 %************************************************************************
171
172 \begin{code}
173 initSysTools :: [String]        -- Command-line arguments starting "-B"
174
175              -> IO String       -- Set all the mutable variables above, holding 
176                                 --      (a) the system programs
177                                 --      (b) the package-config file
178                                 --      (c) the GHC usage message
179                                 -- Return TopDir
180
181
182 initSysTools minusB_args
183   = do  { (am_installed, top_dir) <- getTopDir minusB_args
184                 -- top_dir
185                 --      for "installed" this is the root of GHC's support files
186                 --      for "in-place" it is the root of the build tree
187                 -- NB: top_dir is assumed to be in standard Unix format '/' separated
188
189         ; let installed, installed_bin :: FilePath -> FilePath
190 #ifndef mingw32_TARGET_OS
191               installed_bin pgm   =  pgmPath (top_dir `slash` "extra-bin") pgm
192 #else
193               installed_bin pgm   =  pgmPath (top_dir `slash` "bin") pgm
194 #endif
195               installed     file  =  pgmPath top_dir file
196               inplace dir   pgm   =  pgmPath (top_dir `slash` dir) pgm
197
198         ; let pkgconfig_path
199                 | am_installed = installed "package.conf"
200                 | otherwise    = inplace cGHC_DRIVER_DIR "package.conf.inplace"
201
202               ghc_usage_msg_path
203                 | am_installed = installed "ghc-usage.txt"
204                 | otherwise    = inplace cGHC_DRIVER_DIR "ghc-usage.txt"
205
206                 -- For all systems, unlit, split, mangle are GHC utilities
207                 -- architecture-specific stuff is done when building Config.hs
208               unlit_path
209                 | am_installed = installed_bin cGHC_UNLIT
210                 | otherwise    = inplace cGHC_UNLIT_DIR cGHC_UNLIT
211
212                 -- split and mangle are Perl scripts
213               split_script
214                 | am_installed = installed_bin cGHC_SPLIT
215                 | otherwise    = inplace cGHC_SPLIT_DIR cGHC_SPLIT
216
217               mangle_script
218                 | am_installed = installed_bin cGHC_MANGLER
219                 | otherwise    = inplace cGHC_MANGLER_DIR cGHC_MANGLER
220
221 #ifndef mingw32_TARGET_OS
222         -- check whether TMPDIR is set in the environment
223         ; IO.try (do dir <- getEnv "TMPDIR" -- fails if not set
224                      setTmpDir dir
225                      return ()
226                  )
227 #endif
228
229         -- Check that the package config exists
230         ; config_exists <- doesFileExist pkgconfig_path
231         ; when (not config_exists) $
232              throwDyn (InstallationError 
233                          ("Can't find package.conf as " ++ pkgconfig_path))
234
235 #if defined(mingw32_TARGET_OS)
236         --              WINDOWS-SPECIFIC STUFF
237         -- On Windows, gcc and friends are distributed with GHC,
238         --      so when "installed" we look in TopDir/bin
239         -- When "in-place" we look wherever the build-time configure 
240         --      script found them
241         -- When "install" we tell gcc where its specs file + exes are (-B)
242         --      and also some places to pick up include files.  We need
243         --      to be careful to put all necessary exes in the -B place
244         --      (as, ld, cc1, etc) since if they don't get found there, gcc
245         --      then tries to run unadorned "as", "ld", etc, and will
246         --      pick up whatever happens to be lying around in the path,
247         --      possibly including those from a cygwin install on the target,
248         --      which is exactly what we're trying to avoid.
249         ; let gcc_path  | am_installed = installed_bin ("gcc -B" ++ installed "gcc-lib/"
250                                          ++ " -I" ++ installed "include/mingw")
251                         | otherwise    = cGCC
252               perl_path | am_installed = installed_bin cGHC_PERL
253                         | otherwise    = cGHC_PERL
254
255         -- 'touch' is a GHC util for Windows, and similarly unlit, mangle
256         ; let touch_path  | am_installed = installed_bin cGHC_TOUCHY
257                           | otherwise    = inplace cGHC_TOUCHY_DIR cGHC_TOUCHY
258
259         -- On Win32 we don't want to rely on #!/bin/perl, so we prepend 
260         -- a call to Perl to get the invocation of split and mangle
261         ; let split_path  = perl_path ++ " " ++ split_script
262               mangle_path = perl_path ++ " " ++ mangle_script
263
264         ; let mkdll_path = cMKDLL
265 #else
266         --              UNIX-SPECIFIC STUFF
267         -- On Unix, the "standard" tools are assumed to be
268         -- in the same place whether we are running "in-place" or "installed"
269         -- That place is wherever the build-time configure script found them.
270         ; let   gcc_path   = cGCC
271                 touch_path = cGHC_TOUCHY
272                 mkdll_path = panic "Can't build DLLs on a non-Win32 system"
273
274         -- On Unix, scripts are invoked using the '#!' method.  Binary
275         -- installations of GHC on Unix place the correct line on the front
276         -- of the script at installation time, so we don't want to wire-in
277         -- our knowledge of $(PERL) on the host system here.
278         ; let split_path  = split_script
279               mangle_path = mangle_script
280 #endif
281
282         -- cpp is derived from gcc on all platforms
283         ; let cpp_path  = gcc_path ++ " -E " ++ cRAWCPP_FLAGS
284
285         -- For all systems, copy and remove are provided by the host
286         -- system; architecture-specific stuff is done when building Config.hs
287         ; let   cp_path = cGHC_CP
288         
289         -- Other things being equal, as and ld are simply gcc
290         ; let   as_path  = gcc_path
291                 ld_path  = gcc_path
292
293                                        
294         -- Initialise the global vars
295         ; writeIORef v_Path_package_config pkgconfig_path
296         ; writeIORef v_Path_usage          ghc_usage_msg_path
297
298         ; writeIORef v_Pgm_sysman          (top_dir ++ "/ghc/rts/parallel/SysMan")
299                 -- Hans: this isn't right in general, but you can 
300                 -- elaborate it in the same way as the others
301
302         ; writeIORef v_Pgm_L               unlit_path
303         ; writeIORef v_Pgm_P               cpp_path
304         ; writeIORef v_Pgm_c               gcc_path
305         ; writeIORef v_Pgm_m               mangle_path
306         ; writeIORef v_Pgm_s               split_path
307         ; writeIORef v_Pgm_a               as_path
308         ; writeIORef v_Pgm_l               ld_path
309         ; writeIORef v_Pgm_MkDLL           mkdll_path
310         ; writeIORef v_Pgm_T               touch_path
311         ; writeIORef v_Pgm_CP              cp_path
312
313         ; return top_dir
314         }
315 \end{code}
316
317 setPgm is called when a command-line option like
318         -pgmLld
319 is used to override a particular program with a new onw
320
321 \begin{code}
322 setPgm :: String -> IO ()
323 -- The string is the flag, minus the '-pgm' prefix
324 -- So the first character says which program to override
325
326 setPgm ('P' : pgm) = writeIORef v_Pgm_P pgm
327 setPgm ('c' : pgm) = writeIORef v_Pgm_c pgm
328 setPgm ('m' : pgm) = writeIORef v_Pgm_m pgm
329 setPgm ('s' : pgm) = writeIORef v_Pgm_s pgm
330 setPgm ('a' : pgm) = writeIORef v_Pgm_a pgm
331 setPgm ('l' : pgm) = writeIORef v_Pgm_l pgm
332 setPgm pgm         = unknownFlagErr ("-pgm" ++ pgm)
333 \end{code}
334
335
336 \begin{code}
337 -- Find TopDir
338 --      for "installed" this is the root of GHC's support files
339 --      for "in-place" it is the root of the build tree
340 --
341 -- Plan of action:
342 -- 1. Set proto_top_dir
343 --      a) look for (the last) -B flag, and use it
344 --      b) if there are no -B flags, get the directory 
345 --         where GHC is running (only on Windows)
346 --
347 -- 2. If package.conf exists in proto_top_dir, we are running
348 --      installed; and TopDir = proto_top_dir
349 --
350 -- 3. Otherwise we are running in-place, so
351 --      proto_top_dir will be /...stuff.../ghc/compiler
352 --      Set TopDir to /...stuff..., which is the root of the build tree
353 --
354 -- This is very gruesome indeed
355
356 getTopDir :: [String]
357           -> IO (Bool,          -- True <=> am installed, False <=> in-place
358                  String)        -- TopDir (in Unix format '/' separated)
359
360 getTopDir minusbs
361   = do { top_dir <- get_proto
362         -- Discover whether we're running in a build tree or in an installation,
363         -- by looking for the package configuration file.
364        ; am_installed <- doesFileExist (top_dir `slash` "package.conf")
365
366        ; return (am_installed, top_dir)
367        }
368   where
369     -- get_proto returns a Unix-format path
370     get_proto | not (null minusbs)
371               = return (unDosifyPath (drop 2 (last minusbs)))   -- 2 for "-B"
372               | otherwise          
373               = do { maybe_exec_dir <- getExecDir -- Get directory of executable
374                    ; case maybe_exec_dir of       -- (only works on Windows; 
375                                                   --  returns Nothing on Unix)
376                         Nothing  -> throwDyn (InstallationError "missing -B<dir> option")
377                         Just dir -> return (remove_suffix (unDosifyPath dir))
378                    }
379
380     -- In an installed tree, the ghc binary lives in $libexecdir, which
381     -- is normally $libdir/bin.  So we strip off a /bin suffix here.
382     -- In a build tree, the ghc binary lives in $fptools/ghc/compiler,
383     -- so we strip off the /ghc/compiler suffix here too, leaving a
384     -- standard TOPDIR.
385     -- Unfortunately, getting top_dir like this and then using it to generate
386     -- the path on which to find binaries means that we're ignoring
387     -- $libexecdir anyway.
388     remove_suffix ghc_bin_dir   -- ghc_bin_dir is in standard Unix format
389         | "/ghc/compiler" `isSuffixOf` ghc_bin_dir      = back_two
390         | "/bin" `isSuffixOf` ghc_bin_dir               = back_one
391         | otherwise                                     = ghc_bin_dir
392         where
393          p1      = dropWhile (not . isSlash) (reverse ghc_bin_dir)
394          p2      = dropWhile (not . isSlash) (tail p1)  -- head is '/'
395          back_two = reverse (tail p2)                   -- head is '/'
396          back_one = reverse (tail p1)
397 \end{code}
398
399
400 %************************************************************************
401 %*                                                                      *
402 \subsection{Running an external program}
403 n%*                                                                     *
404 %************************************************************************
405
406
407 \begin{code}
408 runUnlit :: [String] -> IO ()
409 runUnlit args = do p <- readIORef v_Pgm_L
410                    runSomething "Literate pre-processor" p args
411
412 runCpp :: [String] -> IO ()
413 runCpp args =   do p <- readIORef v_Pgm_P
414                    runSomething "C pre-processor" p args
415
416 runCc :: [String] -> IO ()
417 runCc args =   do p <- readIORef v_Pgm_c
418                   runSomething "C Compiler" p args
419
420 runMangle :: [String] -> IO ()
421 runMangle args = do p <- readIORef v_Pgm_m
422                     runSomething "Mangler" p args
423
424 runSplit :: [String] -> IO ()
425 runSplit args = do p <- readIORef v_Pgm_s
426                    runSomething "Splitter" p args
427
428 runAs :: [String] -> IO ()
429 runAs args = do p <- readIORef v_Pgm_a
430                 runSomething "Assembler" p args
431
432 runLink :: [String] -> IO ()
433 runLink args = do p <- readIORef v_Pgm_l
434                   runSomething "Linker" p args
435
436 runMkDLL :: [String] -> IO ()
437 runMkDLL args = do p <- readIORef v_Pgm_MkDLL
438                    runSomething "Make DLL" p args
439
440 touch :: String -> String -> IO ()
441 touch purpose arg =  do p <- readIORef v_Pgm_T
442                         runSomething purpose p [arg]
443
444 copy :: String -> String -> String -> IO ()
445 copy purpose from to = do
446   verb <- dynFlag verbosity
447   when (verb >= 2) $ hPutStrLn stderr ("*** " ++ purpose)
448
449   h <- openFile to WriteMode
450   ls <- readFile from -- inefficient, but it'll do for now.
451                       -- ToDo: speed up via slurping.
452   hPutStr h ls
453   hClose h
454 \end{code}
455
456 \begin{code}
457 getSysMan :: IO String  -- How to invoke the system manager 
458                         -- (parallel system only)
459 getSysMan = readIORef v_Pgm_sysman
460 \end{code}
461
462 %************************************************************************
463 %*                                                                      *
464 \subsection{GHC Usage message}
465 %*                                                                      *
466 %************************************************************************
467
468 Show the usage message and exit
469
470 \begin{code}
471 showGhcUsage = do { usage_path <- readIORef v_Path_usage
472                   ; usage      <- readFile usage_path
473                   ; dump usage
474                   ; exitWith ExitSuccess }
475   where
476      dump ""          = return ()
477      dump ('$':'$':s) = hPutStr stderr progName >> dump s
478      dump (c:s)       = hPutChar stderr c >> dump s
479
480 packageConfigPath = readIORef v_Path_package_config
481 \end{code}
482
483
484 %************************************************************************
485 %*                                                                      *
486 \subsection{Managing temporary files
487 %*                                                                      *
488 %************************************************************************
489
490 \begin{code}
491 GLOBAL_VAR(v_FilesToClean, [],               [String] )
492 GLOBAL_VAR(v_TmpDir,       cDEFAULT_TMPDIR,  String   )
493         -- v_TmpDir has no closing '/'
494 \end{code}
495
496 \begin{code}
497 setTmpDir dir = writeIORef v_TmpDir dir
498
499 cleanTempFiles :: Int -> IO ()
500 cleanTempFiles verb = do fs <- readIORef v_FilesToClean
501                          removeTmpFiles verb fs
502
503 cleanTempFilesExcept :: Int -> [FilePath] -> IO ()
504 cleanTempFilesExcept verb dont_delete
505   = do fs <- readIORef v_FilesToClean
506        let leftovers = filter (`notElem` dont_delete) fs
507        removeTmpFiles verb leftovers
508        writeIORef v_FilesToClean dont_delete
509
510
511 -- find a temporary name that doesn't already exist.
512 newTempName :: Suffix -> IO FilePath
513 newTempName extn
514   = do x <- getProcessID
515        tmp_dir <- readIORef v_TmpDir
516        findTempName tmp_dir x
517   where 
518     findTempName tmp_dir x
519       = do let filename = tmp_dir ++ "/ghc" ++ show x ++ '.':extn
520            b  <- doesFileExist filename
521            if b then findTempName tmp_dir (x+1)
522                 else do add v_FilesToClean filename -- clean it up later
523                         return filename
524
525 addFilesToClean :: [FilePath] -> IO ()
526 -- May include wildcards [used by DriverPipeline.run_phase SplitMangle]
527 addFilesToClean files = mapM_ (add v_FilesToClean) files
528
529 removeTmpFiles :: Int -> [FilePath] -> IO ()
530 removeTmpFiles verb fs
531   = traceCmd "Deleting temp files" 
532              ("Deleting: " ++ unwords fs)
533              (mapM_ rm fs)
534   where
535     rm f = removeFile f `catchAllIO` 
536                 (\_ignored -> 
537                     when (verb >= 2) $
538                       hPutStrLn stderr ("Warning: deleting non-existent " ++ f)
539                 )
540
541 \end{code}
542
543
544 %************************************************************************
545 %*                                                                      *
546 \subsection{Running a program}
547 %*                                                                      *
548 %************************************************************************
549
550 \begin{code}
551 GLOBAL_VAR(v_Dry_run, False, Bool)
552
553 setDryRun :: IO () 
554 setDryRun = writeIORef v_Dry_run True
555
556 -----------------------------------------------------------------------------
557 -- Running an external program
558
559 runSomething :: String          -- For -v message
560              -> String          -- Command name (possibly a full path)
561                                 --      assumed already dos-ified
562              -> [String]        -- Arguments
563                                 --      runSomething will dos-ify them
564              -> IO ()
565
566 runSomething phase_name pgm args
567  = traceCmd phase_name cmd_line $
568    do   { exit_code <- system cmd_line
569         ; if exit_code /= ExitSuccess
570           then throwDyn (PhaseFailed phase_name exit_code)
571           else return ()
572         }
573   where
574     cmd_line = unwords (pgm : dosifyPaths args)
575         -- The pgm is already in native format (appropriate dir separators)
576
577 traceCmd :: String -> String -> IO () -> IO ()
578 -- a) trace the command (at two levels of verbosity)
579 -- b) don't do it at all if dry-run is set
580 traceCmd phase_name cmd_line action
581  = do   { verb <- dynFlag verbosity
582         ; when (verb >= 2) $ hPutStrLn stderr ("*** " ++ phase_name)
583         ; when (verb >= 3) $ hPutStrLn stderr cmd_line
584         ; hFlush stderr
585         
586            -- Test for -n flag
587         ; n <- readIORef v_Dry_run
588         ; unless n $ do {
589
590            -- And run it!
591         ; action `catchAllIO` handle_exn verb
592         }}
593   where
594     handle_exn verb exn = do { when (verb >= 2) (hPutStr   stderr "\n")
595                              ; when (verb >= 3) (hPutStrLn stderr ("Failed: " ++ cmd_line))
596                              ; throwDyn (PhaseFailed phase_name (ExitFailure 1)) }
597 \end{code}
598
599
600 %************************************************************************
601 %*                                                                      *
602 \subsection{Path names}
603 %*                                                                      *
604 %************************************************************************
605
606 We maintain path names in Unix form ('/'-separated) right until 
607 the last moment.  On Windows we dos-ify them just before passing them
608 to the Windows command.
609
610 The alternative, of using '/' consistently on Unix and '\' on Windows,
611 proved quite awkward.  There were a lot more calls to dosifyPath,
612 and even on Windows we might invoke a unix-like utility (eg 'sh'), which
613 interpreted a command line 'foo\baz' as 'foobaz'.
614
615 \begin{code}
616 -----------------------------------------------------------------------------
617 -- Convert filepath into MSDOS form.
618
619 dosifyPaths :: [String] -> [String]
620 -- dosifyPaths does two things
621 -- a) change '/' to '\'
622 -- b) remove initial '/cygdrive/'
623
624 unDosifyPath :: String -> String
625 -- Just change '\' to '/'
626
627 pgmPath :: String               -- Directory string in Unix format
628         -> String               -- Program name with no directory separators
629                                 --      (e.g. copy /y)
630         -> String               -- Program invocation string in native format
631
632
633
634 #if defined(mingw32_TARGET_OS)
635
636 --------------------- Windows version ------------------
637 dosifyPaths xs = map dosifyPath xs
638
639 unDosifyPath xs = subst '\\' '/' xs
640
641 pgmPath dir pgm = dosifyPath dir ++ '\\' : pgm
642
643 dosifyPath stuff
644   = subst '/' '\\' real_stuff
645  where
646    -- fully convince myself that /cygdrive/ prefixes cannot
647    -- really appear here.
648   cygdrive_prefix = "/cygdrive/"
649
650   real_stuff
651     | cygdrive_prefix `isPrefixOf` stuff = drop (length cygdrive_prefix) stuff
652     | otherwise = stuff
653    
654 #else
655
656 --------------------- Unix version ---------------------
657 dosifyPaths  ps = ps
658 unDosifyPath xs = xs
659 pgmPath dir pgm = dir ++ '/' : pgm
660 --------------------------------------------------------
661 #endif
662
663 subst a b ls = map (\ x -> if x == a then b else x) ls
664 \end{code}
665
666
667 -----------------------------------------------------------------------------
668    Path name construction
669
670 \begin{code}
671 slash            :: String -> String -> String
672 absPath, relPath :: [String] -> String
673
674 isSlash '/'   = True
675 isSlash other = False
676
677 relPath [] = ""
678 relPath xs = foldr1 slash xs
679
680 absPath xs = "" `slash` relPath xs
681
682 slash s1 s2 = s1 ++ ('/' : s2)
683 \end{code}
684
685
686 %************************************************************************
687 %*                                                                      *
688 \subsection{Support code}
689 %*                                                                      *
690 %************************************************************************
691
692 \begin{code}
693 -----------------------------------------------------------------------------
694 -- Define       getExecDir     :: IO (Maybe String)
695
696 #if defined(mingw32_TARGET_OS)
697 getExecDir :: IO (Maybe String)
698 getExecDir = do h <- getModuleHandle Nothing
699                 n <- getModuleFileName h
700                 return (Just (reverse (tail (dropWhile (not . isSlash) (reverse (unDosifyPath n))))))
701 #else
702 getExecDir :: IO (Maybe String) = do return Nothing
703 #endif
704
705 #ifdef mingw32_TARGET_OS
706 foreign import "_getpid" getProcessID :: IO Int -- relies on Int == Int32 on Windows
707 #else
708 getProcessID :: IO Int
709 getProcessID = Posix.getProcessID
710 #endif
711 \end{code}