pex-win32.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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-2022 Free Software Foundation, Inc.
  4. This file is part of the libiberty library.
  5. Libiberty is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Library General Public
  7. License as published by the Free Software Foundation; either
  8. version 2 of the License, or (at your option) any later version.
  9. Libiberty is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Library General Public License for more details.
  13. You should have received a copy of the GNU Library General Public
  14. License along with libiberty; see the file COPYING.LIB. If not,
  15. write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
  16. Boston, MA 02110-1301, USA. */
  17. #include "pex-common.h"
  18. #include <windows.h>
  19. #ifdef HAVE_STDLIB_H
  20. #include <stdlib.h>
  21. #endif
  22. #ifdef HAVE_STRING_H
  23. #include <string.h>
  24. #endif
  25. #ifdef HAVE_UNISTD_H
  26. #include <unistd.h>
  27. #endif
  28. #ifdef HAVE_SYS_WAIT_H
  29. #include <sys/wait.h>
  30. #endif
  31. #include <assert.h>
  32. #include <process.h>
  33. #include <io.h>
  34. #include <fcntl.h>
  35. #include <signal.h>
  36. #include <sys/stat.h>
  37. #include <errno.h>
  38. #include <ctype.h>
  39. /* mingw32 headers may not define the following. */
  40. #ifndef _P_WAIT
  41. # define _P_WAIT 0
  42. # define _P_NOWAIT 1
  43. # define _P_OVERLAY 2
  44. # define _P_NOWAITO 3
  45. # define _P_DETACH 4
  46. # define WAIT_CHILD 0
  47. # define WAIT_GRANDCHILD 1
  48. #endif
  49. #define MINGW_NAME "Minimalist GNU for Windows"
  50. #define MINGW_NAME_LEN (sizeof(MINGW_NAME) - 1)
  51. extern char *stpcpy (char *dst, const char *src);
  52. /* Ensure that the executable pathname uses Win32 backslashes. This
  53. is not necessary on NT, but on W9x, forward slashes causes
  54. failure of spawn* and exec* functions (and probably any function
  55. that calls CreateProcess) *iff* the executable pathname (argv[0])
  56. is a quoted string. And quoting is necessary in case a pathname
  57. contains embedded white space. You can't win. */
  58. static void
  59. backslashify (char *s)
  60. {
  61. while ((s = strchr (s, '/')) != NULL)
  62. *s = '\\';
  63. return;
  64. }
  65. static int pex_win32_open_read (struct pex_obj *, const char *, int);
  66. static int pex_win32_open_write (struct pex_obj *, const char *, int, int);
  67. static pid_t pex_win32_exec_child (struct pex_obj *, int, const char *,
  68. char * const *, char * const *,
  69. int, int, int, int,
  70. const char **, int *);
  71. static int pex_win32_close (struct pex_obj *, int);
  72. static pid_t pex_win32_wait (struct pex_obj *, pid_t, int *,
  73. struct pex_time *, int, const char **, int *);
  74. static int pex_win32_pipe (struct pex_obj *, int *, int);
  75. static FILE *pex_win32_fdopenr (struct pex_obj *, int, int);
  76. static FILE *pex_win32_fdopenw (struct pex_obj *, int, int);
  77. /* The list of functions we pass to the common routines. */
  78. const struct pex_funcs funcs =
  79. {
  80. pex_win32_open_read,
  81. pex_win32_open_write,
  82. pex_win32_exec_child,
  83. pex_win32_close,
  84. pex_win32_wait,
  85. pex_win32_pipe,
  86. pex_win32_fdopenr,
  87. pex_win32_fdopenw,
  88. NULL /* cleanup */
  89. };
  90. /* Return a newly initialized pex_obj structure. */
  91. struct pex_obj *
  92. pex_init (int flags, const char *pname, const char *tempbase)
  93. {
  94. return pex_init_common (flags, pname, tempbase, &funcs);
  95. }
  96. /* Open a file for reading. */
  97. static int
  98. pex_win32_open_read (struct pex_obj *obj ATTRIBUTE_UNUSED, const char *name,
  99. int binary)
  100. {
  101. return _open (name, _O_RDONLY | (binary ? _O_BINARY : _O_TEXT));
  102. }
  103. /* Open a file for writing. */
  104. static int
  105. pex_win32_open_write (struct pex_obj *obj ATTRIBUTE_UNUSED, const char *name,
  106. int binary, int append)
  107. {
  108. /* Note that we can't use O_EXCL here because gcc may have already
  109. created the temporary file via make_temp_file. */
  110. if (append)
  111. return -1;
  112. return _open (name,
  113. (_O_WRONLY | _O_CREAT | _O_TRUNC
  114. | (binary ? _O_BINARY : _O_TEXT)),
  115. _S_IREAD | _S_IWRITE);
  116. }
  117. /* Close a file. */
  118. static int
  119. pex_win32_close (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd)
  120. {
  121. return _close (fd);
  122. }
  123. #ifdef USE_MINGW_MSYS
  124. static const char *mingw_keys[] = {"SOFTWARE", "Microsoft", "Windows", "CurrentVersion", "Uninstall", NULL};
  125. /* Tack the executable on the end of a (possibly slash terminated) buffer
  126. and convert everything to \. */
  127. static const char *
  128. tack_on_executable (char *buf, const char *executable)
  129. {
  130. char *p = strchr (buf, '\0');
  131. if (p > buf && (p[-1] == '\\' || p[-1] == '/'))
  132. p[-1] = '\0';
  133. backslashify (strcat (buf, executable));
  134. return buf;
  135. }
  136. /* Walk down a registry hierarchy until the end. Return the key. */
  137. static HKEY
  138. openkey (HKEY hStart, const char *keys[])
  139. {
  140. HKEY hKey, hTmp;
  141. for (hKey = hStart; *keys; keys++)
  142. {
  143. LONG res;
  144. hTmp = hKey;
  145. res = RegOpenKey (hTmp, *keys, &hKey);
  146. if (hTmp != HKEY_LOCAL_MACHINE)
  147. RegCloseKey (hTmp);
  148. if (res != ERROR_SUCCESS)
  149. return NULL;
  150. }
  151. return hKey;
  152. }
  153. /* Return the "mingw root" as derived from the mingw uninstall information. */
  154. static const char *
  155. mingw_rootify (const char *executable)
  156. {
  157. HKEY hKey, hTmp;
  158. DWORD maxlen;
  159. char *namebuf, *foundbuf;
  160. DWORD i;
  161. LONG res;
  162. /* Open the uninstall "directory". */
  163. hKey = openkey (HKEY_LOCAL_MACHINE, mingw_keys);
  164. /* Not found. */
  165. if (!hKey)
  166. return executable;
  167. /* Need to enumerate all of the keys here looking for one the most recent
  168. one for MinGW. */
  169. if (RegQueryInfoKey (hKey, NULL, NULL, NULL, NULL, &maxlen, NULL, NULL,
  170. NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
  171. {
  172. RegCloseKey (hKey);
  173. return executable;
  174. }
  175. namebuf = XNEWVEC (char, ++maxlen);
  176. foundbuf = XNEWVEC (char, maxlen);
  177. foundbuf[0] = '\0';
  178. if (!namebuf || !foundbuf)
  179. {
  180. RegCloseKey (hKey);
  181. free (namebuf);
  182. free (foundbuf);
  183. return executable;
  184. }
  185. /* Look through all of the keys for one that begins with Minimal GNU...
  186. Try to get the latest version by doing a string compare although that
  187. string never really works with version number sorting. */
  188. for (i = 0; RegEnumKey (hKey, i, namebuf, maxlen) == ERROR_SUCCESS; i++)
  189. {
  190. int match = strcasecmp (namebuf, MINGW_NAME);
  191. if (match < 0)
  192. continue;
  193. if (match > 0 && strncasecmp (namebuf, MINGW_NAME, MINGW_NAME_LEN) > 0)
  194. continue;
  195. if (strcasecmp (namebuf, foundbuf) > 0)
  196. strcpy (foundbuf, namebuf);
  197. }
  198. free (namebuf);
  199. /* If foundbuf is empty, we didn't find anything. Punt. */
  200. if (!foundbuf[0])
  201. {
  202. free (foundbuf);
  203. RegCloseKey (hKey);
  204. return executable;
  205. }
  206. /* Open the key that we wanted */
  207. res = RegOpenKey (hKey, foundbuf, &hTmp);
  208. RegCloseKey (hKey);
  209. free (foundbuf);
  210. /* Don't know why this would fail, but you gotta check */
  211. if (res != ERROR_SUCCESS)
  212. return executable;
  213. maxlen = 0;
  214. /* Get the length of the value pointed to by InstallLocation */
  215. if (RegQueryValueEx (hTmp, "InstallLocation", 0, NULL, NULL,
  216. &maxlen) != ERROR_SUCCESS || maxlen == 0)
  217. {
  218. RegCloseKey (hTmp);
  219. return executable;
  220. }
  221. /* Allocate space for the install location */
  222. foundbuf = XNEWVEC (char, maxlen + strlen (executable));
  223. if (!foundbuf)
  224. {
  225. free (foundbuf);
  226. RegCloseKey (hTmp);
  227. }
  228. /* Read the install location into the buffer */
  229. res = RegQueryValueEx (hTmp, "InstallLocation", 0, NULL, (LPBYTE) foundbuf,
  230. &maxlen);
  231. RegCloseKey (hTmp);
  232. if (res != ERROR_SUCCESS)
  233. {
  234. free (foundbuf);
  235. return executable;
  236. }
  237. /* Concatenate the install location and the executable, turn all slashes
  238. to backslashes, and return that. */
  239. return tack_on_executable (foundbuf, executable);
  240. }
  241. /* Read the install location of msys from it's installation file and
  242. rootify the executable based on that. */
  243. static const char *
  244. msys_rootify (const char *executable)
  245. {
  246. size_t bufsize = 64;
  247. size_t execlen = strlen (executable) + 1;
  248. char *buf;
  249. DWORD res = 0;
  250. for (;;)
  251. {
  252. buf = XNEWVEC (char, bufsize + execlen);
  253. if (!buf)
  254. break;
  255. res = GetPrivateProfileString ("InstallSettings", "InstallPath", NULL,
  256. buf, bufsize, "msys.ini");
  257. if (!res)
  258. break;
  259. if (strlen (buf) < bufsize)
  260. break;
  261. res = 0;
  262. free (buf);
  263. bufsize *= 2;
  264. if (bufsize > 65536)
  265. {
  266. buf = NULL;
  267. break;
  268. }
  269. }
  270. if (res)
  271. return tack_on_executable (buf, executable);
  272. /* failed */
  273. free (buf);
  274. return executable;
  275. }
  276. #endif
  277. /* Return the number of arguments in an argv array, not including the null
  278. terminating argument. */
  279. static int
  280. argv_to_argc (char *const *argv)
  281. {
  282. char *const *i = argv;
  283. while (*i)
  284. i++;
  285. return i - argv;
  286. }
  287. /* Return a Windows command-line from ARGV. It is the caller's
  288. responsibility to free the string returned. */
  289. static char *
  290. argv_to_cmdline (char *const *argv)
  291. {
  292. char *cmdline;
  293. char *p;
  294. size_t cmdline_len;
  295. int i, j, k;
  296. int needs_quotes;
  297. cmdline_len = 0;
  298. for (i = 0; argv[i]; i++)
  299. {
  300. /* We only quote arguments that contain spaces, \t or " characters to
  301. prevent wasting 2 chars per argument of the CreateProcess 32k char
  302. limit. We need only escape embedded double-quotes and immediately
  303. preceeding backslash characters. A sequence of backslach characters
  304. that is not follwed by a double quote character will not be
  305. escaped. */
  306. needs_quotes = 0;
  307. for (j = 0; argv[i][j]; j++)
  308. {
  309. if (argv[i][j] == ' ' || argv[i][j] == '\t' || argv[i][j] == '"')
  310. {
  311. needs_quotes = 1;
  312. }
  313. if (argv[i][j] == '"')
  314. {
  315. /* Escape preceeding backslashes. */
  316. for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
  317. cmdline_len++;
  318. /* Escape the qote character. */
  319. cmdline_len++;
  320. }
  321. }
  322. if (j == 0)
  323. needs_quotes = 1;
  324. /* Trailing backslashes also need to be escaped because they will be
  325. followed by the terminating quote. */
  326. if (needs_quotes)
  327. {
  328. for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
  329. cmdline_len++;
  330. }
  331. cmdline_len += j;
  332. /* for leading and trailing quotes and space */
  333. cmdline_len += needs_quotes * 2 + 1;
  334. }
  335. cmdline = XNEWVEC (char, cmdline_len);
  336. p = cmdline;
  337. for (i = 0; argv[i]; i++)
  338. {
  339. needs_quotes = 0;
  340. for (j = 0; argv[i][j]; j++)
  341. {
  342. if (argv[i][j] == ' ' || argv[i][j] == '\t' || argv[i][j] == '"')
  343. {
  344. needs_quotes = 1;
  345. break;
  346. }
  347. }
  348. if (j == 0)
  349. needs_quotes = 1;
  350. if (needs_quotes)
  351. {
  352. *p++ = '"';
  353. }
  354. for (j = 0; argv[i][j]; j++)
  355. {
  356. if (argv[i][j] == '"')
  357. {
  358. for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
  359. *p++ = '\\';
  360. *p++ = '\\';
  361. }
  362. *p++ = argv[i][j];
  363. }
  364. if (needs_quotes)
  365. {
  366. for (k = j - 1; k >= 0 && argv[i][k] == '\\'; k--)
  367. *p++ = '\\';
  368. *p++ = '"';
  369. }
  370. *p++ = ' ';
  371. }
  372. p[-1] = '\0';
  373. return cmdline;
  374. }
  375. /* We'll try the passed filename with all the known standard
  376. extensions, and then without extension. We try no extension
  377. last so that we don't try to run some random extension-less
  378. file that might be hanging around. We try both extension
  379. and no extension so that we don't need any fancy logic
  380. to determine if a file has extension. */
  381. static const char *const
  382. std_suffixes[] = {
  383. ".com",
  384. ".exe",
  385. ".bat",
  386. ".cmd",
  387. "",
  388. 0
  389. };
  390. /* Returns the full path to PROGRAM. If SEARCH is true, look for
  391. PROGRAM in each directory in PATH. */
  392. static char *
  393. find_executable (const char *program, BOOL search)
  394. {
  395. char *full_executable;
  396. char *e;
  397. size_t fe_len;
  398. const char *path = 0;
  399. const char *const *ext;
  400. const char *p, *q;
  401. size_t proglen = strlen (program);
  402. int has_slash = (strchr (program, '/') || strchr (program, '\\'));
  403. HANDLE h;
  404. if (has_slash)
  405. search = FALSE;
  406. if (search)
  407. path = getenv ("PATH");
  408. if (!path)
  409. path = "";
  410. fe_len = 0;
  411. for (p = path; *p; p = q)
  412. {
  413. q = p;
  414. while (*q != ';' && *q != '\0')
  415. q++;
  416. if ((size_t)(q - p) > fe_len)
  417. fe_len = q - p;
  418. if (*q == ';')
  419. q++;
  420. }
  421. fe_len = fe_len + 1 + proglen + 5 /* space for extension */;
  422. full_executable = XNEWVEC (char, fe_len);
  423. p = path;
  424. do
  425. {
  426. q = p;
  427. while (*q != ';' && *q != '\0')
  428. q++;
  429. e = full_executable;
  430. memcpy (e, p, q - p);
  431. e += (q - p);
  432. if (q - p)
  433. *e++ = '\\';
  434. strcpy (e, program);
  435. if (*q == ';')
  436. q++;
  437. for (e = full_executable; *e; e++)
  438. if (*e == '/')
  439. *e = '\\';
  440. /* At this point, e points to the terminating NUL character for
  441. full_executable. */
  442. for (ext = std_suffixes; *ext; ext++)
  443. {
  444. /* Remove any current extension. */
  445. *e = '\0';
  446. /* Add the new one. */
  447. strcat (full_executable, *ext);
  448. /* Attempt to open this file. */
  449. h = CreateFile (full_executable, GENERIC_READ,
  450. FILE_SHARE_READ | FILE_SHARE_WRITE,
  451. 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  452. if (h != INVALID_HANDLE_VALUE)
  453. goto found;
  454. }
  455. p = q;
  456. }
  457. while (*p);
  458. free (full_executable);
  459. return 0;
  460. found:
  461. CloseHandle (h);
  462. return full_executable;
  463. }
  464. /* Low-level process creation function and helper. */
  465. static int
  466. env_compare (const void *a_ptr, const void *b_ptr)
  467. {
  468. const char *a;
  469. const char *b;
  470. unsigned char c1;
  471. unsigned char c2;
  472. a = *(const char **) a_ptr;
  473. b = *(const char **) b_ptr;
  474. /* a and b will be of the form: VAR=VALUE
  475. We compare only the variable name part here using a case-insensitive
  476. comparison algorithm. It might appear that in fact strcasecmp () can
  477. take the place of this whole function, and indeed it could, save for
  478. the fact that it would fail in cases such as comparing A1=foo and
  479. A=bar (because 1 is less than = in the ASCII character set).
  480. (Environment variables containing no numbers would work in such a
  481. scenario.) */
  482. do
  483. {
  484. c1 = (unsigned char) tolower (*a++);
  485. c2 = (unsigned char) tolower (*b++);
  486. if (c1 == '=')
  487. c1 = '\0';
  488. if (c2 == '=')
  489. c2 = '\0';
  490. }
  491. while (c1 == c2 && c1 != '\0');
  492. return c1 - c2;
  493. }
  494. /* Execute a Windows executable as a child process. This will fail if the
  495. * target is not actually an executable, such as if it is a shell script. */
  496. static pid_t
  497. win32_spawn (const char *executable,
  498. BOOL search,
  499. char *const *argv,
  500. char *const *env, /* array of strings of the form: VAR=VALUE */
  501. DWORD dwCreationFlags,
  502. LPSTARTUPINFO si,
  503. LPPROCESS_INFORMATION pi)
  504. {
  505. char *full_executable;
  506. char *cmdline;
  507. char **env_copy;
  508. char *env_block = NULL;
  509. full_executable = NULL;
  510. cmdline = NULL;
  511. if (env)
  512. {
  513. int env_size;
  514. /* Count the number of environment bindings supplied. */
  515. for (env_size = 0; env[env_size]; env_size++)
  516. continue;
  517. /* Assemble an environment block, if required. This consists of
  518. VAR=VALUE strings juxtaposed (with one null character between each
  519. pair) and an additional null at the end. */
  520. if (env_size > 0)
  521. {
  522. int var;
  523. int total_size = 1; /* 1 is for the final null. */
  524. char *bufptr;
  525. /* Windows needs the members of the block to be sorted by variable
  526. name. */
  527. env_copy = (char **) alloca (sizeof (char *) * env_size);
  528. memcpy (env_copy, env, sizeof (char *) * env_size);
  529. qsort (env_copy, env_size, sizeof (char *), env_compare);
  530. for (var = 0; var < env_size; var++)
  531. total_size += strlen (env[var]) + 1;
  532. env_block = XNEWVEC (char, total_size);
  533. bufptr = env_block;
  534. for (var = 0; var < env_size; var++)
  535. bufptr = stpcpy (bufptr, env_copy[var]) + 1;
  536. *bufptr = '\0';
  537. }
  538. }
  539. full_executable = find_executable (executable, search);
  540. if (!full_executable)
  541. goto error;
  542. cmdline = argv_to_cmdline (argv);
  543. if (!cmdline)
  544. goto error;
  545. /* Create the child process. */
  546. if (!CreateProcess (full_executable, cmdline,
  547. /*lpProcessAttributes=*/NULL,
  548. /*lpThreadAttributes=*/NULL,
  549. /*bInheritHandles=*/TRUE,
  550. dwCreationFlags,
  551. (LPVOID) env_block,
  552. /*lpCurrentDirectory=*/NULL,
  553. si,
  554. pi))
  555. {
  556. free (env_block);
  557. free (full_executable);
  558. return (pid_t) -1;
  559. }
  560. /* Clean up. */
  561. CloseHandle (pi->hThread);
  562. free (full_executable);
  563. free (env_block);
  564. return (pid_t) pi->hProcess;
  565. error:
  566. free (env_block);
  567. free (cmdline);
  568. free (full_executable);
  569. return (pid_t) -1;
  570. }
  571. /* Spawn a script. This simulates the Unix script execution mechanism.
  572. This function is called as a fallback if win32_spawn fails. */
  573. static pid_t
  574. spawn_script (const char *executable, char *const *argv,
  575. char* const *env,
  576. DWORD dwCreationFlags,
  577. LPSTARTUPINFO si,
  578. LPPROCESS_INFORMATION pi)
  579. {
  580. pid_t pid = (pid_t) -1;
  581. int save_errno = errno;
  582. int fd = _open (executable, _O_RDONLY);
  583. /* Try to open script, check header format, extract interpreter path,
  584. and spawn script using that interpretter. */
  585. if (fd >= 0)
  586. {
  587. char buf[MAX_PATH + 5];
  588. int len = _read (fd, buf, sizeof (buf) - 1);
  589. _close (fd);
  590. if (len > 3)
  591. {
  592. char *eol;
  593. buf[len] = '\0';
  594. eol = strchr (buf, '\n');
  595. if (eol && strncmp (buf, "#!", 2) == 0)
  596. {
  597. /* Header format is OK. */
  598. char *executable1;
  599. int new_argc;
  600. const char **avhere;
  601. /* Extract interpreter path. */
  602. do
  603. *eol = '\0';
  604. while (*--eol == '\r' || *eol == ' ' || *eol == '\t');
  605. for (executable1 = buf + 2; *executable1 == ' ' || *executable1 == '\t'; executable1++)
  606. continue;
  607. backslashify (executable1);
  608. /* Duplicate argv, prepending the interpreter path. */
  609. new_argc = argv_to_argc (argv) + 1;
  610. avhere = XNEWVEC (const char *, new_argc + 1);
  611. *avhere = executable1;
  612. memcpy (avhere + 1, argv, new_argc * sizeof(*argv));
  613. argv = (char *const *)avhere;
  614. /* Spawn the child. */
  615. #ifndef USE_MINGW_MSYS
  616. executable = strrchr (executable1, '\\') + 1;
  617. if (!executable)
  618. executable = executable1;
  619. pid = win32_spawn (executable, TRUE, argv, env,
  620. dwCreationFlags, si, pi);
  621. #else
  622. if (strchr (executable1, '\\') == NULL)
  623. pid = win32_spawn (executable1, TRUE, argv, env,
  624. dwCreationFlags, si, pi);
  625. else if (executable1[0] != '\\')
  626. pid = win32_spawn (executable1, FALSE, argv, env,
  627. dwCreationFlags, si, pi);
  628. else
  629. {
  630. const char *newex = mingw_rootify (executable1);
  631. *avhere = newex;
  632. pid = win32_spawn (newex, FALSE, argv, env,
  633. dwCreationFlags, si, pi);
  634. if (executable1 != newex)
  635. free ((char *) newex);
  636. if (pid == (pid_t) -1)
  637. {
  638. newex = msys_rootify (executable1);
  639. if (newex != executable1)
  640. {
  641. *avhere = newex;
  642. pid = win32_spawn (newex, FALSE, argv, env,
  643. dwCreationFlags, si, pi);
  644. free ((char *) newex);
  645. }
  646. }
  647. }
  648. #endif
  649. free (avhere);
  650. }
  651. }
  652. }
  653. if (pid == (pid_t) -1)
  654. errno = save_errno;
  655. return pid;
  656. }
  657. /* Execute a child. */
  658. static pid_t
  659. pex_win32_exec_child (struct pex_obj *obj ATTRIBUTE_UNUSED, int flags,
  660. const char *executable, char * const * argv,
  661. char* const* env,
  662. int in, int out, int errdes,
  663. int toclose ATTRIBUTE_UNUSED,
  664. const char **errmsg,
  665. int *err)
  666. {
  667. pid_t pid;
  668. HANDLE stdin_handle;
  669. HANDLE stdout_handle;
  670. HANDLE stderr_handle;
  671. DWORD dwCreationFlags;
  672. OSVERSIONINFO version_info;
  673. STARTUPINFO si;
  674. PROCESS_INFORMATION pi;
  675. int orig_out, orig_in, orig_err = 0;
  676. BOOL separate_stderr = !(flags & PEX_STDERR_TO_STDOUT);
  677. /* Ensure we have inheritable descriptors to pass to the child. */
  678. orig_in = in;
  679. in = _dup (orig_in);
  680. orig_out = out;
  681. out = _dup (orig_out);
  682. if (separate_stderr)
  683. {
  684. orig_err = errdes;
  685. errdes = _dup (orig_err);
  686. }
  687. stdin_handle = INVALID_HANDLE_VALUE;
  688. stdout_handle = INVALID_HANDLE_VALUE;
  689. stderr_handle = INVALID_HANDLE_VALUE;
  690. stdin_handle = (HANDLE) _get_osfhandle (in);
  691. stdout_handle = (HANDLE) _get_osfhandle (out);
  692. if (separate_stderr)
  693. stderr_handle = (HANDLE) _get_osfhandle (errdes);
  694. else
  695. stderr_handle = stdout_handle;
  696. /* Determine the version of Windows we are running on. */
  697. version_info.dwOSVersionInfoSize = sizeof (version_info);
  698. GetVersionEx (&version_info);
  699. if (version_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  700. /* On Windows 95/98/ME the CREATE_NO_WINDOW flag is not
  701. supported, so we cannot avoid creating a console window. */
  702. dwCreationFlags = 0;
  703. else
  704. {
  705. HANDLE conout_handle;
  706. /* Determine whether or not we have an associated console. */
  707. conout_handle = CreateFile("CONOUT$",
  708. GENERIC_WRITE,
  709. FILE_SHARE_WRITE,
  710. /*lpSecurityAttributes=*/NULL,
  711. OPEN_EXISTING,
  712. FILE_ATTRIBUTE_NORMAL,
  713. /*hTemplateFile=*/NULL);
  714. if (conout_handle == INVALID_HANDLE_VALUE)
  715. /* There is no console associated with this process. Since
  716. the child is a console process, the OS would normally
  717. create a new console Window for the child. Since we'll be
  718. redirecting the child's standard streams, we do not need
  719. the console window. */
  720. dwCreationFlags = CREATE_NO_WINDOW;
  721. else
  722. {
  723. /* There is a console associated with the process, so the OS
  724. will not create a new console. And, if we use
  725. CREATE_NO_WINDOW in this situation, the child will have
  726. no associated console. Therefore, if the child's
  727. standard streams are connected to the console, the output
  728. will be discarded. */
  729. CloseHandle(conout_handle);
  730. dwCreationFlags = 0;
  731. }
  732. }
  733. /* Since the child will be a console process, it will, by default,
  734. connect standard input/output to its console. However, we want
  735. the child to use the handles specifically designated above. In
  736. addition, if there is no console (such as when we are running in
  737. a Cygwin X window), then we must redirect the child's
  738. input/output, as there is no console for the child to use. */
  739. memset (&si, 0, sizeof (si));
  740. si.cb = sizeof (si);
  741. si.dwFlags = STARTF_USESTDHANDLES;
  742. si.hStdInput = stdin_handle;
  743. si.hStdOutput = stdout_handle;
  744. si.hStdError = stderr_handle;
  745. /* Create the child process. */
  746. pid = win32_spawn (executable, (flags & PEX_SEARCH) != 0,
  747. argv, env, dwCreationFlags, &si, &pi);
  748. if (pid == (pid_t) -1)
  749. pid = spawn_script (executable, argv, env, dwCreationFlags,
  750. &si, &pi);
  751. if (pid == (pid_t) -1)
  752. {
  753. *err = ENOENT;
  754. *errmsg = "CreateProcess";
  755. }
  756. /* If the child was created successfully, close the original file
  757. descriptors. If the process creation fails, these are closed by
  758. pex_run_in_environment instead. We must not close them twice as
  759. that seems to cause a Windows exception. */
  760. if (pid != (pid_t) -1)
  761. {
  762. if (orig_in != STDIN_FILENO)
  763. _close (orig_in);
  764. if (orig_out != STDOUT_FILENO)
  765. _close (orig_out);
  766. if (separate_stderr
  767. && orig_err != STDERR_FILENO)
  768. _close (orig_err);
  769. }
  770. /* Close the standard input, standard output and standard error handles
  771. in the parent. */
  772. _close (in);
  773. _close (out);
  774. if (separate_stderr)
  775. _close (errdes);
  776. return pid;
  777. }
  778. /* Wait for a child process to complete. MS CRTDLL doesn't return
  779. enough information in status to decide if the child exited due to a
  780. signal or not, rather it simply returns an integer with the exit
  781. code of the child; eg., if the child exited with an abort() call
  782. and didn't have a handler for SIGABRT, it simply returns with
  783. status == 3. We fix the status code to conform to the usual WIF*
  784. macros. Note that WIFSIGNALED will never be true under CRTDLL. */
  785. static pid_t
  786. pex_win32_wait (struct pex_obj *obj ATTRIBUTE_UNUSED, pid_t pid,
  787. int *status, struct pex_time *time, int done ATTRIBUTE_UNUSED,
  788. const char **errmsg, int *err)
  789. {
  790. DWORD termstat;
  791. HANDLE h;
  792. if (time != NULL)
  793. memset (time, 0, sizeof *time);
  794. h = (HANDLE) pid;
  795. /* FIXME: If done is non-zero, we should probably try to kill the
  796. process. */
  797. if (WaitForSingleObject (h, INFINITE) != WAIT_OBJECT_0)
  798. {
  799. CloseHandle (h);
  800. *err = ECHILD;
  801. *errmsg = "WaitForSingleObject";
  802. return -1;
  803. }
  804. GetExitCodeProcess (h, &termstat);
  805. CloseHandle (h);
  806. /* A value of 3 indicates that the child caught a signal, but not
  807. which one. Since only SIGABRT, SIGFPE and SIGINT do anything, we
  808. report SIGABRT. */
  809. if (termstat == 3)
  810. *status = SIGABRT;
  811. else
  812. *status = (termstat & 0xff) << 8;
  813. return 0;
  814. }
  815. /* Create a pipe. */
  816. static int
  817. pex_win32_pipe (struct pex_obj *obj ATTRIBUTE_UNUSED, int *p,
  818. int binary)
  819. {
  820. return _pipe (p, 256, (binary ? _O_BINARY : _O_TEXT) | _O_NOINHERIT);
  821. }
  822. /* Get a FILE pointer to read from a file descriptor. */
  823. static FILE *
  824. pex_win32_fdopenr (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd,
  825. int binary)
  826. {
  827. HANDLE h = (HANDLE) _get_osfhandle (fd);
  828. if (h == INVALID_HANDLE_VALUE)
  829. return NULL;
  830. if (! SetHandleInformation (h, HANDLE_FLAG_INHERIT, 0))
  831. return NULL;
  832. return fdopen (fd, binary ? "rb" : "r");
  833. }
  834. static FILE *
  835. pex_win32_fdopenw (struct pex_obj *obj ATTRIBUTE_UNUSED, int fd,
  836. int binary)
  837. {
  838. HANDLE h = (HANDLE) _get_osfhandle (fd);
  839. if (h == INVALID_HANDLE_VALUE)
  840. return NULL;
  841. if (! SetHandleInformation (h, HANDLE_FLAG_INHERIT, 0))
  842. return NULL;
  843. return fdopen (fd, binary ? "wb" : "w");
  844. }
  845. #ifdef MAIN
  846. #include <stdio.h>
  847. int
  848. main (int argc ATTRIBUTE_UNUSED, char **argv)
  849. {
  850. char const *errmsg;
  851. int err;
  852. argv++;
  853. printf ("%ld\n", (long) pex_win32_exec_child (NULL, PEX_SEARCH, argv[0], argv, NULL, 0, 0, 1, 2, &errmsg, &err));
  854. exit (0);
  855. }
  856. #endif