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-2023 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"
23 #define WIN32_LEAN_AND_MEAN
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, int);
82 static pid_t
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 pid_t
pex_win32_wait (struct pex_obj
*, pid_t
, 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
,
129 int binary
, int append
)
131 /* Note that we can't use O_EXCL here because gcc may have already
132 created the temporary file via make_temp_file. */
136 (_O_WRONLY
| _O_CREAT
| _O_TRUNC
137 | (binary
? _O_BINARY
: _O_TEXT
)),
138 _S_IREAD
| _S_IWRITE
);
144 pex_win32_close (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
)
149 #ifdef USE_MINGW_MSYS
150 static const char *mingw_keys
[] = {"SOFTWARE", "Microsoft", "Windows", "CurrentVersion", "Uninstall", NULL
};
152 /* Tack the executable on the end of a (possibly slash terminated) buffer
153 and convert everything to \. */
155 tack_on_executable (char *buf
, const char *executable
)
157 char *p
= strchr (buf
, '\0');
158 if (p
> buf
&& (p
[-1] == '\\' || p
[-1] == '/'))
160 backslashify (strcat (buf
, executable
));
164 /* Walk down a registry hierarchy until the end. Return the key. */
166 openkey (HKEY hStart
, const char *keys
[])
169 for (hKey
= hStart
; *keys
; keys
++)
173 res
= RegOpenKey (hTmp
, *keys
, &hKey
);
175 if (hTmp
!= HKEY_LOCAL_MACHINE
)
178 if (res
!= ERROR_SUCCESS
)
184 /* Return the "mingw root" as derived from the mingw uninstall information. */
186 mingw_rootify (const char *executable
)
190 char *namebuf
, *foundbuf
;
194 /* Open the uninstall "directory". */
195 hKey
= openkey (HKEY_LOCAL_MACHINE
, mingw_keys
);
201 /* Need to enumerate all of the keys here looking for one the most recent
203 if (RegQueryInfoKey (hKey
, NULL
, NULL
, NULL
, NULL
, &maxlen
, NULL
, NULL
,
204 NULL
, NULL
, NULL
, NULL
) != ERROR_SUCCESS
)
209 namebuf
= XNEWVEC (char, ++maxlen
);
210 foundbuf
= XNEWVEC (char, maxlen
);
212 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
);
323 /* Return the number of arguments in an argv array, not including the null
324 terminating argument. */
327 argv_to_argc (char *const *argv
)
329 char *const *i
= argv
;
335 /* Return a Windows command-line from ARGV. It is the caller's
336 responsibility to free the string returned. */
339 argv_to_cmdline (char *const *argv
)
348 for (i
= 0; argv
[i
]; i
++)
350 /* We only quote arguments that contain spaces, \t or " characters to
351 prevent wasting 2 chars per argument of the CreateProcess 32k char
352 limit. We need only escape embedded double-quotes and immediately
353 preceeding backslash characters. A sequence of backslach characters
354 that is not follwed by a double quote character will not be
357 for (j
= 0; argv
[i
][j
]; j
++)
359 if (argv
[i
][j
] == ' ' || argv
[i
][j
] == '\t' || argv
[i
][j
] == '"')
364 if (argv
[i
][j
] == '"')
366 /* Escape preceeding backslashes. */
367 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
369 /* Escape the qote character. */
375 /* Trailing backslashes also need to be escaped because they will be
376 followed by the terminating quote. */
379 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
383 /* for leading and trailing quotes and space */
384 cmdline_len
+= needs_quotes
* 2 + 1;
386 cmdline
= XNEWVEC (char, cmdline_len
);
388 for (i
= 0; argv
[i
]; i
++)
391 for (j
= 0; argv
[i
][j
]; j
++)
393 if (argv
[i
][j
] == ' ' || argv
[i
][j
] == '\t' || argv
[i
][j
] == '"')
406 for (j
= 0; argv
[i
][j
]; j
++)
408 if (argv
[i
][j
] == '"')
410 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
418 for (k
= j
- 1; k
>= 0 && argv
[i
][k
] == '\\'; k
--)
428 /* We'll try the passed filename with all the known standard
429 extensions, and then without extension. We try no extension
430 last so that we don't try to run some random extension-less
431 file that might be hanging around. We try both extension
432 and no extension so that we don't need any fancy logic
433 to determine if a file has extension. */
434 static const char *const
444 /* Returns the full path to PROGRAM. If SEARCH is true, look for
445 PROGRAM in each directory in PATH. */
448 find_executable (const char *program
, BOOL search
)
450 char *full_executable
;
453 const char *path
= 0;
454 const char *const *ext
;
456 size_t proglen
= strlen (program
);
457 int has_slash
= (strchr (program
, '/') || strchr (program
, '\\'));
464 path
= getenv ("PATH");
469 for (p
= path
; *p
; p
= q
)
472 while (*q
!= ';' && *q
!= '\0')
474 if ((size_t)(q
- p
) > fe_len
)
479 fe_len
= fe_len
+ 1 + proglen
+ 5 /* space for extension */;
480 full_executable
= XNEWVEC (char, fe_len
);
486 while (*q
!= ';' && *q
!= '\0')
490 memcpy (e
, p
, q
- p
);
499 for (e
= full_executable
; *e
; e
++)
503 /* At this point, e points to the terminating NUL character for
505 for (ext
= std_suffixes
; *ext
; ext
++)
507 /* Remove any current extension. */
509 /* Add the new one. */
510 strcat (full_executable
, *ext
);
512 /* Attempt to open this file. */
513 h
= CreateFile (full_executable
, GENERIC_READ
,
514 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
515 0, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
516 if (h
!= INVALID_HANDLE_VALUE
)
522 free (full_executable
);
527 return full_executable
;
530 /* Low-level process creation function and helper. */
533 env_compare (const void *a_ptr
, const void *b_ptr
)
540 a
= *(const char **) a_ptr
;
541 b
= *(const char **) b_ptr
;
543 /* a and b will be of the form: VAR=VALUE
544 We compare only the variable name part here using a case-insensitive
545 comparison algorithm. It might appear that in fact strcasecmp () can
546 take the place of this whole function, and indeed it could, save for
547 the fact that it would fail in cases such as comparing A1=foo and
548 A=bar (because 1 is less than = in the ASCII character set).
549 (Environment variables containing no numbers would work in such a
554 c1
= (unsigned char) tolower (*a
++);
555 c2
= (unsigned char) tolower (*b
++);
563 while (c1
== c2
&& c1
!= '\0');
568 /* Execute a Windows executable as a child process. This will fail if the
569 * target is not actually an executable, such as if it is a shell script. */
572 win32_spawn (const char *executable
,
575 char *const *env
, /* array of strings of the form: VAR=VALUE */
576 DWORD dwCreationFlags
,
578 LPPROCESS_INFORMATION pi
)
580 char *full_executable
= NULL
;
581 char *cmdline
= NULL
;
582 pid_t pid
= (pid_t
) -1;
584 char *env_block
= NULL
;
590 /* Count the number of environment bindings supplied. */
591 for (env_size
= 0; env
[env_size
]; env_size
++)
594 /* Assemble an environment block, if required. This consists of
595 VAR=VALUE strings juxtaposed (with one null character between each
596 pair) and an additional null at the end. */
600 int total_size
= 1; /* 1 is for the final null. */
603 /* Windows needs the members of the block to be sorted by variable
605 env_copy
= (char **) alloca (sizeof (char *) * env_size
);
606 memcpy (env_copy
, env
, sizeof (char *) * env_size
);
607 qsort (env_copy
, env_size
, sizeof (char *), env_compare
);
609 for (var
= 0; var
< env_size
; var
++)
610 total_size
+= strlen (env
[var
]) + 1;
612 env_block
= XNEWVEC (char, total_size
);
614 for (var
= 0; var
< env_size
; var
++)
615 bufptr
= stpcpy (bufptr
, env_copy
[var
]) + 1;
621 full_executable
= find_executable (executable
, search
);
622 if (!full_executable
)
624 cmdline
= argv_to_cmdline (argv
);
628 /* Create the child process. */
629 if (CreateProcess (full_executable
, cmdline
,
630 /*lpProcessAttributes=*/NULL
,
631 /*lpThreadAttributes=*/NULL
,
632 /*bInheritHandles=*/TRUE
,
635 /*lpCurrentDirectory=*/NULL
,
639 CloseHandle (pi
->hThread
);
640 pid
= (pid_t
) pi
->hProcess
;
647 free (full_executable
);
652 /* Spawn a script. This simulates the Unix script execution mechanism.
653 This function is called as a fallback if win32_spawn fails. */
656 spawn_script (const char *executable
, char *const *argv
,
658 DWORD dwCreationFlags
,
660 LPPROCESS_INFORMATION pi
)
662 pid_t pid
= (pid_t
) -1;
663 int save_errno
= errno
;
664 int fd
= _open (executable
, _O_RDONLY
);
666 /* Try to open script, check header format, extract interpreter path,
667 and spawn script using that interpretter. */
670 char buf
[MAX_PATH
+ 5];
671 int len
= _read (fd
, buf
, sizeof (buf
) - 1);
677 eol
= strchr (buf
, '\n');
678 if (eol
&& strncmp (buf
, "#!", 2) == 0)
681 /* Header format is OK. */
686 /* Extract interpreter path. */
689 while (*--eol
== '\r' || *eol
== ' ' || *eol
== '\t');
690 for (executable1
= buf
+ 2; *executable1
== ' ' || *executable1
== '\t'; executable1
++)
692 backslashify (executable1
);
694 /* Duplicate argv, prepending the interpreter path. */
695 new_argc
= argv_to_argc (argv
) + 1;
696 avhere
= XNEWVEC (const char *, new_argc
+ 1);
697 *avhere
= executable1
;
698 memcpy (avhere
+ 1, argv
, new_argc
* sizeof(*argv
));
699 argv
= (char *const *)avhere
;
701 /* Spawn the child. */
702 #ifndef USE_MINGW_MSYS
703 executable
= strrchr (executable1
, '\\') + 1;
705 executable
= executable1
;
706 pid
= win32_spawn (executable
, TRUE
, argv
, env
,
707 dwCreationFlags
, si
, pi
);
709 if (strchr (executable1
, '\\') == NULL
)
710 pid
= win32_spawn (executable1
, TRUE
, argv
, env
,
711 dwCreationFlags
, si
, pi
);
712 else if (executable1
[0] != '\\')
713 pid
= win32_spawn (executable1
, FALSE
, argv
, env
,
714 dwCreationFlags
, si
, pi
);
717 const char *newex
= mingw_rootify (executable1
);
719 pid
= win32_spawn (newex
, FALSE
, argv
, env
,
720 dwCreationFlags
, si
, pi
);
721 if (executable1
!= newex
)
722 free ((char *) newex
);
723 if (pid
== (pid_t
) -1)
725 newex
= msys_rootify (executable1
);
726 if (newex
!= executable1
)
729 pid
= win32_spawn (newex
, FALSE
, argv
, env
,
730 dwCreationFlags
, si
, pi
);
731 free ((char *) newex
);
740 if (pid
== (pid_t
) -1)
745 /* Execute a child. */
748 pex_win32_exec_child (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int flags
,
749 const char *executable
, char * const * argv
,
751 int in
, int out
, int errdes
,
752 int toclose ATTRIBUTE_UNUSED
,
758 HANDLE stdout_handle
;
759 HANDLE stderr_handle
;
760 DWORD dwCreationFlags
;
761 OSVERSIONINFO version_info
;
763 PROCESS_INFORMATION pi
;
764 int orig_out
, orig_in
, orig_err
= 0;
765 BOOL separate_stderr
= !(flags
& PEX_STDERR_TO_STDOUT
);
767 /* Ensure we have inheritable descriptors to pass to the child. */
772 out
= _dup (orig_out
);
777 errdes
= _dup (orig_err
);
780 stdin_handle
= INVALID_HANDLE_VALUE
;
781 stdout_handle
= INVALID_HANDLE_VALUE
;
782 stderr_handle
= INVALID_HANDLE_VALUE
;
784 stdin_handle
= (HANDLE
) _get_osfhandle (in
);
785 stdout_handle
= (HANDLE
) _get_osfhandle (out
);
787 stderr_handle
= (HANDLE
) _get_osfhandle (errdes
);
789 stderr_handle
= stdout_handle
;
791 /* Determine the version of Windows we are running on. */
792 version_info
.dwOSVersionInfoSize
= sizeof (version_info
);
793 GetVersionEx (&version_info
);
794 if (version_info
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
)
795 /* On Windows 95/98/ME the CREATE_NO_WINDOW flag is not
796 supported, so we cannot avoid creating a console window. */
800 HANDLE conout_handle
;
802 /* Determine whether or not we have an associated console. */
803 conout_handle
= CreateFile("CONOUT$",
806 /*lpSecurityAttributes=*/NULL
,
808 FILE_ATTRIBUTE_NORMAL
,
809 /*hTemplateFile=*/NULL
);
810 if (conout_handle
== INVALID_HANDLE_VALUE
)
811 /* There is no console associated with this process. Since
812 the child is a console process, the OS would normally
813 create a new console Window for the child. Since we'll be
814 redirecting the child's standard streams, we do not need
815 the console window. */
816 dwCreationFlags
= CREATE_NO_WINDOW
;
819 /* There is a console associated with the process, so the OS
820 will not create a new console. And, if we use
821 CREATE_NO_WINDOW in this situation, the child will have
822 no associated console. Therefore, if the child's
823 standard streams are connected to the console, the output
824 will be discarded. */
825 CloseHandle(conout_handle
);
830 /* Since the child will be a console process, it will, by default,
831 connect standard input/output to its console. However, we want
832 the child to use the handles specifically designated above. In
833 addition, if there is no console (such as when we are running in
834 a Cygwin X window), then we must redirect the child's
835 input/output, as there is no console for the child to use. */
836 memset (&si
, 0, sizeof (si
));
838 si
.dwFlags
= STARTF_USESTDHANDLES
;
839 si
.hStdInput
= stdin_handle
;
840 si
.hStdOutput
= stdout_handle
;
841 si
.hStdError
= stderr_handle
;
843 /* Create the child process. */
844 pid
= win32_spawn (executable
, (flags
& PEX_SEARCH
) != 0,
845 argv
, env
, dwCreationFlags
, &si
, &pi
);
846 if (pid
== (pid_t
) -1)
847 pid
= spawn_script (executable
, argv
, env
, dwCreationFlags
,
849 if (pid
== (pid_t
) -1)
852 *errmsg
= "CreateProcess";
855 /* If the child was created successfully, close the original file
856 descriptors. If the process creation fails, these are closed by
857 pex_run_in_environment instead. We must not close them twice as
858 that seems to cause a Windows exception. */
860 if (pid
!= (pid_t
) -1)
862 if (orig_in
!= STDIN_FILENO
)
864 if (orig_out
!= STDOUT_FILENO
)
867 && orig_err
!= STDERR_FILENO
)
871 /* Close the standard input, standard output and standard error handles
882 /* Wait for a child process to complete. MS CRTDLL doesn't return
883 enough information in status to decide if the child exited due to a
884 signal or not, rather it simply returns an integer with the exit
885 code of the child; eg., if the child exited with an abort() call
886 and didn't have a handler for SIGABRT, it simply returns with
887 status == 3. We fix the status code to conform to the usual WIF*
888 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
891 pex_win32_wait (struct pex_obj
*obj ATTRIBUTE_UNUSED
, pid_t pid
,
892 int *status
, struct pex_time
*time
, int done ATTRIBUTE_UNUSED
,
893 const char **errmsg
, int *err
)
899 memset (time
, 0, sizeof *time
);
903 /* FIXME: If done is non-zero, we should probably try to kill the
905 if (WaitForSingleObject (h
, INFINITE
) != WAIT_OBJECT_0
)
909 *errmsg
= "WaitForSingleObject";
913 GetExitCodeProcess (h
, &termstat
);
916 /* A value of 3 indicates that the child caught a signal, but not
917 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
922 *status
= (termstat
& 0xff) << 8;
930 pex_win32_pipe (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int *p
,
933 return _pipe (p
, 256, (binary
? _O_BINARY
: _O_TEXT
) | _O_NOINHERIT
);
936 /* Get a FILE pointer to read from a file descriptor. */
939 pex_win32_fdopenr (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
,
942 HANDLE h
= (HANDLE
) _get_osfhandle (fd
);
943 if (h
== INVALID_HANDLE_VALUE
)
945 if (! SetHandleInformation (h
, HANDLE_FLAG_INHERIT
, 0))
947 return fdopen (fd
, binary
? "rb" : "r");
951 pex_win32_fdopenw (struct pex_obj
*obj ATTRIBUTE_UNUSED
, int fd
,
954 HANDLE h
= (HANDLE
) _get_osfhandle (fd
);
955 if (h
== INVALID_HANDLE_VALUE
)
957 if (! SetHandleInformation (h
, HANDLE_FLAG_INHERIT
, 0))
959 return fdopen (fd
, binary
? "wb" : "w");
966 main (int argc ATTRIBUTE_UNUSED
, char **argv
)
971 printf ("%ld\n", (long) pex_win32_exec_child (NULL
, PEX_SEARCH
, argv
[0], argv
, NULL
, 0, 0, 1, 2, &errmsg
, &err
));