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-2019 Free Software Foundation, Inc.
5 This file is part of the libiberty library.
6 Libiberty is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public
8 License as published by the Free Software Foundation; either
9 version 2 of the License, or (at your option) any later version.
11 Libiberty is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with libiberty; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
19 Boston, MA 02110-1301, USA. */
21 #include "pex-common.h"
34 #ifdef HAVE_SYS_WAIT_H
47 /* mingw32 headers may not define the following. */
57 # define WAIT_GRANDCHILD 1
60 #define MINGW_NAME "Minimalist GNU for Windows"
61 #define MINGW_NAME_LEN (sizeof(MINGW_NAME) - 1)
63 extern char *stpcpy (char *dst
, const char *src
);
65 /* Ensure that the executable pathname uses Win32 backslashes. This
66 is not necessary on NT, but on W9x, forward slashes causes
67 failure of spawn* and exec* functions (and probably any function
68 that calls CreateProcess) *iff* the executable pathname (argv[0])
69 is a quoted string. And quoting is necessary in case a pathname
70 contains embedded white space. You can't win. */
72 backslashify (char *s
)
74 while ((s
= strchr (s
, '/')) != NULL
)
79 static int pex_win32_open_read (struct pex_obj
*, const char *, int);
80 static int pex_win32_open_write (struct pex_obj
*, const char *, int, int);
81 static pid_t
pex_win32_exec_child (struct pex_obj
*, int, const char *,
82 char * const *, char * const *,
84 const char **, int *);
85 static int pex_win32_close (struct pex_obj
*, int);
86 static pid_t
pex_win32_wait (struct pex_obj
*, pid_t
, int *,
87 struct pex_time
*, int, const char **, int *);
88 static int pex_win32_pipe (struct pex_obj
*, int *, int);
89 static FILE *pex_win32_fdopenr (struct pex_obj
*, int, int);
90 static FILE *pex_win32_fdopenw (struct pex_obj
*, int, int);
92 /* The list of functions we pass to the common routines. */
94 const struct pex_funcs funcs
=
107 /* Return a newly initialized pex_obj structure. */
110 pex_init (int flags
, const char *pname
, const char *tempbase
)
112 return pex_init_common (flags
, pname
, tempbase
, &funcs
);
115 /* Open a file for reading. */
118 pex_win32_open_read (struct pex_obj
*obj ATTRIBUTE_UNUSED
, const char *name
,
121 return _open (name
, _O_RDONLY
| (binary
? _O_BINARY
: _O_TEXT
));
124 /* Open a file for writing. */
127 pex_win32_open_write (struct pex_obj
*obj ATTRIBUTE_UNUSED
, const char *name
,
128 int binary
, int append
)
130 /* Note that we can't use O_EXCL here because gcc may have already
131 created the temporary file via make_temp_file. */
135 (_O_WRONLY
| _O_CREAT
| _O_TRUNC
136 | (binary
? _O_BINARY
: _O_TEXT
)),
137 _S_IREAD
| _S_IWRITE
);
143 pex_win32_close (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
)
148 #ifdef USE_MINGW_MSYS
149 static const char *mingw_keys
[] = {"SOFTWARE", "Microsoft", "Windows", "CurrentVersion", "Uninstall", NULL
};
151 /* Tack the executable on the end of a (possibly slash terminated) buffer
152 and convert everything to \. */
154 tack_on_executable (char *buf
, const char *executable
)
156 char *p
= strchr (buf
, '\0');
157 if (p
> buf
&& (p
[-1] == '\\' || p
[-1] == '/'))
159 backslashify (strcat (buf
, executable
));
163 /* Walk down a registry hierarchy until the end. Return the key. */
165 openkey (HKEY hStart
, const char *keys
[])
168 for (hKey
= hStart
; *keys
; keys
++)
172 res
= RegOpenKey (hTmp
, *keys
, &hKey
);
174 if (hTmp
!= HKEY_LOCAL_MACHINE
)
177 if (res
!= ERROR_SUCCESS
)
183 /* Return the "mingw root" as derived from the mingw uninstall information. */
185 mingw_rootify (const char *executable
)
189 char *namebuf
, *foundbuf
;
193 /* Open the uninstall "directory". */
194 hKey
= openkey (HKEY_LOCAL_MACHINE
, mingw_keys
);
200 /* Need to enumerate all of the keys here looking for one the most recent
202 if (RegQueryInfoKey (hKey
, NULL
, NULL
, NULL
, NULL
, &maxlen
, NULL
, NULL
,
203 NULL
, NULL
, NULL
, NULL
) != ERROR_SUCCESS
)
208 namebuf
= XNEWVEC (char, ++maxlen
);
209 foundbuf
= XNEWVEC (char, maxlen
);
211 if (!namebuf
|| !foundbuf
)
219 /* Look through all of the keys for one that begins with Minimal GNU...
220 Try to get the latest version by doing a string compare although that
221 string never really works with version number sorting. */
222 for (i
= 0; RegEnumKey (hKey
, i
, namebuf
, maxlen
) == ERROR_SUCCESS
; i
++)
224 int match
= strcasecmp (namebuf
, MINGW_NAME
);
227 if (match
> 0 && strncasecmp (namebuf
, MINGW_NAME
, MINGW_NAME_LEN
) > 0)
229 if (strcasecmp (namebuf
, foundbuf
) > 0)
230 strcpy (foundbuf
, namebuf
);
234 /* If foundbuf is empty, we didn't find anything. Punt. */
242 /* Open the key that we wanted */
243 res
= RegOpenKey (hKey
, foundbuf
, &hTmp
);
247 /* Don't know why this would fail, but you gotta check */
248 if (res
!= ERROR_SUCCESS
)
252 /* Get the length of the value pointed to by InstallLocation */
253 if (RegQueryValueEx (hTmp
, "InstallLocation", 0, NULL
, NULL
,
254 &maxlen
) != ERROR_SUCCESS
|| maxlen
== 0)
260 /* Allocate space for the install location */
261 foundbuf
= XNEWVEC (char, maxlen
+ strlen (executable
));
268 /* Read the install location into the buffer */
269 res
= RegQueryValueEx (hTmp
, "InstallLocation", 0, NULL
, (LPBYTE
) foundbuf
,
272 if (res
!= ERROR_SUCCESS
)
278 /* Concatenate the install location and the executable, turn all slashes
279 to backslashes, and return that. */
280 return tack_on_executable (foundbuf
, executable
);
283 /* Read the install location of msys from it's installation file and
284 rootify the executable based on that. */
286 msys_rootify (const char *executable
)
289 size_t execlen
= strlen (executable
) + 1;
294 buf
= XNEWVEC (char, bufsize
+ execlen
);
297 res
= GetPrivateProfileString ("InstallSettings", "InstallPath", NULL
,
298 buf
, bufsize
, "msys.ini");
301 if (strlen (buf
) < bufsize
)
314 return tack_on_executable (buf
, executable
);
322 /* Return the number of arguments in an argv array, not including the null
323 terminating argument. */
326 argv_to_argc (char *const *argv
)
328 char *const *i
= argv
;
334 /* Return a Windows command-line from ARGV. It is the caller's
335 responsibility to free the string returned. */
338 argv_to_cmdline (char *const *argv
)
347 for (i
= 0; argv
[i
]; i
++)
349 /* We only quote arguments that contain spaces, \t or " characters to
350 prevent wasting 2 chars per argument of the CreateProcess 32k char
351 limit. We need only escape embedded double-quotes and immediately
352 preceeding backslash characters. A sequence of backslach characters
353 that is not follwed by a double quote character will not be
356 for (j
= 0; argv
[i
][j
]; j
++)
358 if (argv
[i
][j
] == ' ' || argv
[i
][j
] == '\t' || argv
[i
][j
] == '"')
363 if (argv
[i
][j
] == '"')
365 /* Escape preceeding backslashes. */
366 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
368 /* Escape the qote character. */
374 /* Trailing backslashes also need to be escaped because they will be
375 followed by the terminating quote. */
378 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
382 /* for leading and trailing quotes and space */
383 cmdline_len
+= needs_quotes
* 2 + 1;
385 cmdline
= XNEWVEC (char, cmdline_len
);
387 for (i
= 0; argv
[i
]; i
++)
390 for (j
= 0; argv
[i
][j
]; j
++)
392 if (argv
[i
][j
] == ' ' || argv
[i
][j
] == '\t' || argv
[i
][j
] == '"')
405 for (j
= 0; argv
[i
][j
]; j
++)
407 if (argv
[i
][j
] == '"')
409 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
417 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
427 /* We'll try the passed filename with all the known standard
428 extensions, and then without extension. We try no extension
429 last so that we don't try to run some random extension-less
430 file that might be hanging around. We try both extension
431 and no extension so that we don't need any fancy logic
432 to determine if a file has extension. */
433 static const char *const
443 /* Returns the full path to PROGRAM. If SEARCH is true, look for
444 PROGRAM in each directory in PATH. */
447 find_executable (const char *program
, BOOL search
)
449 char *full_executable
;
452 const char *path
= 0;
453 const char *const *ext
;
455 size_t proglen
= strlen (program
);
456 int has_slash
= (strchr (program
, '/') || strchr (program
, '\\'));
463 path
= getenv ("PATH");
468 for (p
= path
; *p
; p
= q
)
471 while (*q
!= ';' && *q
!= '\0')
473 if ((size_t)(q
- p
) > fe_len
)
478 fe_len
= fe_len
+ 1 + proglen
+ 5 /* space for extension */;
479 full_executable
= XNEWVEC (char, fe_len
);
485 while (*q
!= ';' && *q
!= '\0')
489 memcpy (e
, p
, q
- p
);
498 for (e
= full_executable
; *e
; e
++)
502 /* At this point, e points to the terminating NUL character for
504 for (ext
= std_suffixes
; *ext
; ext
++)
506 /* Remove any current extension. */
508 /* Add the new one. */
509 strcat (full_executable
, *ext
);
511 /* Attempt to open this file. */
512 h
= CreateFile (full_executable
, GENERIC_READ
,
513 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
514 0, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
515 if (h
!= INVALID_HANDLE_VALUE
)
521 free (full_executable
);
526 return full_executable
;
529 /* Low-level process creation function and helper. */
532 env_compare (const void *a_ptr
, const void *b_ptr
)
539 a
= *(const char **) a_ptr
;
540 b
= *(const char **) b_ptr
;
542 /* a and b will be of the form: VAR=VALUE
543 We compare only the variable name part here using a case-insensitive
544 comparison algorithm. It might appear that in fact strcasecmp () can
545 take the place of this whole function, and indeed it could, save for
546 the fact that it would fail in cases such as comparing A1=foo and
547 A=bar (because 1 is less than = in the ASCII character set).
548 (Environment variables containing no numbers would work in such a
553 c1
= (unsigned char) tolower (*a
++);
554 c2
= (unsigned char) tolower (*b
++);
562 while (c1
== c2
&& c1
!= '\0');
567 /* Execute a Windows executable as a child process. This will fail if the
568 * target is not actually an executable, such as if it is a shell script. */
571 win32_spawn (const char *executable
,
574 char *const *env
, /* array of strings of the form: VAR=VALUE */
575 DWORD dwCreationFlags
,
577 LPPROCESS_INFORMATION pi
)
579 char *full_executable
;
582 char *env_block
= NULL
;
584 full_executable
= NULL
;
591 /* Count the number of environment bindings supplied. */
592 for (env_size
= 0; env
[env_size
]; env_size
++)
595 /* Assemble an environment block, if required. This consists of
596 VAR=VALUE strings juxtaposed (with one null character between each
597 pair) and an additional null at the end. */
601 int total_size
= 1; /* 1 is for the final null. */
604 /* Windows needs the members of the block to be sorted by variable
606 env_copy
= (char **) alloca (sizeof (char *) * env_size
);
607 memcpy (env_copy
, env
, sizeof (char *) * env_size
);
608 qsort (env_copy
, env_size
, sizeof (char *), env_compare
);
610 for (var
= 0; var
< env_size
; var
++)
611 total_size
+= strlen (env
[var
]) + 1;
613 env_block
= XNEWVEC (char, total_size
);
615 for (var
= 0; var
< env_size
; var
++)
616 bufptr
= stpcpy (bufptr
, env_copy
[var
]) + 1;
622 full_executable
= find_executable (executable
, search
);
623 if (!full_executable
)
625 cmdline
= argv_to_cmdline (argv
);
629 /* Create the child process. */
630 if (!CreateProcess (full_executable
, cmdline
,
631 /*lpProcessAttributes=*/NULL
,
632 /*lpThreadAttributes=*/NULL
,
633 /*bInheritHandles=*/TRUE
,
636 /*lpCurrentDirectory=*/NULL
,
642 free (full_executable
);
648 CloseHandle (pi
->hThread
);
649 free (full_executable
);
652 return (pid_t
) pi
->hProcess
;
657 free (full_executable
);
662 /* Spawn a script. This simulates the Unix script execution mechanism.
663 This function is called as a fallback if win32_spawn fails. */
666 spawn_script (const char *executable
, char *const *argv
,
668 DWORD dwCreationFlags
,
670 LPPROCESS_INFORMATION pi
)
672 pid_t pid
= (pid_t
) -1;
673 int save_errno
= errno
;
674 int fd
= _open (executable
, _O_RDONLY
);
676 /* Try to open script, check header format, extract interpreter path,
677 and spawn script using that interpretter. */
680 char buf
[MAX_PATH
+ 5];
681 int len
= _read (fd
, buf
, sizeof (buf
) - 1);
687 eol
= strchr (buf
, '\n');
688 if (eol
&& strncmp (buf
, "#!", 2) == 0)
691 /* Header format is OK. */
696 /* Extract interpreter path. */
699 while (*--eol
== '\r' || *eol
== ' ' || *eol
== '\t');
700 for (executable1
= buf
+ 2; *executable1
== ' ' || *executable1
== '\t'; executable1
++)
702 backslashify (executable1
);
704 /* Duplicate argv, prepending the interpreter path. */
705 new_argc
= argv_to_argc (argv
) + 1;
706 avhere
= XNEWVEC (const char *, new_argc
+ 1);
707 *avhere
= executable1
;
708 memcpy (avhere
+ 1, argv
, new_argc
* sizeof(*argv
));
709 argv
= (char *const *)avhere
;
711 /* Spawn the child. */
712 #ifndef USE_MINGW_MSYS
713 executable
= strrchr (executable1
, '\\') + 1;
715 executable
= executable1
;
716 pid
= win32_spawn (executable
, TRUE
, argv
, env
,
717 dwCreationFlags
, si
, pi
);
719 if (strchr (executable1
, '\\') == NULL
)
720 pid
= win32_spawn (executable1
, TRUE
, argv
, env
,
721 dwCreationFlags
, si
, pi
);
722 else if (executable1
[0] != '\\')
723 pid
= win32_spawn (executable1
, FALSE
, argv
, env
,
724 dwCreationFlags
, si
, pi
);
727 const char *newex
= mingw_rootify (executable1
);
729 pid
= win32_spawn (newex
, FALSE
, argv
, env
,
730 dwCreationFlags
, si
, pi
);
731 if (executable1
!= newex
)
732 free ((char *) newex
);
733 if (pid
== (pid_t
) -1)
735 newex
= msys_rootify (executable1
);
736 if (newex
!= executable1
)
739 pid
= win32_spawn (newex
, FALSE
, argv
, env
,
740 dwCreationFlags
, si
, pi
);
741 free ((char *) newex
);
750 if (pid
== (pid_t
) -1)
755 /* Execute a child. */
758 pex_win32_exec_child (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int flags
,
759 const char *executable
, char * const * argv
,
761 int in
, int out
, int errdes
,
762 int toclose ATTRIBUTE_UNUSED
,
768 HANDLE stdout_handle
;
769 HANDLE stderr_handle
;
770 DWORD dwCreationFlags
;
771 OSVERSIONINFO version_info
;
773 PROCESS_INFORMATION pi
;
774 int orig_out
, orig_in
, orig_err
;
775 BOOL separate_stderr
= !(flags
& PEX_STDERR_TO_STDOUT
);
777 /* Ensure we have inheritable descriptors to pass to the child. */
782 out
= _dup (orig_out
);
787 errdes
= _dup (orig_err
);
790 stdin_handle
= INVALID_HANDLE_VALUE
;
791 stdout_handle
= INVALID_HANDLE_VALUE
;
792 stderr_handle
= INVALID_HANDLE_VALUE
;
794 stdin_handle
= (HANDLE
) _get_osfhandle (in
);
795 stdout_handle
= (HANDLE
) _get_osfhandle (out
);
797 stderr_handle
= (HANDLE
) _get_osfhandle (errdes
);
799 stderr_handle
= stdout_handle
;
801 /* Determine the version of Windows we are running on. */
802 version_info
.dwOSVersionInfoSize
= sizeof (version_info
);
803 GetVersionEx (&version_info
);
804 if (version_info
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
)
805 /* On Windows 95/98/ME the CREATE_NO_WINDOW flag is not
806 supported, so we cannot avoid creating a console window. */
810 HANDLE conout_handle
;
812 /* Determine whether or not we have an associated console. */
813 conout_handle
= CreateFile("CONOUT$",
816 /*lpSecurityAttributes=*/NULL
,
818 FILE_ATTRIBUTE_NORMAL
,
819 /*hTemplateFile=*/NULL
);
820 if (conout_handle
== INVALID_HANDLE_VALUE
)
821 /* There is no console associated with this process. Since
822 the child is a console process, the OS would normally
823 create a new console Window for the child. Since we'll be
824 redirecting the child's standard streams, we do not need
825 the console window. */
826 dwCreationFlags
= CREATE_NO_WINDOW
;
829 /* There is a console associated with the process, so the OS
830 will not create a new console. And, if we use
831 CREATE_NO_WINDOW in this situation, the child will have
832 no associated console. Therefore, if the child's
833 standard streams are connected to the console, the output
834 will be discarded. */
835 CloseHandle(conout_handle
);
840 /* Since the child will be a console process, it will, by default,
841 connect standard input/output to its console. However, we want
842 the child to use the handles specifically designated above. In
843 addition, if there is no console (such as when we are running in
844 a Cygwin X window), then we must redirect the child's
845 input/output, as there is no console for the child to use. */
846 memset (&si
, 0, sizeof (si
));
848 si
.dwFlags
= STARTF_USESTDHANDLES
;
849 si
.hStdInput
= stdin_handle
;
850 si
.hStdOutput
= stdout_handle
;
851 si
.hStdError
= stderr_handle
;
853 /* Create the child process. */
854 pid
= win32_spawn (executable
, (flags
& PEX_SEARCH
) != 0,
855 argv
, env
, dwCreationFlags
, &si
, &pi
);
856 if (pid
== (pid_t
) -1)
857 pid
= spawn_script (executable
, argv
, env
, dwCreationFlags
,
859 if (pid
== (pid_t
) -1)
862 *errmsg
= "CreateProcess";
865 /* If the child was created successfully, close the original file
866 descriptors. If the process creation fails, these are closed by
867 pex_run_in_environment instead. We must not close them twice as
868 that seems to cause a Windows exception. */
870 if (pid
!= (pid_t
) -1)
872 if (orig_in
!= STDIN_FILENO
)
874 if (orig_out
!= STDOUT_FILENO
)
877 && orig_err
!= STDERR_FILENO
)
881 /* Close the standard input, standard output and standard error handles
892 /* Wait for a child process to complete. MS CRTDLL doesn't return
893 enough information in status to decide if the child exited due to a
894 signal or not, rather it simply returns an integer with the exit
895 code of the child; eg., if the child exited with an abort() call
896 and didn't have a handler for SIGABRT, it simply returns with
897 status == 3. We fix the status code to conform to the usual WIF*
898 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
901 pex_win32_wait (struct pex_obj
*obj ATTRIBUTE_UNUSED
, pid_t pid
,
902 int *status
, struct pex_time
*time
, int done ATTRIBUTE_UNUSED
,
903 const char **errmsg
, int *err
)
909 memset (time
, 0, sizeof *time
);
913 /* FIXME: If done is non-zero, we should probably try to kill the
915 if (WaitForSingleObject (h
, INFINITE
) != WAIT_OBJECT_0
)
919 *errmsg
= "WaitForSingleObject";
923 GetExitCodeProcess (h
, &termstat
);
926 /* A value of 3 indicates that the child caught a signal, but not
927 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
932 *status
= (termstat
& 0xff) << 8;
940 pex_win32_pipe (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int *p
,
943 return _pipe (p
, 256, (binary
? _O_BINARY
: _O_TEXT
) | _O_NOINHERIT
);
946 /* Get a FILE pointer to read from a file descriptor. */
949 pex_win32_fdopenr (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
,
952 HANDLE h
= (HANDLE
) _get_osfhandle (fd
);
953 if (h
== INVALID_HANDLE_VALUE
)
955 if (! SetHandleInformation (h
, HANDLE_FLAG_INHERIT
, 0))
957 return fdopen (fd
, binary
? "rb" : "r");
961 pex_win32_fdopenw (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
,
964 HANDLE h
= (HANDLE
) _get_osfhandle (fd
);
965 if (h
== INVALID_HANDLE_VALUE
)
967 if (! SetHandleInformation (h
, HANDLE_FLAG_INHERIT
, 0))
969 return fdopen (fd
, binary
? "wb" : "w");
976 main (int argc ATTRIBUTE_UNUSED
, char **argv
)
981 printf ("%ld\n", (long) pex_win32_exec_child (NULL
, PEX_SEARCH
, argv
[0], argv
, NULL
, 0, 0, 1, 2, &errmsg
, &err
));