]> git.ipfire.org Git - thirdparty/gcc.git/blame - libiberty/pex-win32.c
RISC-V: Support RVV FP16 ZVFH floating-point intrinsic API
[thirdparty/gcc.git] / libiberty / pex-win32.c
CommitLineData
55d0e5e0
ZW
1/* Utilities to execute a program in a subprocess (possibly linked by pipes
2 with other subprocesses), and wait for it. Generic Win32 specialization.
83ffe9cd 3 Copyright (C) 1996-2023 Free Software Foundation, Inc.
55d0e5e0
ZW
4
5This file is part of the libiberty library.
6Libiberty is free software; you can redistribute it and/or
7modify it under the terms of the GNU Library General Public
8License as published by the Free Software Foundation; either
9version 2 of the License, or (at your option) any later version.
10
11Libiberty is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14Library General Public License for more details.
15
16You should have received a copy of the GNU Library General Public
17License along with libiberty; see the file COPYING.LIB. If not,
ee58dffd
NC
18write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
19Boston, MA 02110-1301, USA. */
55d0e5e0
ZW
20
21#include "pex-common.h"
22
902c7559 23#define WIN32_LEAN_AND_MEAN
0d676b85
CF
24#include <windows.h>
25
a584cf65
ILT
26#ifdef HAVE_STDLIB_H
27#include <stdlib.h>
28#endif
55d0e5e0
ZW
29#ifdef HAVE_STRING_H
30#include <string.h>
31#endif
32#ifdef HAVE_UNISTD_H
33#include <unistd.h>
34#endif
35#ifdef HAVE_SYS_WAIT_H
36#include <sys/wait.h>
37#endif
38
ea60341e 39#include <assert.h>
55d0e5e0
ZW
40#include <process.h>
41#include <io.h>
42#include <fcntl.h>
43#include <signal.h>
a584cf65 44#include <sys/stat.h>
bd9e7c5c 45#include <errno.h>
ea60341e 46#include <ctype.h>
55d0e5e0
ZW
47
48/* mingw32 headers may not define the following. */
49
50#ifndef _P_WAIT
51# define _P_WAIT 0
52# define _P_NOWAIT 1
53# define _P_OVERLAY 2
54# define _P_NOWAITO 3
55# define _P_DETACH 4
56
57# define WAIT_CHILD 0
58# define WAIT_GRANDCHILD 1
59#endif
60
0d676b85
CF
61#define MINGW_NAME "Minimalist GNU for Windows"
62#define MINGW_NAME_LEN (sizeof(MINGW_NAME) - 1)
63
ea60341e
MS
64extern char *stpcpy (char *dst, const char *src);
65
0d676b85
CF
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. */
72static void
73backslashify (char *s)
74{
75 while ((s = strchr (s, '/')) != NULL)
76 *s = '\\';
77 return;
78}
79
a584cf65 80static int pex_win32_open_read (struct pex_obj *, const char *, int);
29ce50b0 81static int pex_win32_open_write (struct pex_obj *, const char *, int, int);
1651030c 82static pid_t pex_win32_exec_child (struct pex_obj *, int, const char *,
ea60341e 83 char * const *, char * const *,
5317e1c7 84 int, int, int, int,
a584cf65
ILT
85 const char **, int *);
86static int pex_win32_close (struct pex_obj *, int);
92c3e704 87static pid_t pex_win32_wait (struct pex_obj *, pid_t, int *,
a584cf65
ILT
88 struct pex_time *, int, const char **, int *);
89static int pex_win32_pipe (struct pex_obj *, int *, int);
90static FILE *pex_win32_fdopenr (struct pex_obj *, int, int);
8eff378c 91static FILE *pex_win32_fdopenw (struct pex_obj *, int, int);
a584cf65
ILT
92
93/* The list of functions we pass to the common routines. */
94
95const struct pex_funcs funcs =
55d0e5e0 96{
a584cf65
ILT
97 pex_win32_open_read,
98 pex_win32_open_write,
99 pex_win32_exec_child,
100 pex_win32_close,
101 pex_win32_wait,
102 pex_win32_pipe,
103 pex_win32_fdopenr,
8eff378c 104 pex_win32_fdopenw,
a584cf65
ILT
105 NULL /* cleanup */
106};
107
108/* Return a newly initialized pex_obj structure. */
109
110struct pex_obj *
111pex_init (int flags, const char *pname, const char *tempbase)
112{
113 return pex_init_common (flags, pname, tempbase, &funcs);
114}
115
116/* Open a file for reading. */
117
118static int
119pex_win32_open_read (struct pex_obj *obj ATTRIBUTE_UNUSED, const char *name,
120 int binary)
121{
122 return _open (name, _O_RDONLY | (binary ? _O_BINARY : _O_TEXT));
123}
124
125/* Open a file for writing. */
126
127static int
128pex_win32_open_write (struct pex_obj *obj ATTRIBUTE_UNUSED, const char *name,
29ce50b0 129 int binary, int append)
a584cf65
ILT
130{
131 /* Note that we can't use O_EXCL here because gcc may have already
132 created the temporary file via make_temp_file. */
29ce50b0
MO
133 if (append)
134 return -1;
a584cf65
ILT
135 return _open (name,
136 (_O_WRONLY | _O_CREAT | _O_TRUNC
137 | (binary ? _O_BINARY : _O_TEXT)),
138 _S_IREAD | _S_IWRITE);
139}
140
141/* Close a file. */
142
143static int
144pex_win32_close (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd)
145{
146 return _close (fd);
147}
148
0d676b85
CF
149#ifdef USE_MINGW_MSYS
150static const char *mingw_keys[] = {"SOFTWARE", "Microsoft", "Windows", "CurrentVersion", "Uninstall", NULL};
151
152/* Tack the executable on the end of a (possibly slash terminated) buffer
153 and convert everything to \. */
154static const char *
155tack_on_executable (char *buf, const char *executable)
156{
157 char *p = strchr (buf, '\0');
158 if (p > buf && (p[-1] == '\\' || p[-1] == '/'))
159 p[-1] = '\0';
160 backslashify (strcat (buf, executable));
161 return buf;
162}
163
164/* Walk down a registry hierarchy until the end. Return the key. */
165static HKEY
166openkey (HKEY hStart, const char *keys[])
167{
168 HKEY hKey, hTmp;
169 for (hKey = hStart; *keys; keys++)
170 {
171 LONG res;
172 hTmp = hKey;
173 res = RegOpenKey (hTmp, *keys, &hKey);
174
175 if (hTmp != HKEY_LOCAL_MACHINE)
176 RegCloseKey (hTmp);
177
178 if (res != ERROR_SUCCESS)
179 return NULL;
180 }
181 return hKey;
182}
183
184/* Return the "mingw root" as derived from the mingw uninstall information. */
185static const char *
186mingw_rootify (const char *executable)
187{
188 HKEY hKey, hTmp;
189 DWORD maxlen;
190 char *namebuf, *foundbuf;
191 DWORD i;
192 LONG res;
193
194 /* Open the uninstall "directory". */
195 hKey = openkey (HKEY_LOCAL_MACHINE, mingw_keys);
196
197 /* Not found. */
198 if (!hKey)
199 return executable;
200
201 /* Need to enumerate all of the keys here looking for one the most recent
202 one for MinGW. */
203 if (RegQueryInfoKey (hKey, NULL, NULL, NULL, NULL, &maxlen, NULL, NULL,
204 NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
205 {
206 RegCloseKey (hKey);
207 return executable;
208 }
209 namebuf = XNEWVEC (char, ++maxlen);
210 foundbuf = XNEWVEC (char, maxlen);
211 foundbuf[0] = '\0';
212 if (!namebuf || !foundbuf)
213 {
214 RegCloseKey (hKey);
04695783
JM
215 free (namebuf);
216 free (foundbuf);
0d676b85
CF
217 return executable;
218 }
219
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++)
224 {
225 int match = strcasecmp (namebuf, MINGW_NAME);
226 if (match < 0)
227 continue;
228 if (match > 0 && strncasecmp (namebuf, MINGW_NAME, MINGW_NAME_LEN) > 0)
229 continue;
230 if (strcasecmp (namebuf, foundbuf) > 0)
231 strcpy (foundbuf, namebuf);
232 }
233 free (namebuf);
234
235 /* If foundbuf is empty, we didn't find anything. Punt. */
236 if (!foundbuf[0])
237 {
238 free (foundbuf);
239 RegCloseKey (hKey);
240 return executable;
241 }
242
243 /* Open the key that we wanted */
244 res = RegOpenKey (hKey, foundbuf, &hTmp);
245 RegCloseKey (hKey);
246 free (foundbuf);
247
248 /* Don't know why this would fail, but you gotta check */
249 if (res != ERROR_SUCCESS)
250 return executable;
251
252 maxlen = 0;
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)
256 {
257 RegCloseKey (hTmp);
258 return executable;
259 }
260
261 /* Allocate space for the install location */
262 foundbuf = XNEWVEC (char, maxlen + strlen (executable));
263 if (!foundbuf)
264 {
265 free (foundbuf);
266 RegCloseKey (hTmp);
267 }
268
269 /* Read the install location into the buffer */
270 res = RegQueryValueEx (hTmp, "InstallLocation", 0, NULL, (LPBYTE) foundbuf,
271 &maxlen);
272 RegCloseKey (hTmp);
273 if (res != ERROR_SUCCESS)
274 {
275 free (foundbuf);
276 return executable;
277 }
278
279 /* Concatenate the install location and the executable, turn all slashes
280 to backslashes, and return that. */
281 return tack_on_executable (foundbuf, executable);
282}
283
284/* Read the install location of msys from it's installation file and
285 rootify the executable based on that. */
286static const char *
287msys_rootify (const char *executable)
288{
289 size_t bufsize = 64;
290 size_t execlen = strlen (executable) + 1;
291 char *buf;
292 DWORD res = 0;
293 for (;;)
294 {
295 buf = XNEWVEC (char, bufsize + execlen);
296 if (!buf)
297 break;
298 res = GetPrivateProfileString ("InstallSettings", "InstallPath", NULL,
299 buf, bufsize, "msys.ini");
300 if (!res)
301 break;
302 if (strlen (buf) < bufsize)
303 break;
304 res = 0;
305 free (buf);
306 bufsize *= 2;
307 if (bufsize > 65536)
308 {
309 buf = NULL;
310 break;
311 }
312 }
313
314 if (res)
315 return tack_on_executable (buf, executable);
316
317 /* failed */
04695783 318 free (buf);
0d676b85
CF
319 return executable;
320}
321#endif
322
98b45309
AL
323/* Return the number of arguments in an argv array, not including the null
324 terminating argument. */
325
326static int
327argv_to_argc (char *const *argv)
328{
329 char *const *i = argv;
330 while (*i)
331 i++;
332 return i - argv;
333}
334
bd9e7c5c
MM
335/* Return a Windows command-line from ARGV. It is the caller's
336 responsibility to free the string returned. */
337
338static char *
339argv_to_cmdline (char *const *argv)
340{
341 char *cmdline;
342 char *p;
343 size_t cmdline_len;
344 int i, j, k;
ad484eca 345 int needs_quotes;
bd9e7c5c
MM
346
347 cmdline_len = 0;
348 for (i = 0; argv[i]; i++)
349 {
ad484eca
RD
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
bd9e7c5c
MM
353 preceeding backslash characters. A sequence of backslach characters
354 that is not follwed by a double quote character will not be
355 escaped. */
ad484eca 356 needs_quotes = 0;
bd9e7c5c
MM
357 for (j = 0; argv[i][j]; j++)
358 {
ad484eca
RD
359 if (argv[i][j] == ' ' || argv[i][j] == '\t' || argv[i][j] == '"')
360 {
361 needs_quotes = 1;
362 }
363
bd9e7c5c
MM
364 if (argv[i][j] == '"')
365 {
366 /* Escape preceeding backslashes. */
367 for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
368 cmdline_len++;
369 /* Escape the qote character. */
370 cmdline_len++;
371 }
372 }
471a0d47
AS
373 if (j == 0)
374 needs_quotes = 1;
bd9e7c5c
MM
375 /* Trailing backslashes also need to be escaped because they will be
376 followed by the terminating quote. */
ad484eca
RD
377 if (needs_quotes)
378 {
379 for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
380 cmdline_len++;
381 }
bd9e7c5c 382 cmdline_len += j;
ad484eca
RD
383 /* for leading and trailing quotes and space */
384 cmdline_len += needs_quotes * 2 + 1;
bd9e7c5c 385 }
7445de0a 386 cmdline = XNEWVEC (char, cmdline_len);
bd9e7c5c
MM
387 p = cmdline;
388 for (i = 0; argv[i]; i++)
389 {
ad484eca
RD
390 needs_quotes = 0;
391 for (j = 0; argv[i][j]; j++)
392 {
393 if (argv[i][j] == ' ' || argv[i][j] == '\t' || argv[i][j] == '"')
394 {
395 needs_quotes = 1;
396 break;
397 }
398 }
471a0d47
AS
399 if (j == 0)
400 needs_quotes = 1;
ad484eca
RD
401
402 if (needs_quotes)
403 {
404 *p++ = '"';
405 }
bd9e7c5c
MM
406 for (j = 0; argv[i][j]; j++)
407 {
408 if (argv[i][j] == '"')
409 {
410 for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
411 *p++ = '\\';
412 *p++ = '\\';
413 }
414 *p++ = argv[i][j];
415 }
ad484eca
RD
416 if (needs_quotes)
417 {
418 for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
419 *p++ = '\\';
420 *p++ = '"';
421 }
bd9e7c5c
MM
422 *p++ = ' ';
423 }
424 p[-1] = '\0';
425 return cmdline;
426}
427
e9903c67
VP
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. */
bd9e7c5c
MM
434static const char *const
435std_suffixes[] = {
436 ".com",
437 ".exe",
438 ".bat",
439 ".cmd",
bd9e7c5c
MM
440 "",
441 0
442};
443
444/* Returns the full path to PROGRAM. If SEARCH is true, look for
445 PROGRAM in each directory in PATH. */
446
447static char *
448find_executable (const char *program, BOOL search)
449{
450 char *full_executable;
451 char *e;
452 size_t fe_len;
453 const char *path = 0;
454 const char *const *ext;
455 const char *p, *q;
456 size_t proglen = strlen (program);
bd9e7c5c
MM
457 int has_slash = (strchr (program, '/') || strchr (program, '\\'));
458 HANDLE h;
459
460 if (has_slash)
461 search = FALSE;
462
463 if (search)
464 path = getenv ("PATH");
465 if (!path)
466 path = "";
467
468 fe_len = 0;
469 for (p = path; *p; p = q)
470 {
471 q = p;
472 while (*q != ';' && *q != '\0')
473 q++;
474 if ((size_t)(q - p) > fe_len)
475 fe_len = q - p;
476 if (*q == ';')
477 q++;
478 }
e9903c67 479 fe_len = fe_len + 1 + proglen + 5 /* space for extension */;
7445de0a 480 full_executable = XNEWVEC (char, fe_len);
bd9e7c5c
MM
481
482 p = path;
483 do
484 {
485 q = p;
486 while (*q != ';' && *q != '\0')
487 q++;
488
489 e = full_executable;
490 memcpy (e, p, q - p);
491 e += (q - p);
492 if (q - p)
493 *e++ = '\\';
494 strcpy (e, program);
495
496 if (*q == ';')
497 q++;
498
499 for (e = full_executable; *e; e++)
500 if (*e == '/')
501 *e = '\\';
502
503 /* At this point, e points to the terminating NUL character for
504 full_executable. */
e9903c67 505 for (ext = std_suffixes; *ext; ext++)
bd9e7c5c
MM
506 {
507 /* Remove any current extension. */
508 *e = '\0';
509 /* Add the new one. */
510 strcat (full_executable, *ext);
511
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)
517 goto found;
518 }
519 p = q;
520 }
521 while (*p);
522 free (full_executable);
523 return 0;
524
525 found:
526 CloseHandle (h);
527 return full_executable;
528}
529
ea60341e
MS
530/* Low-level process creation function and helper. */
531
532static int
533env_compare (const void *a_ptr, const void *b_ptr)
534{
535 const char *a;
536 const char *b;
537 unsigned char c1;
538 unsigned char c2;
539
540 a = *(const char **) a_ptr;
541 b = *(const char **) b_ptr;
542
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
550 scenario.) */
551
552 do
553 {
554 c1 = (unsigned char) tolower (*a++);
555 c2 = (unsigned char) tolower (*b++);
556
557 if (c1 == '=')
558 c1 = '\0';
559
560 if (c2 == '=')
561 c2 = '\0';
562 }
563 while (c1 == c2 && c1 != '\0');
564
565 return c1 - c2;
566}
bd9e7c5c 567
98b45309
AL
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. */
570
1651030c 571static pid_t
180ebb8a
CA
572win32_spawn (struct pex_obj *obj,
573 const char *executable,
bd9e7c5c
MM
574 BOOL search,
575 char *const *argv,
ea60341e 576 char *const *env, /* array of strings of the form: VAR=VALUE */
bd9e7c5c
MM
577 DWORD dwCreationFlags,
578 LPSTARTUPINFO si,
579 LPPROCESS_INFORMATION pi)
580{
59bc2b68
CA
581 char *full_executable = NULL;
582 char *cmdline = NULL;
583 pid_t pid = (pid_t) -1;
ea60341e
MS
584 char **env_copy;
585 char *env_block = NULL;
bd9e7c5c 586
ea60341e
MS
587 if (env)
588 {
589 int env_size;
590
591 /* Count the number of environment bindings supplied. */
592 for (env_size = 0; env[env_size]; env_size++)
593 continue;
594
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. */
598 if (env_size > 0)
599 {
600 int var;
601 int total_size = 1; /* 1 is for the final null. */
602 char *bufptr;
603
604 /* Windows needs the members of the block to be sorted by variable
605 name. */
7445de0a 606 env_copy = (char **) alloca (sizeof (char *) * env_size);
ea60341e
MS
607 memcpy (env_copy, env, sizeof (char *) * env_size);
608 qsort (env_copy, env_size, sizeof (char *), env_compare);
609
610 for (var = 0; var < env_size; var++)
611 total_size += strlen (env[var]) + 1;
612
7445de0a 613 env_block = XNEWVEC (char, total_size);
ea60341e
MS
614 bufptr = env_block;
615 for (var = 0; var < env_size; var++)
616 bufptr = stpcpy (bufptr, env_copy[var]) + 1;
617
618 *bufptr = '\0';
619 }
620 }
621
bd9e7c5c
MM
622 full_executable = find_executable (executable, search);
623 if (!full_executable)
59bc2b68 624 goto exit;
bd9e7c5c
MM
625 cmdline = argv_to_cmdline (argv);
626 if (!cmdline)
59bc2b68 627 goto exit;
180ebb8a
CA
628 /* If cmdline is too large, CreateProcess will fail with a bad
629 'No such file or directory' error. Try passing it through a
630 temporary response file instead. */
631 if (strlen (cmdline) > 32767)
632 {
633 char *response_file = make_temp_file ("");
634 /* Register the file for deletion by pex_free. */
635 ++obj->remove_count;
636 obj->remove = XRESIZEVEC (char *, obj->remove, obj->remove_count);
637 obj->remove[obj->remove_count - 1] = response_file;
638 int fd = pex_win32_open_write (obj, response_file, 0, 0);
639 if (fd == -1)
640 goto exit;
641 FILE *f = pex_win32_fdopenw (obj, fd, 0);
642 /* Don't write argv[0] (program name) to the response file. */
643 if (writeargv (&argv[1], f))
644 {
645 fclose (f);
646 goto exit;
647 }
648 fclose (f); /* Also closes fd and the underlying OS handle. */
649 char *response_arg = concat ("@", response_file, NULL);
650 char *response_argv[3] = {argv[0], response_arg, NULL};
651 free (cmdline);
652 cmdline = argv_to_cmdline (response_argv);
653 free (response_arg);
654 if (!cmdline)
655 goto exit;
656 }
657
658 /* Create the child process. */
59bc2b68 659 if (CreateProcess (full_executable, cmdline,
bd9e7c5c
MM
660 /*lpProcessAttributes=*/NULL,
661 /*lpThreadAttributes=*/NULL,
662 /*bInheritHandles=*/TRUE,
663 dwCreationFlags,
ea60341e 664 (LPVOID) env_block,
bd9e7c5c
MM
665 /*lpCurrentDirectory=*/NULL,
666 si,
667 pi))
668 {
59bc2b68
CA
669 CloseHandle (pi->hThread);
670 pid = (pid_t) pi->hProcess;
bd9e7c5c
MM
671 }
672
59bc2b68 673 exit:
bd9e7c5c 674 /* Clean up. */
04695783
JM
675 free (env_block);
676 free (cmdline);
677 free (full_executable);
180ebb8a 678
59bc2b68 679 return pid;
bd9e7c5c
MM
680}
681
98b45309
AL
682/* Spawn a script. This simulates the Unix script execution mechanism.
683 This function is called as a fallback if win32_spawn fails. */
684
1651030c 685static pid_t
180ebb8a
CA
686spawn_script (struct pex_obj *obj,
687 const char *executable, char *const *argv,
ea60341e 688 char* const *env,
bd9e7c5c
MM
689 DWORD dwCreationFlags,
690 LPSTARTUPINFO si,
691 LPPROCESS_INFORMATION pi)
0d676b85 692{
1651030c 693 pid_t pid = (pid_t) -1;
0d676b85
CF
694 int save_errno = errno;
695 int fd = _open (executable, _O_RDONLY);
696
98b45309
AL
697 /* Try to open script, check header format, extract interpreter path,
698 and spawn script using that interpretter. */
0d676b85
CF
699 if (fd >= 0)
700 {
701 char buf[MAX_PATH + 5];
702 int len = _read (fd, buf, sizeof (buf) - 1);
703 _close (fd);
704 if (len > 3)
705 {
706 char *eol;
707 buf[len] = '\0';
708 eol = strchr (buf, '\n');
709 if (eol && strncmp (buf, "#!", 2) == 0)
710 {
98b45309
AL
711
712 /* Header format is OK. */
0d676b85 713 char *executable1;
98b45309
AL
714 int new_argc;
715 const char **avhere;
716
717 /* Extract interpreter path. */
0d676b85
CF
718 do
719 *eol = '\0';
720 while (*--eol == '\r' || *eol == ' ' || *eol == '\t');
721 for (executable1 = buf + 2; *executable1 == ' ' || *executable1 == '\t'; executable1++)
722 continue;
0d676b85 723 backslashify (executable1);
98b45309
AL
724
725 /* Duplicate argv, prepending the interpreter path. */
726 new_argc = argv_to_argc (argv) + 1;
727 avhere = XNEWVEC (const char *, new_argc + 1);
0d676b85 728 *avhere = executable1;
98b45309
AL
729 memcpy (avhere + 1, argv, new_argc * sizeof(*argv));
730 argv = (char *const *)avhere;
731
732 /* Spawn the child. */
0d676b85
CF
733#ifndef USE_MINGW_MSYS
734 executable = strrchr (executable1, '\\') + 1;
735 if (!executable)
736 executable = executable1;
180ebb8a 737 pid = win32_spawn (obj, executable, TRUE, argv, env,
bd9e7c5c 738 dwCreationFlags, si, pi);
0d676b85
CF
739#else
740 if (strchr (executable1, '\\') == NULL)
180ebb8a 741 pid = win32_spawn (obj, executable1, TRUE, argv, env,
bd9e7c5c 742 dwCreationFlags, si, pi);
0d676b85 743 else if (executable1[0] != '\\')
180ebb8a 744 pid = win32_spawn (obj, executable1, FALSE, argv, env,
bd9e7c5c 745 dwCreationFlags, si, pi);
0d676b85
CF
746 else
747 {
748 const char *newex = mingw_rootify (executable1);
749 *avhere = newex;
180ebb8a 750 pid = win32_spawn (obj, newex, FALSE, argv, env,
bd9e7c5c 751 dwCreationFlags, si, pi);
0d676b85
CF
752 if (executable1 != newex)
753 free ((char *) newex);
92c3e704 754 if (pid == (pid_t) -1)
0d676b85
CF
755 {
756 newex = msys_rootify (executable1);
757 if (newex != executable1)
758 {
759 *avhere = newex;
180ebb8a 760 pid = win32_spawn (obj, newex, FALSE, argv, env,
bd9e7c5c 761 dwCreationFlags, si, pi);
0d676b85
CF
762 free ((char *) newex);
763 }
764 }
765 }
766#endif
98b45309 767 free (avhere);
0d676b85
CF
768 }
769 }
770 }
92c3e704 771 if (pid == (pid_t) -1)
0d676b85
CF
772 errno = save_errno;
773 return pid;
774}
775
a584cf65
ILT
776/* Execute a child. */
777
1651030c 778static pid_t
180ebb8a 779pex_win32_exec_child (struct pex_obj *obj, int flags,
a584cf65 780 const char *executable, char * const * argv,
ea60341e 781 char* const* env,
5317e1c7
ILT
782 int in, int out, int errdes,
783 int toclose ATTRIBUTE_UNUSED,
784 const char **errmsg,
a584cf65
ILT
785 int *err)
786{
1651030c 787 pid_t pid;
bd9e7c5c
MM
788 HANDLE stdin_handle;
789 HANDLE stdout_handle;
790 HANDLE stderr_handle;
791 DWORD dwCreationFlags;
792 OSVERSIONINFO version_info;
793 STARTUPINFO si;
794 PROCESS_INFORMATION pi;
946b73c1 795 int orig_out, orig_in, orig_err = 0;
6874160d
JB
796 BOOL separate_stderr = !(flags & PEX_STDERR_TO_STDOUT);
797
9cd6dd82 798 /* Ensure we have inheritable descriptors to pass to the child. */
6874160d
JB
799 orig_in = in;
800 in = _dup (orig_in);
6874160d
JB
801
802 orig_out = out;
803 out = _dup (orig_out);
6874160d
JB
804
805 if (separate_stderr)
806 {
807 orig_err = errdes;
808 errdes = _dup (orig_err);
6874160d 809 }
bd9e7c5c
MM
810
811 stdin_handle = INVALID_HANDLE_VALUE;
812 stdout_handle = INVALID_HANDLE_VALUE;
813 stderr_handle = INVALID_HANDLE_VALUE;
814
815 stdin_handle = (HANDLE) _get_osfhandle (in);
816 stdout_handle = (HANDLE) _get_osfhandle (out);
6874160d 817 if (separate_stderr)
bd9e7c5c
MM
818 stderr_handle = (HANDLE) _get_osfhandle (errdes);
819 else
820 stderr_handle = stdout_handle;
821
822 /* Determine the version of Windows we are running on. */
823 version_info.dwOSVersionInfoSize = sizeof (version_info);
824 GetVersionEx (&version_info);
825 if (version_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
826 /* On Windows 95/98/ME the CREATE_NO_WINDOW flag is not
827 supported, so we cannot avoid creating a console window. */
828 dwCreationFlags = 0;
829 else
55d0e5e0 830 {
bd9e7c5c
MM
831 HANDLE conout_handle;
832
833 /* Determine whether or not we have an associated console. */
834 conout_handle = CreateFile("CONOUT$",
835 GENERIC_WRITE,
836 FILE_SHARE_WRITE,
837 /*lpSecurityAttributes=*/NULL,
838 OPEN_EXISTING,
839 FILE_ATTRIBUTE_NORMAL,
840 /*hTemplateFile=*/NULL);
841 if (conout_handle == INVALID_HANDLE_VALUE)
842 /* There is no console associated with this process. Since
843 the child is a console process, the OS would normally
844 create a new console Window for the child. Since we'll be
845 redirecting the child's standard streams, we do not need
846 the console window. */
847 dwCreationFlags = CREATE_NO_WINDOW;
848 else
a584cf65 849 {
bd9e7c5c
MM
850 /* There is a console associated with the process, so the OS
851 will not create a new console. And, if we use
852 CREATE_NO_WINDOW in this situation, the child will have
853 no associated console. Therefore, if the child's
854 standard streams are connected to the console, the output
855 will be discarded. */
856 CloseHandle(conout_handle);
857 dwCreationFlags = 0;
a584cf65 858 }
55d0e5e0
ZW
859 }
860
bd9e7c5c
MM
861 /* Since the child will be a console process, it will, by default,
862 connect standard input/output to its console. However, we want
863 the child to use the handles specifically designated above. In
864 addition, if there is no console (such as when we are running in
865 a Cygwin X window), then we must redirect the child's
866 input/output, as there is no console for the child to use. */
867 memset (&si, 0, sizeof (si));
868 si.cb = sizeof (si);
869 si.dwFlags = STARTF_USESTDHANDLES;
870 si.hStdInput = stdin_handle;
871 si.hStdOutput = stdout_handle;
872 si.hStdError = stderr_handle;
873
874 /* Create the child process. */
180ebb8a 875 pid = win32_spawn (obj, executable, (flags & PEX_SEARCH) != 0,
ea60341e 876 argv, env, dwCreationFlags, &si, &pi);
1651030c 877 if (pid == (pid_t) -1)
180ebb8a 878 pid = spawn_script (obj, executable, argv, env, dwCreationFlags,
ea60341e 879 &si, &pi);
1651030c 880 if (pid == (pid_t) -1)
55d0e5e0 881 {
bd9e7c5c
MM
882 *err = ENOENT;
883 *errmsg = "CreateProcess";
55d0e5e0
ZW
884 }
885
9cd6dd82
KH
886 /* If the child was created successfully, close the original file
887 descriptors. If the process creation fails, these are closed by
888 pex_run_in_environment instead. We must not close them twice as
889 that seems to cause a Windows exception. */
890
891 if (pid != (pid_t) -1)
892 {
893 if (orig_in != STDIN_FILENO)
894 _close (orig_in);
895 if (orig_out != STDOUT_FILENO)
896 _close (orig_out);
897 if (separate_stderr
898 && orig_err != STDERR_FILENO)
899 _close (orig_err);
900 }
901
6874160d
JB
902 /* Close the standard input, standard output and standard error handles
903 in the parent. */
904
965cc3c3
JB
905 _close (in);
906 _close (out);
907 if (separate_stderr)
6874160d 908 _close (errdes);
55d0e5e0
ZW
909
910 return pid;
911}
912
a584cf65
ILT
913/* Wait for a child process to complete. MS CRTDLL doesn't return
914 enough information in status to decide if the child exited due to a
915 signal or not, rather it simply returns an integer with the exit
916 code of the child; eg., if the child exited with an abort() call
917 and didn't have a handler for SIGABRT, it simply returns with
918 status == 3. We fix the status code to conform to the usual WIF*
919 macros. Note that WIFSIGNALED will never be true under CRTDLL. */
920
92c3e704 921static pid_t
1651030c 922pex_win32_wait (struct pex_obj *obj ATTRIBUTE_UNUSED, pid_t pid,
a584cf65
ILT
923 int *status, struct pex_time *time, int done ATTRIBUTE_UNUSED,
924 const char **errmsg, int *err)
55d0e5e0 925{
bd9e7c5c
MM
926 DWORD termstat;
927 HANDLE h;
55d0e5e0 928
a584cf65
ILT
929 if (time != NULL)
930 memset (time, 0, sizeof *time);
931
bd9e7c5c
MM
932 h = (HANDLE) pid;
933
a584cf65
ILT
934 /* FIXME: If done is non-zero, we should probably try to kill the
935 process. */
bd9e7c5c 936 if (WaitForSingleObject (h, INFINITE) != WAIT_OBJECT_0)
a584cf65 937 {
bd9e7c5c
MM
938 CloseHandle (h);
939 *err = ECHILD;
940 *errmsg = "WaitForSingleObject";
a584cf65
ILT
941 return -1;
942 }
55d0e5e0 943
bd9e7c5c
MM
944 GetExitCodeProcess (h, &termstat);
945 CloseHandle (h);
946
947 /* A value of 3 indicates that the child caught a signal, but not
948 which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
949 report SIGABRT. */
55d0e5e0
ZW
950 if (termstat == 3)
951 *status = SIGABRT;
952 else
bd9e7c5c 953 *status = (termstat & 0xff) << 8;
55d0e5e0 954
a584cf65
ILT
955 return 0;
956}
957
958/* Create a pipe. */
959
960static int
961pex_win32_pipe (struct pex_obj *obj ATTRIBUTE_UNUSED, int *p,
962 int binary)
963{
6874160d 964 return _pipe (p, 256, (binary ? _O_BINARY : _O_TEXT) | _O_NOINHERIT);
a584cf65
ILT
965}
966
967/* Get a FILE pointer to read from a file descriptor. */
968
969static FILE *
970pex_win32_fdopenr (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd,
971 int binary)
972{
bb870b58
KT
973 HANDLE h = (HANDLE) _get_osfhandle (fd);
974 if (h == INVALID_HANDLE_VALUE)
975 return NULL;
976 if (! SetHandleInformation (h, HANDLE_FLAG_INHERIT, 0))
977 return NULL;
a584cf65 978 return fdopen (fd, binary ? "rb" : "r");
55d0e5e0 979}
0d676b85 980
8eff378c
JB
981static FILE *
982pex_win32_fdopenw (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd,
983 int binary)
984{
985 HANDLE h = (HANDLE) _get_osfhandle (fd);
986 if (h == INVALID_HANDLE_VALUE)
987 return NULL;
988 if (! SetHandleInformation (h, HANDLE_FLAG_INHERIT, 0))
989 return NULL;
990 return fdopen (fd, binary ? "wb" : "w");
991}
992
0d676b85
CF
993#ifdef MAIN
994#include <stdio.h>
995
996int
997main (int argc ATTRIBUTE_UNUSED, char **argv)
998{
999 char const *errmsg;
1000 int err;
1001 argv++;
1651030c 1002 printf ("%ld\n", (long) pex_win32_exec_child (NULL, PEX_SEARCH, argv[0], argv, NULL, 0, 0, 1, 2, &errmsg, &err));
0d676b85
CF
1003 exit (0);
1004}
1005#endif