1 /* Utilities to execute a program in a subprocess (possibly linked by pipes
2 with other subprocesses), and wait for it. Generic Win32 specialization.
3 Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
4 Free Software Foundation, Inc.
6 This file is part of the libiberty library.
7 Libiberty is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public
9 License as published by the Free Software Foundation; either
10 version 2 of the License, or (at your option) any later version.
12 Libiberty is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with libiberty; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 #include "pex-common.h"
35 #ifdef HAVE_SYS_WAIT_H
48 /* mingw32 headers may not define the following. */
58 # define WAIT_GRANDCHILD 1
61 #define MINGW_NAME "Minimalist GNU for Windows"
62 #define MINGW_NAME_LEN (sizeof(MINGW_NAME) - 1)
64 extern char *stpcpy (char *dst
, const char *src
);
66 /* Ensure that the executable pathname uses Win32 backslashes. This
67 is not necessary on NT, but on W9x, forward slashes causes
68 failure of spawn* and exec* functions (and probably any function
69 that calls CreateProcess) *iff* the executable pathname (argv[0])
70 is a quoted string. And quoting is necessary in case a pathname
71 contains embedded white space. You can't win. */
73 backslashify (char *s
)
75 while ((s
= strchr (s
, '/')) != NULL
)
80 static int pex_win32_open_read (struct pex_obj
*, const char *, int);
81 static int pex_win32_open_write (struct pex_obj
*, const char *, int);
82 static long pex_win32_exec_child (struct pex_obj
*, int, const char *,
83 char * const *, char * const *,
85 const char **, int *);
86 static int pex_win32_close (struct pex_obj
*, int);
87 static int pex_win32_wait (struct pex_obj
*, long, int *,
88 struct pex_time
*, int, const char **, int *);
89 static int pex_win32_pipe (struct pex_obj
*, int *, int);
90 static FILE *pex_win32_fdopenr (struct pex_obj
*, int, int);
91 static FILE *pex_win32_fdopenw (struct pex_obj
*, int, int);
93 /* The list of functions we pass to the common routines. */
95 const struct pex_funcs funcs
=
108 /* Return a newly initialized pex_obj structure. */
111 pex_init (int flags
, const char *pname
, const char *tempbase
)
113 return pex_init_common (flags
, pname
, tempbase
, &funcs
);
116 /* Open a file for reading. */
119 pex_win32_open_read (struct pex_obj
*obj ATTRIBUTE_UNUSED
, const char *name
,
122 return _open (name
, _O_RDONLY
| (binary
? _O_BINARY
: _O_TEXT
));
125 /* Open a file for writing. */
128 pex_win32_open_write (struct pex_obj
*obj ATTRIBUTE_UNUSED
, const char *name
,
131 /* Note that we can't use O_EXCL here because gcc may have already
132 created the temporary file via make_temp_file. */
134 (_O_WRONLY
| _O_CREAT
| _O_TRUNC
135 | (binary
? _O_BINARY
: _O_TEXT
)),
136 _S_IREAD
| _S_IWRITE
);
142 pex_win32_close (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
)
147 #ifdef USE_MINGW_MSYS
148 static const char *mingw_keys
[] = {"SOFTWARE", "Microsoft", "Windows", "CurrentVersion", "Uninstall", NULL
};
150 /* Tack the executable on the end of a (possibly slash terminated) buffer
151 and convert everything to \. */
153 tack_on_executable (char *buf
, const char *executable
)
155 char *p
= strchr (buf
, '\0');
156 if (p
> buf
&& (p
[-1] == '\\' || p
[-1] == '/'))
158 backslashify (strcat (buf
, executable
));
162 /* Walk down a registry hierarchy until the end. Return the key. */
164 openkey (HKEY hStart
, const char *keys
[])
167 for (hKey
= hStart
; *keys
; keys
++)
171 res
= RegOpenKey (hTmp
, *keys
, &hKey
);
173 if (hTmp
!= HKEY_LOCAL_MACHINE
)
176 if (res
!= ERROR_SUCCESS
)
182 /* Return the "mingw root" as derived from the mingw uninstall information. */
184 mingw_rootify (const char *executable
)
188 char *namebuf
, *foundbuf
;
192 /* Open the uninstall "directory". */
193 hKey
= openkey (HKEY_LOCAL_MACHINE
, mingw_keys
);
199 /* Need to enumerate all of the keys here looking for one the most recent
201 if (RegQueryInfoKey (hKey
, NULL
, NULL
, NULL
, NULL
, &maxlen
, NULL
, NULL
,
202 NULL
, NULL
, NULL
, NULL
) != ERROR_SUCCESS
)
207 namebuf
= XNEWVEC (char, ++maxlen
);
208 foundbuf
= XNEWVEC (char, maxlen
);
210 if (!namebuf
|| !foundbuf
)
220 /* Look through all of the keys for one that begins with Minimal GNU...
221 Try to get the latest version by doing a string compare although that
222 string never really works with version number sorting. */
223 for (i
= 0; RegEnumKey (hKey
, i
, namebuf
, maxlen
) == ERROR_SUCCESS
; i
++)
225 int match
= strcasecmp (namebuf
, MINGW_NAME
);
228 if (match
> 0 && strncasecmp (namebuf
, MINGW_NAME
, MINGW_NAME_LEN
) > 0)
230 if (strcasecmp (namebuf
, foundbuf
) > 0)
231 strcpy (foundbuf
, namebuf
);
235 /* If foundbuf is empty, we didn't find anything. Punt. */
243 /* Open the key that we wanted */
244 res
= RegOpenKey (hKey
, foundbuf
, &hTmp
);
248 /* Don't know why this would fail, but you gotta check */
249 if (res
!= ERROR_SUCCESS
)
253 /* Get the length of the value pointed to by InstallLocation */
254 if (RegQueryValueEx (hTmp
, "InstallLocation", 0, NULL
, NULL
,
255 &maxlen
) != ERROR_SUCCESS
|| maxlen
== 0)
261 /* Allocate space for the install location */
262 foundbuf
= XNEWVEC (char, maxlen
+ strlen (executable
));
269 /* Read the install location into the buffer */
270 res
= RegQueryValueEx (hTmp
, "InstallLocation", 0, NULL
, (LPBYTE
) foundbuf
,
273 if (res
!= ERROR_SUCCESS
)
279 /* Concatenate the install location and the executable, turn all slashes
280 to backslashes, and return that. */
281 return tack_on_executable (foundbuf
, executable
);
284 /* Read the install location of msys from it's installation file and
285 rootify the executable based on that. */
287 msys_rootify (const char *executable
)
290 size_t execlen
= strlen (executable
) + 1;
295 buf
= XNEWVEC (char, bufsize
+ execlen
);
298 res
= GetPrivateProfileString ("InstallSettings", "InstallPath", NULL
,
299 buf
, bufsize
, "msys.ini");
302 if (strlen (buf
) < bufsize
)
315 return tack_on_executable (buf
, executable
);
324 /* Return a Windows command-line from ARGV. It is the caller's
325 responsibility to free the string returned. */
328 argv_to_cmdline (char *const *argv
)
336 for (i
= 0; argv
[i
]; i
++)
338 /* We quote every last argument. This simplifies the problem;
339 we need only escape embedded double-quotes and immediately
340 preceeding backslash characters. A sequence of backslach characters
341 that is not follwed by a double quote character will not be
343 for (j
= 0; argv
[i
][j
]; j
++)
345 if (argv
[i
][j
] == '"')
347 /* Escape preceeding backslashes. */
348 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
350 /* Escape the qote character. */
354 /* Trailing backslashes also need to be escaped because they will be
355 followed by the terminating quote. */
356 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
359 cmdline_len
+= 3; /* for leading and trailing quotes and space */
361 cmdline
= xmalloc (cmdline_len
);
363 for (i
= 0; argv
[i
]; i
++)
366 for (j
= 0; argv
[i
][j
]; j
++)
368 if (argv
[i
][j
] == '"')
370 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
376 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
385 static const char *const
393 static const char *const
399 /* Returns the full path to PROGRAM. If SEARCH is true, look for
400 PROGRAM in each directory in PATH. */
403 find_executable (const char *program
, BOOL search
)
405 char *full_executable
;
408 const char *path
= 0;
409 const char *const *ext
;
411 size_t proglen
= strlen (program
);
412 int has_extension
= !!strchr (program
, '.');
413 int has_slash
= (strchr (program
, '/') || strchr (program
, '\\'));
420 path
= getenv ("PATH");
425 for (p
= path
; *p
; p
= q
)
428 while (*q
!= ';' && *q
!= '\0')
430 if ((size_t)(q
- p
) > fe_len
)
435 fe_len
= fe_len
+ 1 + proglen
+ (has_extension
? 1 : 5);
436 full_executable
= xmalloc (fe_len
);
442 while (*q
!= ';' && *q
!= '\0')
446 memcpy (e
, p
, q
- p
);
455 for (e
= full_executable
; *e
; e
++)
459 /* At this point, e points to the terminating NUL character for
461 for (ext
= has_extension
? no_suffixes
: std_suffixes
; *ext
; ext
++)
463 /* Remove any current extension. */
465 /* Add the new one. */
466 strcat (full_executable
, *ext
);
468 /* Attempt to open this file. */
469 h
= CreateFile (full_executable
, GENERIC_READ
,
470 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
471 0, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
472 if (h
!= INVALID_HANDLE_VALUE
)
478 free (full_executable
);
483 return full_executable
;
486 /* Low-level process creation function and helper. */
489 env_compare (const void *a_ptr
, const void *b_ptr
)
496 a
= *(const char **) a_ptr
;
497 b
= *(const char **) b_ptr
;
499 /* a and b will be of the form: VAR=VALUE
500 We compare only the variable name part here using a case-insensitive
501 comparison algorithm. It might appear that in fact strcasecmp () can
502 take the place of this whole function, and indeed it could, save for
503 the fact that it would fail in cases such as comparing A1=foo and
504 A=bar (because 1 is less than = in the ASCII character set).
505 (Environment variables containing no numbers would work in such a
510 c1
= (unsigned char) tolower (*a
++);
511 c2
= (unsigned char) tolower (*b
++);
519 while (c1
== c2
&& c1
!= '\0');
525 win32_spawn (const char *executable
,
528 char *const *env
, /* array of strings of the form: VAR=VALUE */
529 DWORD dwCreationFlags
,
531 LPPROCESS_INFORMATION pi
)
533 char *full_executable
;
536 char *env_block
= NULL
;
538 full_executable
= NULL
;
545 /* Count the number of environment bindings supplied. */
546 for (env_size
= 0; env
[env_size
]; env_size
++)
549 /* Assemble an environment block, if required. This consists of
550 VAR=VALUE strings juxtaposed (with one null character between each
551 pair) and an additional null at the end. */
555 int total_size
= 1; /* 1 is for the final null. */
558 /* Windows needs the members of the block to be sorted by variable
560 env_copy
= alloca (sizeof (char *) * env_size
);
561 memcpy (env_copy
, env
, sizeof (char *) * env_size
);
562 qsort (env_copy
, env_size
, sizeof (char *), env_compare
);
564 for (var
= 0; var
< env_size
; var
++)
565 total_size
+= strlen (env
[var
]) + 1;
567 env_block
= malloc (total_size
);
569 for (var
= 0; var
< env_size
; var
++)
570 bufptr
= stpcpy (bufptr
, env_copy
[var
]) + 1;
576 full_executable
= find_executable (executable
, search
);
577 if (!full_executable
)
579 cmdline
= argv_to_cmdline (argv
);
583 /* Create the child process. */
584 if (!CreateProcess (full_executable
, cmdline
,
585 /*lpProcessAttributes=*/NULL
,
586 /*lpThreadAttributes=*/NULL
,
587 /*bInheritHandles=*/TRUE
,
590 /*lpCurrentDirectory=*/NULL
,
597 free (full_executable
);
603 CloseHandle (pi
->hThread
);
604 free (full_executable
);
608 return (long) pi
->hProcess
;
616 free (full_executable
);
622 spawn_script (const char *executable
, char *const *argv
,
624 DWORD dwCreationFlags
,
626 LPPROCESS_INFORMATION pi
)
629 int save_errno
= errno
;
630 int fd
= _open (executable
, _O_RDONLY
);
634 char buf
[MAX_PATH
+ 5];
635 int len
= _read (fd
, buf
, sizeof (buf
) - 1);
641 eol
= strchr (buf
, '\n');
642 if (eol
&& strncmp (buf
, "#!", 2) == 0)
645 const char ** avhere
= (const char **) --argv
;
648 while (*--eol
== '\r' || *eol
== ' ' || *eol
== '\t');
649 for (executable1
= buf
+ 2; *executable1
== ' ' || *executable1
== '\t'; executable1
++)
652 backslashify (executable1
);
653 *avhere
= executable1
;
654 #ifndef USE_MINGW_MSYS
655 executable
= strrchr (executable1
, '\\') + 1;
657 executable
= executable1
;
658 pid
= win32_spawn (executable
, TRUE
, argv
, env
,
659 dwCreationFlags
, si
, pi
);
661 if (strchr (executable1
, '\\') == NULL
)
662 pid
= win32_spawn (executable1
, TRUE
, argv
, env
,
663 dwCreationFlags
, si
, pi
);
664 else if (executable1
[0] != '\\')
665 pid
= win32_spawn (executable1
, FALSE
, argv
, env
,
666 dwCreationFlags
, si
, pi
);
669 const char *newex
= mingw_rootify (executable1
);
671 pid
= win32_spawn (newex
, FALSE
, argv
, env
,
672 dwCreationFlags
, si
, pi
);
673 if (executable1
!= newex
)
674 free ((char *) newex
);
677 newex
= msys_rootify (executable1
);
678 if (newex
!= executable1
)
681 pid
= win32_spawn (newex
, FALSE
, argv
, env
,
682 dwCreationFlags
, si
, pi
);
683 free ((char *) newex
);
696 /* Execute a child. */
699 pex_win32_exec_child (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int flags
,
700 const char *executable
, char * const * argv
,
702 int in
, int out
, int errdes
,
703 int toclose ATTRIBUTE_UNUSED
,
709 HANDLE stdout_handle
;
710 HANDLE stderr_handle
;
711 DWORD dwCreationFlags
;
712 OSVERSIONINFO version_info
;
714 PROCESS_INFORMATION pi
;
716 stdin_handle
= INVALID_HANDLE_VALUE
;
717 stdout_handle
= INVALID_HANDLE_VALUE
;
718 stderr_handle
= INVALID_HANDLE_VALUE
;
720 stdin_handle
= (HANDLE
) _get_osfhandle (in
);
721 stdout_handle
= (HANDLE
) _get_osfhandle (out
);
722 if (!(flags
& PEX_STDERR_TO_STDOUT
))
723 stderr_handle
= (HANDLE
) _get_osfhandle (errdes
);
725 stderr_handle
= stdout_handle
;
727 /* Determine the version of Windows we are running on. */
728 version_info
.dwOSVersionInfoSize
= sizeof (version_info
);
729 GetVersionEx (&version_info
);
730 if (version_info
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
)
731 /* On Windows 95/98/ME the CREATE_NO_WINDOW flag is not
732 supported, so we cannot avoid creating a console window. */
736 HANDLE conout_handle
;
738 /* Determine whether or not we have an associated console. */
739 conout_handle
= CreateFile("CONOUT$",
742 /*lpSecurityAttributes=*/NULL
,
744 FILE_ATTRIBUTE_NORMAL
,
745 /*hTemplateFile=*/NULL
);
746 if (conout_handle
== INVALID_HANDLE_VALUE
)
747 /* There is no console associated with this process. Since
748 the child is a console process, the OS would normally
749 create a new console Window for the child. Since we'll be
750 redirecting the child's standard streams, we do not need
751 the console window. */
752 dwCreationFlags
= CREATE_NO_WINDOW
;
755 /* There is a console associated with the process, so the OS
756 will not create a new console. And, if we use
757 CREATE_NO_WINDOW in this situation, the child will have
758 no associated console. Therefore, if the child's
759 standard streams are connected to the console, the output
760 will be discarded. */
761 CloseHandle(conout_handle
);
766 /* Since the child will be a console process, it will, by default,
767 connect standard input/output to its console. However, we want
768 the child to use the handles specifically designated above. In
769 addition, if there is no console (such as when we are running in
770 a Cygwin X window), then we must redirect the child's
771 input/output, as there is no console for the child to use. */
772 memset (&si
, 0, sizeof (si
));
774 si
.dwFlags
= STARTF_USESTDHANDLES
;
775 si
.hStdInput
= stdin_handle
;
776 si
.hStdOutput
= stdout_handle
;
777 si
.hStdError
= stderr_handle
;
779 /* Create the child process. */
780 pid
= win32_spawn (executable
, (flags
& PEX_SEARCH
) != 0,
781 argv
, env
, dwCreationFlags
, &si
, &pi
);
783 pid
= spawn_script (executable
, argv
, env
, dwCreationFlags
,
788 *errmsg
= "CreateProcess";
791 /* Close the standard output and standard error handles in the
793 if (out
!= STDOUT_FILENO
)
794 obj
->funcs
->close (obj
, out
);
795 if (errdes
!= STDERR_FILENO
)
796 obj
->funcs
->close (obj
, errdes
);
801 /* Wait for a child process to complete. MS CRTDLL doesn't return
802 enough information in status to decide if the child exited due to a
803 signal or not, rather it simply returns an integer with the exit
804 code of the child; eg., if the child exited with an abort() call
805 and didn't have a handler for SIGABRT, it simply returns with
806 status == 3. We fix the status code to conform to the usual WIF*
807 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
810 pex_win32_wait (struct pex_obj
*obj ATTRIBUTE_UNUSED
, long pid
,
811 int *status
, struct pex_time
*time
, int done ATTRIBUTE_UNUSED
,
812 const char **errmsg
, int *err
)
818 memset (time
, 0, sizeof *time
);
822 /* FIXME: If done is non-zero, we should probably try to kill the
824 if (WaitForSingleObject (h
, INFINITE
) != WAIT_OBJECT_0
)
828 *errmsg
= "WaitForSingleObject";
832 GetExitCodeProcess (h
, &termstat
);
835 /* A value of 3 indicates that the child caught a signal, but not
836 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
841 *status
= (termstat
& 0xff) << 8;
849 pex_win32_pipe (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int *p
,
852 return _pipe (p
, 256, binary
? _O_BINARY
: _O_TEXT
);
855 /* Get a FILE pointer to read from a file descriptor. */
858 pex_win32_fdopenr (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
,
861 return fdopen (fd
, binary
? "rb" : "r");
865 pex_win32_fdopenw (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
,
868 HANDLE h
= (HANDLE
) _get_osfhandle (fd
);
869 if (h
== INVALID_HANDLE_VALUE
)
871 if (! SetHandleInformation (h
, HANDLE_FLAG_INHERIT
, 0))
873 return fdopen (fd
, binary
? "wb" : "w");
880 main (int argc ATTRIBUTE_UNUSED
, char **argv
)
885 printf ("%ld\n", pex_win32_exec_child (NULL
, PEX_SEARCH
, argv
[0], argv
, NULL
, 0, 0, 1, 2, &errmsg
, &err
));