pex-win32.c 26 KB

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