posix-w32.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. /* Copyright (C) 2001, 2006, 2008, 2016 Free Software Foundation, Inc.
  2. *
  3. * This library is free software; you can redistribute it and/or
  4. * modify it under the terms of the GNU Lesser General Public License
  5. * as published by the Free Software Foundation; either version 3 of
  6. * the License, or (at your option) any later version.
  7. *
  8. * This library is distributed in the hope that it will be useful, but
  9. * WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * Lesser General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Lesser General Public
  14. * License along with this library; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. * 02110-1301 USA
  17. */
  18. #ifdef HAVE_CONFIG_H
  19. # include <config.h>
  20. #endif
  21. #include "libguile/__scm.h"
  22. # define WIN32_LEAN_AND_MEAN
  23. #include <windows.h>
  24. #include <c-strcase.h>
  25. #include <process.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <errno.h>
  30. #include <signal.h>
  31. #include <io.h>
  32. #include <fcntl.h>
  33. #include "posix-w32.h"
  34. #include "libguile/gc.h" /* for scm_*alloc, scm_strdup */
  35. #include "libguile/threads.h" /* for scm_i_scm_pthread_mutex_lock */
  36. /*
  37. * Get name and information about current kernel.
  38. */
  39. int
  40. uname (struct utsname *uts)
  41. {
  42. enum { WinNT, Win95, Win98, WinUnknown };
  43. OSVERSIONINFO osver;
  44. SYSTEM_INFO sysinfo;
  45. DWORD sLength;
  46. DWORD os = WinUnknown;
  47. memset (uts, 0, sizeof (*uts));
  48. osver.dwOSVersionInfoSize = sizeof (osver);
  49. GetVersionEx (&osver);
  50. GetSystemInfo (&sysinfo);
  51. switch (osver.dwPlatformId)
  52. {
  53. case VER_PLATFORM_WIN32_NT: /* NT, Windows 2000 or Windows XP */
  54. if (osver.dwMajorVersion == 4)
  55. strcpy (uts->sysname, "Windows NT4x"); /* NT4x */
  56. else if (osver.dwMajorVersion <= 3)
  57. strcpy (uts->sysname, "Windows NT3x"); /* NT3x */
  58. else if (osver.dwMajorVersion == 5 && osver.dwMinorVersion < 1)
  59. strcpy (uts->sysname, "Windows 2000"); /* 2k */
  60. else if (osver.dwMajorVersion < 6)
  61. strcpy (uts->sysname, "Windows XP"); /* XP */
  62. else if (osver.dwMajorVersion == 6)
  63. {
  64. if (osver.dwMinorVersion < 1)
  65. strcpy (uts->sysname, "Windows Vista"); /* Vista */
  66. else if (osver.dwMinorVersion < 2)
  67. strcpy (uts->sysname, "Windows 7"); /* Windows 7 */
  68. else if (osver.dwMinorVersion < 3)
  69. strcpy (uts->sysname, "Windows 8"); /* Windows 8 */
  70. else if (osver.dwMinorVersion < 4)
  71. strcpy (uts->sysname, "Windows 8.1"); /* Windows 8.1 */
  72. }
  73. else if (osver.dwMajorVersion >= 10)
  74. strcpy (uts->sysname, "Windows 10 or later"); /* Windows 10 and later */
  75. os = WinNT;
  76. break;
  77. case VER_PLATFORM_WIN32_WINDOWS: /* Win95, Win98 or WinME */
  78. if ((osver.dwMajorVersion > 4) ||
  79. ((osver.dwMajorVersion == 4) && (osver.dwMinorVersion > 0)))
  80. {
  81. if (osver.dwMinorVersion >= 90)
  82. strcpy (uts->sysname, "Windows ME"); /* ME */
  83. else
  84. strcpy (uts->sysname, "Windows 98"); /* 98 */
  85. os = Win98;
  86. }
  87. else
  88. {
  89. strcpy (uts->sysname, "Windows 95"); /* 95 */
  90. os = Win95;
  91. }
  92. break;
  93. case VER_PLATFORM_WIN32s: /* Windows 3.x */
  94. strcpy (uts->sysname, "Windows");
  95. break;
  96. }
  97. sprintf (uts->version, "%ld.%02ld",
  98. osver.dwMajorVersion, osver.dwMinorVersion);
  99. if (osver.szCSDVersion[0] != '\0' &&
  100. (strlen (osver.szCSDVersion) + strlen (uts->version) + 1) <
  101. sizeof (uts->version))
  102. {
  103. strcat (uts->version, " ");
  104. strcat (uts->version, osver.szCSDVersion);
  105. }
  106. sprintf (uts->release, "build %ld", osver.dwBuildNumber & 0xFFFF);
  107. switch (sysinfo.wProcessorArchitecture)
  108. {
  109. case PROCESSOR_ARCHITECTURE_PPC:
  110. strcpy (uts->machine, "ppc");
  111. break;
  112. case PROCESSOR_ARCHITECTURE_ALPHA:
  113. strcpy (uts->machine, "alpha");
  114. break;
  115. case PROCESSOR_ARCHITECTURE_MIPS:
  116. strcpy (uts->machine, "mips");
  117. break;
  118. case PROCESSOR_ARCHITECTURE_IA64:
  119. strcpy (uts->machine, "ia64");
  120. break;
  121. case PROCESSOR_ARCHITECTURE_INTEL:
  122. /*
  123. * dwProcessorType is only valid in Win95 and Win98 and WinME
  124. * wProcessorLevel is only valid in WinNT
  125. */
  126. switch (os)
  127. {
  128. case Win95:
  129. case Win98:
  130. switch (sysinfo.dwProcessorType)
  131. {
  132. case PROCESSOR_INTEL_386:
  133. case PROCESSOR_INTEL_486:
  134. case PROCESSOR_INTEL_PENTIUM:
  135. sprintf (uts->machine, "i%ld", sysinfo.dwProcessorType);
  136. break;
  137. default:
  138. strcpy (uts->machine, "i386");
  139. break;
  140. }
  141. break;
  142. case WinNT:
  143. sprintf (uts->machine, "i%d86", sysinfo.wProcessorLevel);
  144. break;
  145. default:
  146. strcpy (uts->machine, "unknown");
  147. break;
  148. }
  149. break;
  150. case PROCESSOR_ARCHITECTURE_AMD64:
  151. strcpy (uts->machine, "x86_64");
  152. break;
  153. default:
  154. strcpy (uts->machine, "unknown");
  155. break;
  156. }
  157. sLength = sizeof (uts->nodename) - 1;
  158. GetComputerName (uts->nodename, &sLength);
  159. return 0;
  160. }
  161. /* Utility functions for maintaining the list of subprocesses launched
  162. by Guile. */
  163. struct proc_record {
  164. DWORD pid;
  165. HANDLE handle;
  166. };
  167. static struct proc_record *procs;
  168. static ptrdiff_t proc_size;
  169. /* Find the process slot that corresponds to PID. Return the index of
  170. the slot, or -1 if not found. */
  171. static ptrdiff_t
  172. find_proc (pid_t pid)
  173. {
  174. ptrdiff_t found = -1, i;
  175. for (i = 0; i < proc_size; i++)
  176. {
  177. if (procs[i].pid == pid && procs[i].handle != INVALID_HANDLE_VALUE)
  178. found = i;
  179. }
  180. return found;
  181. }
  182. /* Return the process handle corresponding to its PID. If not found,
  183. return invalid handle value. */
  184. static HANDLE
  185. proc_handle (pid_t pid)
  186. {
  187. ptrdiff_t idx = find_proc (pid);
  188. if (idx < 0)
  189. return INVALID_HANDLE_VALUE;
  190. return procs[idx].handle;
  191. }
  192. /* Store a process record in the procs[] array. */
  193. static void
  194. record_proc (pid_t proc_pid, HANDLE proc_handle)
  195. {
  196. ptrdiff_t i;
  197. /* Find a vacant slot. */
  198. for (i = 0; i < proc_size; i++)
  199. {
  200. if (procs[i].handle == INVALID_HANDLE_VALUE)
  201. break;
  202. }
  203. /* If no vacant slot, enlarge the array. */
  204. if (i == proc_size)
  205. {
  206. proc_size++;
  207. procs = scm_realloc (procs, proc_size * sizeof(procs[0]));
  208. }
  209. /* Store the process data. */
  210. procs[i].pid = proc_pid;
  211. procs[i].handle = proc_handle;
  212. }
  213. /* Delete a process record for process PID. */
  214. static void
  215. delete_proc (pid_t pid)
  216. {
  217. ptrdiff_t idx = find_proc (pid);
  218. if (0 <= idx && idx < proc_size)
  219. procs[idx].handle = INVALID_HANDLE_VALUE;
  220. }
  221. /* Run a child process with redirected standard handles, without
  222. redirecting standard handles of the parent. This is required in
  223. multithreaded programs, where redirecting a standard handle affects
  224. all threads. */
  225. /* Prepare a possibly redirected file handle to be passed to a child
  226. process. The handle is for the file/device open on file descriptor
  227. FD; if FD is invalid, use the null device instead.
  228. USE_STD non-zero means we have been passed the descriptor used by
  229. the parent.
  230. ACCESS is the Windows access mode for opening the null device.
  231. Returns the Win32 handle to be passed to CreateProcess. */
  232. static HANDLE
  233. prepare_child_handle (int fd, int use_std, DWORD access)
  234. {
  235. HANDLE htem, hret;
  236. DWORD err = 0;
  237. /* Start with the descriptor, if specified by the caller and valid,
  238. otherwise open the null device. */
  239. if (fd < 0)
  240. htem = INVALID_HANDLE_VALUE;
  241. else
  242. htem = (HANDLE)_get_osfhandle (fd);
  243. /* Duplicate the handle and make it inheritable. */
  244. if (DuplicateHandle (GetCurrentProcess (),
  245. htem,
  246. GetCurrentProcess (),
  247. &hret,
  248. 0,
  249. TRUE,
  250. DUPLICATE_SAME_ACCESS) == FALSE)
  251. {
  252. /* If the original standard handle was invalid (happens, e.g.,
  253. in GUI programs), open the null device instead. */
  254. if ((err = GetLastError ()) == ERROR_INVALID_HANDLE
  255. && use_std)
  256. {
  257. htem = CreateFile ("NUL", access,
  258. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
  259. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  260. if (htem != INVALID_HANDLE_VALUE
  261. && DuplicateHandle (GetCurrentProcess (),
  262. htem,
  263. GetCurrentProcess (),
  264. &hret,
  265. 0,
  266. TRUE,
  267. DUPLICATE_SAME_ACCESS) == FALSE)
  268. {
  269. err = GetLastError ();
  270. CloseHandle (htem);
  271. hret = INVALID_HANDLE_VALUE;
  272. }
  273. }
  274. }
  275. if (hret == INVALID_HANDLE_VALUE)
  276. {
  277. switch (err)
  278. {
  279. case ERROR_NO_MORE_FILES:
  280. errno = EMFILE;
  281. break;
  282. case ERROR_INVALID_HANDLE:
  283. default:
  284. errno = EBADF;
  285. break;
  286. }
  287. }
  288. return hret;
  289. }
  290. /* A comparison function for sorting the environment. */
  291. static int
  292. compenv (const void *a1, const void *a2)
  293. {
  294. return stricmp (*((char**)a1), *((char**)a2));
  295. }
  296. /* Convert the program's 'environ' array to a block of environment
  297. variables suitable to be passed to CreateProcess. This is needed
  298. to ensure the child process inherits the up-to-date environment of
  299. the parent, including any variables inserted by the parent. */
  300. static void
  301. prepare_envblk (char **envp, char **envblk)
  302. {
  303. char **tmp;
  304. int size_needed;
  305. int envcnt;
  306. char *ptr;
  307. for (envcnt = 0; envp[envcnt]; envcnt++)
  308. ;
  309. tmp = scm_calloc ((envcnt + 1) * sizeof (*tmp));
  310. for (envcnt = size_needed = 0; envp[envcnt]; envcnt++)
  311. {
  312. tmp[envcnt] = envp[envcnt];
  313. size_needed += strlen (envp[envcnt]) + 1;
  314. }
  315. size_needed++;
  316. /* Windows likes its environment variables sorted. */
  317. qsort ((void *) tmp, (size_t) envcnt, sizeof (char *), compenv);
  318. /* CreateProcess needs the environment block as a linear array,
  319. where each variable is terminated by a null character, and the
  320. last one is terminated by 2 null characters. */
  321. ptr = *envblk = scm_calloc (size_needed);
  322. for (envcnt = 0; tmp[envcnt]; envcnt++)
  323. {
  324. strcpy (ptr, tmp[envcnt]);
  325. ptr += strlen (tmp[envcnt]) + 1;
  326. }
  327. free (tmp);
  328. }
  329. /* Find an executable PROGRAM on PATH, return result in malloc'ed
  330. storage. If PROGRAM is /bin/sh, and no sh.exe was found on PATH,
  331. fall back on the Windows shell and set BIN_SH_REPLACED to non-zero. */
  332. static char *
  333. lookup_cmd (const char *program, int *bin_sh_replaced)
  334. {
  335. static const char *extensions[] = {
  336. ".exe", ".cmd", ".bat", "", ".com", NULL
  337. };
  338. int bin_sh_requested = 0;
  339. char *path, *dir, *sep;
  340. char abs_name[MAX_PATH];
  341. DWORD abs_namelen = 0;
  342. /* If they ask for the Unix system shell, try to find it on PATH. */
  343. if (c_strcasecmp (program, "/bin/sh") == 0)
  344. {
  345. bin_sh_requested = 1;
  346. program = "sh.exe";
  347. }
  348. /* If PROGRAM includes leading directories, the caller already did
  349. our job. */
  350. if (strchr (program, '/') != NULL
  351. || strchr (program, '\\') != NULL)
  352. return scm_strdup (program);
  353. /* Note: It is OK for getenv below to return NULL -- in that case,
  354. SearchPath will search in the directories whose list is specified
  355. by the system Registry. */
  356. path = getenv ("PATH");
  357. if (!path) /* shouldn't happen, really */
  358. path = ".";
  359. dir = sep = path = strdup (path);
  360. for ( ; sep && *sep; dir = sep + 1)
  361. {
  362. int i;
  363. sep = strpbrk (dir, ";");
  364. if (sep == dir) /* two or more ;'s in a row */
  365. continue;
  366. if (sep)
  367. *sep = '\0';
  368. for (i = 0; extensions[i]; i++)
  369. {
  370. abs_namelen = SearchPath (dir, program, extensions[i],
  371. MAX_PATH, abs_name, NULL);
  372. if (0 < abs_namelen && abs_namelen <= MAX_PATH) /* found! */
  373. break;
  374. }
  375. if (extensions[i]) /* found! */
  376. break;
  377. if (sep)
  378. *sep = ';';
  379. }
  380. free (path);
  381. /* If they asked for /bin/sh and we didn't find it, fall back on the
  382. default Windows shell. */
  383. if (abs_namelen <= 0 && bin_sh_requested)
  384. {
  385. const char *shell = getenv ("ComSpec");
  386. if (!shell)
  387. shell = "C:\\Windows\\system32\\cmd.exe";
  388. *bin_sh_replaced = 1;
  389. strcpy (abs_name, shell);
  390. abs_namelen = strlen (abs_name);
  391. }
  392. /* If not found, return the original PROGRAM name. */
  393. if (abs_namelen <= 0 || abs_namelen > MAX_PATH)
  394. return scm_strdup (program);
  395. return scm_strndup (abs_name, abs_namelen);
  396. }
  397. /* Concatenate command-line arguments in argv[] into a single
  398. command-line string, while quoting arguments as needed. The result
  399. is malloc'ed. */
  400. static char *
  401. prepare_cmdline (const char *cmd, const char * const *argv, int bin_sh_replaced)
  402. {
  403. /* These characters should include anything that is special to _any_
  404. program, including both Windows and Unixy shells, and the
  405. widlcard expansion in startup code of a typical Windows app. */
  406. const char need_quotes[] = " \t#;\"\'*?[]&|<>(){}$`^";
  407. size_t cmdlen = 1; /* for terminating null */
  408. char *cmdline = scm_malloc (cmdlen);
  409. char *dst = cmdline;
  410. int cmd_exe_quoting = 0;
  411. int i;
  412. const char *p;
  413. /* Are we constructing a command line for cmd.exe? */
  414. if (bin_sh_replaced)
  415. cmd_exe_quoting = 1;
  416. else
  417. {
  418. for (p = cmd + strlen (cmd);
  419. p > cmd && p[-1] != '/' && p[-1] != '\\' && p[-1] != ':';
  420. p--)
  421. ;
  422. if (c_strcasecmp (p, "cmd.exe") == 0
  423. || c_strcasecmp (p, "cmd") == 0)
  424. cmd_exe_quoting = 1;
  425. }
  426. /* Initialize the command line to empty. */
  427. *dst = '\0';
  428. /* Append arguments, if any, from argv[]. */
  429. for (i = 0; argv[i]; i++)
  430. {
  431. const char *src = argv[i];
  432. size_t len;
  433. int quote_this = 0, n_backslashes = 0;
  434. int j;
  435. /* Append the blank separator. We don't do that for argv[0]
  436. because that is the command name (will end up in child's
  437. argv[0]), and is only recognized as such if there're no
  438. blanks before it. */
  439. if (i > 0)
  440. *dst++ = ' ';
  441. len = dst - cmdline;
  442. /* How much space is required for this argument? */
  443. cmdlen += strlen (argv[i]) + 1; /* 1 for a blank separator */
  444. /* cmd.exe needs a different style of quoting: all the arguments
  445. beyond the /c switch are enclosed in an extra pair of quotes,
  446. and not otherwise quoted/escaped. */
  447. if (cmd_exe_quoting)
  448. {
  449. if (i == 2)
  450. cmdlen += 2;
  451. }
  452. else if (strpbrk (argv[i], need_quotes))
  453. {
  454. quote_this = 1;
  455. cmdlen += 2;
  456. for ( ; *src; src++)
  457. {
  458. /* An embedded quote needs to be escaped by a backslash.
  459. Any backslashes immediately preceding that quote need
  460. each one to be escaped by another backslash. */
  461. if (*src == '\"')
  462. cmdlen += n_backslashes + 1;
  463. if (*src == '\\')
  464. n_backslashes++;
  465. else
  466. n_backslashes = 0;
  467. }
  468. /* If the closing quote we will add is preceded by
  469. backslashes, those backslashes need to be escaped. */
  470. cmdlen += n_backslashes;
  471. }
  472. /* Enlarge the command-line string as needed. */
  473. cmdline = scm_realloc (cmdline, cmdlen);
  474. dst = cmdline + len;
  475. if (i == 0
  476. && c_strcasecmp (argv[0], "/bin/sh") == 0
  477. && bin_sh_replaced)
  478. {
  479. strcpy (dst, "cmd.exe");
  480. dst += sizeof ("cmd.exe") - 1;
  481. continue;
  482. }
  483. if (i == 1 && bin_sh_replaced && strcmp (argv[1], "-c") == 0)
  484. {
  485. *dst++ = '/';
  486. *dst++ = 'c';
  487. *dst = '\0';
  488. continue;
  489. }
  490. /* Add this argument, possibly quoted, to the command line. */
  491. if (quote_this || (i == 2 && cmd_exe_quoting))
  492. *dst++ = '\"';
  493. for (src = argv[i]; *src; src++)
  494. {
  495. if (quote_this)
  496. {
  497. if (*src == '\"')
  498. for (j = n_backslashes + 1; j > 0; j--)
  499. *dst++ = '\\';
  500. if (*src == '\\')
  501. n_backslashes++;
  502. else
  503. n_backslashes = 0;
  504. }
  505. *dst++ = *src;
  506. }
  507. if (quote_this)
  508. {
  509. for (j = n_backslashes; j > 0; j--)
  510. *dst++ = '\\';
  511. *dst++ = '\"';
  512. }
  513. *dst = '\0';
  514. }
  515. if (cmd_exe_quoting && i > 2)
  516. {
  517. /* One extra slot was already reserved when we enlarged cmdlen
  518. by 2 in the "if (cmd_exe_quoting)" clause above. So we can
  519. safely append a closing quote. */
  520. *dst++ = '\"';
  521. *dst = '\0';
  522. }
  523. return cmdline;
  524. }
  525. /* Start a child process running the program in EXEC_FILE with its
  526. standard input and output optionally redirected to a pipe. ARGV is
  527. the array of command-line arguments to pass to the child. P2C and
  528. C2P are 2 pipes for communicating with the child, and ERRFD is the
  529. standard error file descriptor to be inherited by the child.
  530. READING and WRITING, if non-zero, mean that the corresponding pipe
  531. will be used.
  532. Return the PID of the child process, or -1 if couldn't start a
  533. process. */
  534. pid_t
  535. start_child (const char *exec_file, char **argv,
  536. int reading, int c2p[2], int writing, int p2c[2],
  537. int infd, int outfd, int errfd)
  538. {
  539. HANDLE hin = INVALID_HANDLE_VALUE, hout = INVALID_HANDLE_VALUE;
  540. HANDLE herr = INVALID_HANDLE_VALUE;
  541. STARTUPINFO si;
  542. char *env_block = NULL;
  543. char *cmdline = NULL;
  544. PROCESS_INFORMATION pi;
  545. char *progfile, *p;
  546. int errno_save;
  547. intptr_t pid;
  548. int bin_sh_replaced = 0;
  549. if (!reading)
  550. c2p[1] = outfd;
  551. if (!writing)
  552. p2c[0] = infd;
  553. /* Prepare standard handles to be passed to the child process. */
  554. hin = prepare_child_handle (p2c[0], !writing, GENERIC_READ);
  555. if (hin == INVALID_HANDLE_VALUE)
  556. return -1;
  557. hout = prepare_child_handle (c2p[1], !reading, GENERIC_WRITE);
  558. if (hout == INVALID_HANDLE_VALUE)
  559. return -1;
  560. herr = prepare_child_handle (errfd, 1, GENERIC_WRITE);
  561. if (herr == INVALID_HANDLE_VALUE)
  562. return -1;
  563. /* Make sure the parent side of both pipes is not inherited. This
  564. is required because gnulib's 'pipe' creates pipes whose both ends
  565. are inheritable, which is traditional on Posix (where pipe
  566. descriptors are implicitly duplicated by 'fork'), but wrong on
  567. Windows (where pipe handles need to be explicitly
  568. duplicated). */
  569. if (writing)
  570. SetHandleInformation ((HANDLE)_get_osfhandle (p2c[1]),
  571. HANDLE_FLAG_INHERIT, 0);
  572. if (reading)
  573. {
  574. SetHandleInformation ((HANDLE)_get_osfhandle (c2p[0]),
  575. HANDLE_FLAG_INHERIT, 0);
  576. /* Gnulib's 'pipe' opens the pipe in binary mode, but we don't
  577. want to read text-mode input of subprocesses in binary more,
  578. because then we will get the ^M (a.k.a. "CR") characters we
  579. don't expect. */
  580. _setmode (c2p[0], _O_TEXT);
  581. }
  582. /* Set up the startup info for the child, using the parent's as the
  583. starting point, and specify in it the redirected handles. */
  584. GetStartupInfo (&si);
  585. si.dwFlags = STARTF_USESTDHANDLES;
  586. si.lpReserved = 0;
  587. si.cbReserved2 = 0;
  588. si.lpReserved2 = 0;
  589. si.hStdInput = hin;
  590. si.hStdOutput = hout;
  591. si.hStdError = herr;
  592. /* Create the environment block for the child. This is needed
  593. because the environment we have in 'environ' is not in the format
  594. expected by CreateProcess. */
  595. prepare_envblk (environ, &env_block);
  596. /* CreateProcess doesn't search PATH, so we must do that for it. */
  597. progfile = lookup_cmd (exec_file, &bin_sh_replaced);
  598. /* CreateProcess doesn't like forward slashes in the application
  599. file name. */
  600. for (p = progfile; *p; p++)
  601. if (*p == '/')
  602. *p = '\\';
  603. /* Construct the command line. */
  604. cmdline = prepare_cmdline (exec_file, (const char * const *)argv,
  605. bin_sh_replaced);
  606. /* All set and ready to fly. Launch the child process. */
  607. if (!CreateProcess (progfile, cmdline, NULL, NULL, TRUE, 0, env_block, NULL,
  608. &si, &pi))
  609. {
  610. pid = -1;
  611. /* Since we use Win32 APIs directly, we need to translate their
  612. errors to errno values by hand. */
  613. switch (GetLastError ())
  614. {
  615. case ERROR_FILE_NOT_FOUND:
  616. case ERROR_PATH_NOT_FOUND:
  617. case ERROR_INVALID_DRIVE:
  618. case ERROR_BAD_PATHNAME:
  619. errno = ENOENT;
  620. break;
  621. case ERROR_ACCESS_DENIED:
  622. errno = EACCES;
  623. break;
  624. case ERROR_BAD_ENVIRONMENT:
  625. errno = E2BIG;
  626. break;
  627. case ERROR_BROKEN_PIPE:
  628. errno = EPIPE;
  629. break;
  630. case ERROR_INVALID_HANDLE:
  631. errno = EBADF;
  632. break;
  633. case ERROR_MAX_THRDS_REACHED:
  634. errno = EAGAIN;
  635. break;
  636. case ERROR_BAD_EXE_FORMAT:
  637. case ERROR_BAD_FORMAT:
  638. default:
  639. errno = ENOEXEC;
  640. break;
  641. }
  642. }
  643. else
  644. {
  645. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  646. record_proc (pi.dwProcessId, pi.hProcess);
  647. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  648. pid = pi.dwProcessId;
  649. }
  650. errno_save = errno;
  651. /* Free resources. */
  652. free (progfile);
  653. free (cmdline);
  654. free (env_block);
  655. CloseHandle (hin);
  656. CloseHandle (hout);
  657. CloseHandle (herr);
  658. CloseHandle (pi.hThread);
  659. /* Posix requires to call the shell if execvp fails to invoke EXEC_FILE. */
  660. if (errno_save == ENOEXEC || errno_save == ENOENT)
  661. {
  662. const char *shell = getenv ("ComSpec");
  663. if (!shell)
  664. shell = "cmd.exe";
  665. if (c_strcasecmp (exec_file, shell) != 0)
  666. {
  667. argv[0] = (char *)exec_file;
  668. return start_child (shell, argv, reading, c2p, writing, p2c,
  669. infd, outfd, errfd);
  670. }
  671. }
  672. errno = errno_save;
  673. return pid;
  674. }
  675. /* Emulation of waitpid which only supports WNOHANG, since _cwait doesn't. */
  676. int
  677. waitpid (pid_t pid, int *status, int options)
  678. {
  679. HANDLE ph;
  680. /* Not supported on MS-Windows. */
  681. if (pid <= 0)
  682. {
  683. errno = ENOSYS;
  684. return -1;
  685. }
  686. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  687. ph = proc_handle (pid);
  688. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  689. /* Since scm_waitpid is documented to work only on child processes,
  690. being unable to find a process in our records means failure. */
  691. if (ph == INVALID_HANDLE_VALUE)
  692. {
  693. errno = ECHILD;
  694. return -1;
  695. }
  696. if ((options & WNOHANG) != 0)
  697. {
  698. DWORD st;
  699. if (!GetExitCodeProcess (ph, &st))
  700. {
  701. errno = ECHILD;
  702. return -1;
  703. }
  704. if (st == STILL_ACTIVE)
  705. return 0;
  706. if (status)
  707. *status = st;
  708. CloseHandle (ph);
  709. }
  710. else
  711. _cwait (status, (intptr_t)ph, WAIT_CHILD);
  712. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  713. delete_proc (pid);
  714. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  715. return pid;
  716. }
  717. /* Translate abnormal exit status of Windows programs into the signal
  718. that terminated the program. This is required to support scm_kill
  719. and WTERMSIG. */
  720. struct signal_and_status {
  721. int sig;
  722. DWORD status;
  723. };
  724. static const struct signal_and_status sigtbl[] = {
  725. {SIGSEGV, 0xC0000005}, /* access to invalid address */
  726. {SIGSEGV, 0xC0000008}, /* invalid handle */
  727. {SIGILL, 0xC000001D}, /* illegal instruction */
  728. {SIGILL, 0xC0000025}, /* non-continuable instruction */
  729. {SIGSEGV, 0xC000008C}, /* array bounds exceeded */
  730. {SIGFPE, 0xC000008D}, /* float denormal */
  731. {SIGFPE, 0xC000008E}, /* float divide by zero */
  732. {SIGFPE, 0xC000008F}, /* float inexact */
  733. {SIGFPE, 0xC0000090}, /* float invalid operation */
  734. {SIGFPE, 0xC0000091}, /* float overflow */
  735. {SIGFPE, 0xC0000092}, /* float stack check */
  736. {SIGFPE, 0xC0000093}, /* float underflow */
  737. {SIGFPE, 0xC0000094}, /* integer divide by zero */
  738. {SIGFPE, 0xC0000095}, /* integer overflow */
  739. {SIGILL, 0xC0000096}, /* privileged instruction */
  740. {SIGSEGV, 0xC00000FD}, /* stack overflow */
  741. {SIGTERM, 0xC000013A}, /* Ctrl-C exit */
  742. {SIGINT, 0xC000013A}
  743. };
  744. static int
  745. w32_signal_to_status (int sig)
  746. {
  747. int i;
  748. for (i = 0; i < sizeof (sigtbl) / sizeof (sigtbl[0]); i++)
  749. if (sig == sigtbl[i].sig)
  750. return sigtbl[i].status;
  751. return (int)0xC000013A;
  752. }
  753. int
  754. w32_status_to_termsig (DWORD status)
  755. {
  756. int i;
  757. for (i = 0; i < sizeof (sigtbl) / sizeof (sigtbl[0]); i++)
  758. if (status == sigtbl[i].status)
  759. return sigtbl[i].sig;
  760. return SIGTERM;
  761. }
  762. /* Support for scm_kill. */
  763. int
  764. kill (int pid, int sig)
  765. {
  766. HANDLE ph;
  767. int child_proc = 0;
  768. if (pid == getpid ())
  769. {
  770. if (raise (sig) == 0)
  771. errno = ENOSYS;
  772. return -1;
  773. }
  774. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  775. ph = proc_handle (pid);
  776. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  777. /* If not found among our subprocesses, look elsewhere in the
  778. system. */
  779. if (ph == INVALID_HANDLE_VALUE)
  780. ph = OpenProcess (PROCESS_TERMINATE, 0, pid);
  781. else
  782. child_proc = 1;
  783. if (!ph)
  784. {
  785. errno = EPERM;
  786. return -1;
  787. }
  788. if (!TerminateProcess (ph, w32_signal_to_status (sig)))
  789. {
  790. /* If it's our subprocess, it could have already exited. In
  791. that case, waitpid will handily delete the process from our
  792. records, and we should return a more meaningful ESRCH to the
  793. caller. */
  794. if (child_proc && waitpid (pid, NULL, WNOHANG) == pid)
  795. errno = ESRCH;
  796. else
  797. errno = EINVAL;
  798. return -1;
  799. }
  800. CloseHandle (ph);
  801. if (child_proc)
  802. {
  803. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  804. delete_proc (pid);
  805. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  806. }
  807. return 0;
  808. }
  809. /* Emulation of getpriority and setpriority. */
  810. #define NZERO 8
  811. int
  812. getpriority (int which, int who)
  813. {
  814. HANDLE hp;
  815. int nice_value = -1;
  816. int error = 0;
  817. int child_proc = 0;
  818. /* We don't support process groups and users. */
  819. if (which != PRIO_PROCESS)
  820. {
  821. errno = ENOSYS;
  822. return -1;
  823. }
  824. if (who == 0)
  825. hp = GetCurrentProcess ();
  826. else
  827. {
  828. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  829. hp = proc_handle (who);
  830. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  831. /* If not found among our subprocesses, look elsewhere in the
  832. system. */
  833. if (hp == INVALID_HANDLE_VALUE)
  834. hp = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, who);
  835. else
  836. child_proc = 1;
  837. }
  838. if (hp)
  839. {
  840. DWORD pri_class = GetPriorityClass (hp);
  841. /* The pseudo-handle returned by GetCurrentProcess doesn't need
  842. to be closed. */
  843. if (who > 0 && !child_proc)
  844. CloseHandle (hp);
  845. if (pri_class > 0)
  846. {
  847. switch (pri_class)
  848. {
  849. case IDLE_PRIORITY_CLASS:
  850. nice_value = 4;
  851. break;
  852. case BELOW_NORMAL_PRIORITY_CLASS:
  853. nice_value = 6;
  854. break;
  855. case NORMAL_PRIORITY_CLASS:
  856. nice_value = 8;
  857. break;
  858. case ABOVE_NORMAL_PRIORITY_CLASS:
  859. nice_value = 10;
  860. break;
  861. case HIGH_PRIORITY_CLASS:
  862. nice_value = 13;
  863. break;
  864. case REALTIME_PRIORITY_CLASS:
  865. nice_value = 24;
  866. break;
  867. }
  868. /* If WHO is us, we can provide a more fine-grained value by
  869. looking at the current thread's priority value. (For
  870. other processes, it is not clear which thread to use.) */
  871. if (who == 0 || who == GetCurrentProcessId ())
  872. {
  873. HANDLE ht = GetCurrentThread ();
  874. int tprio = GetThreadPriority (ht);
  875. switch (tprio)
  876. {
  877. case THREAD_PRIORITY_IDLE:
  878. if (pri_class == REALTIME_PRIORITY_CLASS)
  879. nice_value = 16;
  880. else
  881. nice_value = 1;
  882. break;
  883. case THREAD_PRIORITY_TIME_CRITICAL:
  884. if (pri_class == REALTIME_PRIORITY_CLASS)
  885. nice_value = 31;
  886. else
  887. nice_value = 15;
  888. case THREAD_PRIORITY_ERROR_RETURN:
  889. nice_value = -1;
  890. error = 1;
  891. break;
  892. default:
  893. nice_value += tprio;
  894. break;
  895. }
  896. }
  897. /* Map to "nice values" similar to what one would see on
  898. Posix platforms. */
  899. if (!error)
  900. nice_value = - (nice_value - NZERO);
  901. }
  902. else
  903. error = 1;
  904. }
  905. else
  906. error = 1;
  907. if (error)
  908. {
  909. DWORD err = GetLastError ();
  910. switch (err)
  911. {
  912. case ERROR_INVALID_PARAMETER:
  913. case ERROR_INVALID_THREAD_ID:
  914. errno = ESRCH;
  915. break;
  916. default:
  917. errno = EPERM;
  918. break;
  919. }
  920. }
  921. return nice_value;
  922. }
  923. int
  924. setpriority (int which, int who, int nice_val)
  925. {
  926. HANDLE hp;
  927. DWORD err;
  928. int child_proc = 0, retval = -1;
  929. if (which != PRIO_PROCESS)
  930. {
  931. errno = ENOSYS;
  932. return -1;
  933. }
  934. if (who == 0)
  935. hp = GetCurrentProcess ();
  936. else
  937. {
  938. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  939. hp = proc_handle (who);
  940. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  941. /* If not found among our subprocesses, look elsewhere in the
  942. system. */
  943. if (hp == INVALID_HANDLE_VALUE)
  944. hp = OpenProcess (PROCESS_SET_INFORMATION, FALSE, who);
  945. else
  946. child_proc = 1;
  947. }
  948. if (hp)
  949. {
  950. DWORD pri_class;
  951. /* Map "nice values" back to process priority classes. */
  952. nice_val = -nice_val + NZERO;
  953. if (nice_val < 6)
  954. pri_class = IDLE_PRIORITY_CLASS;
  955. else if (nice_val < 8)
  956. pri_class = BELOW_NORMAL_PRIORITY_CLASS;
  957. else if (nice_val < 10)
  958. pri_class = NORMAL_PRIORITY_CLASS;
  959. else if (nice_val < 13)
  960. pri_class = ABOVE_NORMAL_PRIORITY_CLASS;
  961. else if (nice_val < 16)
  962. pri_class = HIGH_PRIORITY_CLASS;
  963. else
  964. pri_class = REALTIME_PRIORITY_CLASS;
  965. if (SetPriorityClass (hp, pri_class))
  966. retval = 0;
  967. }
  968. err = GetLastError ();
  969. switch (err)
  970. {
  971. case ERROR_INVALID_PARAMETER:
  972. errno = ESRCH;
  973. break;
  974. default:
  975. errno = EPERM;
  976. break;
  977. }
  978. /* The pseudo-handle returned by GetCurrentProcess doesn't
  979. need to be closed. */
  980. if (hp && who > 0 && !child_proc)
  981. CloseHandle (hp);
  982. return retval;
  983. }
  984. /* Emulation of sched_getaffinity and sched_setaffinity. */
  985. int
  986. sched_getaffinity (int pid, size_t mask_size, cpu_set_t *mask)
  987. {
  988. HANDLE hp;
  989. DWORD err;
  990. int child_proc = 0;
  991. if (mask == NULL)
  992. {
  993. errno = EFAULT;
  994. return -1;
  995. }
  996. if (pid == 0)
  997. hp = GetCurrentProcess ();
  998. else
  999. {
  1000. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  1001. hp = proc_handle (pid);
  1002. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  1003. /* If not found among our subprocesses, look elsewhere in the
  1004. system. */
  1005. if (hp == INVALID_HANDLE_VALUE)
  1006. hp = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid);
  1007. else
  1008. child_proc = 1;
  1009. }
  1010. if (hp)
  1011. {
  1012. DWORD_PTR ignored;
  1013. BOOL result = GetProcessAffinityMask (hp, (DWORD_PTR *)mask, &ignored);
  1014. /* The pseudo-handle returned by GetCurrentProcess doesn't
  1015. need to be closed. */
  1016. if (pid > 0 && !child_proc)
  1017. CloseHandle (hp);
  1018. if (result)
  1019. return 0;
  1020. }
  1021. err = GetLastError ();
  1022. switch (err)
  1023. {
  1024. case ERROR_INVALID_PARAMETER:
  1025. errno = ESRCH;
  1026. break;
  1027. case ERROR_ACCESS_DENIED:
  1028. default:
  1029. errno = EPERM;
  1030. break;
  1031. }
  1032. return -1;
  1033. }
  1034. int
  1035. sched_setaffinity (int pid, size_t mask_size, cpu_set_t *mask)
  1036. {
  1037. HANDLE hp;
  1038. DWORD err;
  1039. int child_proc = 0;
  1040. if (mask == NULL)
  1041. {
  1042. errno = EFAULT;
  1043. return -1;
  1044. }
  1045. if (pid == 0)
  1046. hp = GetCurrentProcess ();
  1047. else
  1048. {
  1049. scm_i_scm_pthread_mutex_lock (&scm_i_misc_mutex);
  1050. hp = proc_handle (pid);
  1051. scm_i_pthread_mutex_unlock (&scm_i_misc_mutex);
  1052. /* If not found among our subprocesses, look elsewhere in the
  1053. system. */
  1054. if (hp == INVALID_HANDLE_VALUE)
  1055. hp = OpenProcess (PROCESS_SET_INFORMATION, FALSE, pid);
  1056. else
  1057. child_proc = 1;
  1058. }
  1059. if (hp)
  1060. {
  1061. BOOL result = SetProcessAffinityMask (hp, *(DWORD_PTR *)mask);
  1062. /* The pseudo-handle returned by GetCurrentProcess doesn't
  1063. need to be closed. */
  1064. if (pid > 0 && !child_proc)
  1065. CloseHandle (hp);
  1066. if (result)
  1067. return 0;
  1068. }
  1069. err = GetLastError ();
  1070. switch (err)
  1071. {
  1072. case ERROR_INVALID_PARAMETER:
  1073. errno = ESRCH;
  1074. break;
  1075. case ERROR_ACCESS_DENIED:
  1076. default:
  1077. errno = EPERM;
  1078. break;
  1079. }
  1080. return -1;
  1081. }