PageRenderTime 48ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/deps/uv/src/win/process.c

https://gitlab.com/GeekSir/node
C | 1247 lines | 831 code | 191 blank | 225 comment | 232 complexity | 2cbb3d67ff1dc958c5aba39b15ecf60c MD5 | raw file
Possible License(s): 0BSD, Apache-2.0, MPL-2.0-no-copyleft-exception, JSON, WTFPL, CC-BY-SA-3.0, Unlicense, ISC, BSD-3-Clause, MIT, AGPL-3.0
  1. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to
  5. * deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  7. * sell copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  19. * IN THE SOFTWARE.
  20. */
  21. #include <assert.h>
  22. #include <io.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <signal.h>
  26. #include <limits.h>
  27. #include <malloc.h>
  28. #include <wchar.h>
  29. #include "uv.h"
  30. #include "internal.h"
  31. #include "handle-inl.h"
  32. #include "req-inl.h"
  33. #define SIGKILL 9
  34. typedef struct env_var {
  35. const WCHAR* const wide;
  36. const WCHAR* const wide_eq;
  37. const size_t len; /* including null or '=' */
  38. } env_var_t;
  39. #define E_V(str) { L##str, L##str L"=", sizeof(str) }
  40. static const env_var_t required_vars[] = { /* keep me sorted */
  41. E_V("HOMEDRIVE"),
  42. E_V("HOMEPATH"),
  43. E_V("LOGONSERVER"),
  44. E_V("PATH"),
  45. E_V("SYSTEMDRIVE"),
  46. E_V("SYSTEMROOT"),
  47. E_V("TEMP"),
  48. E_V("USERDOMAIN"),
  49. E_V("USERNAME"),
  50. E_V("USERPROFILE"),
  51. E_V("WINDIR"),
  52. };
  53. static size_t n_required_vars = ARRAY_SIZE(required_vars);
  54. static HANDLE uv_global_job_handle_;
  55. static uv_once_t uv_global_job_handle_init_guard_ = UV_ONCE_INIT;
  56. static void uv__init_global_job_handle(void) {
  57. /* Create a job object and set it up to kill all contained processes when
  58. * it's closed. Since this handle is made non-inheritable and we're not
  59. * giving it to anyone, we're the only process holding a reference to it.
  60. * That means that if this process exits it is closed and all the processes
  61. * it contains are killed. All processes created with uv_spawn that are not
  62. * spawned with the UV_PROCESS_DETACHED flag are assigned to this job.
  63. *
  64. * We're setting the JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag so only the
  65. * processes that we explicitly add are affected, and *their* subprocesses
  66. * are not. This ensures that our child processes are not limited in their
  67. * ability to use job control on Windows versions that don't deal with
  68. * nested jobs (prior to Windows 8 / Server 2012). It also lets our child
  69. * processes created detached processes without explicitly breaking away
  70. * from job control (which uv_spawn doesn't, either).
  71. */
  72. SECURITY_ATTRIBUTES attr;
  73. JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
  74. memset(&attr, 0, sizeof attr);
  75. attr.bInheritHandle = FALSE;
  76. memset(&info, 0, sizeof info);
  77. info.BasicLimitInformation.LimitFlags =
  78. JOB_OBJECT_LIMIT_BREAKAWAY_OK |
  79. JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK |
  80. JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION |
  81. JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
  82. uv_global_job_handle_ = CreateJobObjectW(&attr, NULL);
  83. if (uv_global_job_handle_ == NULL)
  84. uv_fatal_error(GetLastError(), "CreateJobObjectW");
  85. if (!SetInformationJobObject(uv_global_job_handle_,
  86. JobObjectExtendedLimitInformation,
  87. &info,
  88. sizeof info))
  89. uv_fatal_error(GetLastError(), "SetInformationJobObject");
  90. }
  91. static int uv_utf8_to_utf16_alloc(const char* s, WCHAR** ws_ptr) {
  92. int ws_len, r;
  93. WCHAR* ws;
  94. ws_len = MultiByteToWideChar(CP_UTF8,
  95. 0,
  96. s,
  97. -1,
  98. NULL,
  99. 0);
  100. if (ws_len <= 0) {
  101. return GetLastError();
  102. }
  103. ws = (WCHAR*) malloc(ws_len * sizeof(WCHAR));
  104. if (ws == NULL) {
  105. return ERROR_OUTOFMEMORY;
  106. }
  107. r = MultiByteToWideChar(CP_UTF8,
  108. 0,
  109. s,
  110. -1,
  111. ws,
  112. ws_len);
  113. assert(r == ws_len);
  114. *ws_ptr = ws;
  115. return 0;
  116. }
  117. static void uv_process_init(uv_loop_t* loop, uv_process_t* handle) {
  118. uv__handle_init(loop, (uv_handle_t*) handle, UV_PROCESS);
  119. handle->exit_cb = NULL;
  120. handle->pid = 0;
  121. handle->exit_signal = 0;
  122. handle->wait_handle = INVALID_HANDLE_VALUE;
  123. handle->process_handle = INVALID_HANDLE_VALUE;
  124. handle->child_stdio_buffer = NULL;
  125. handle->exit_cb_pending = 0;
  126. uv_req_init(loop, (uv_req_t*)&handle->exit_req);
  127. handle->exit_req.type = UV_PROCESS_EXIT;
  128. handle->exit_req.data = handle;
  129. }
  130. /*
  131. * Path search functions
  132. */
  133. /*
  134. * Helper function for search_path
  135. */
  136. static WCHAR* search_path_join_test(const WCHAR* dir,
  137. size_t dir_len,
  138. const WCHAR* name,
  139. size_t name_len,
  140. const WCHAR* ext,
  141. size_t ext_len,
  142. const WCHAR* cwd,
  143. size_t cwd_len) {
  144. WCHAR *result, *result_pos;
  145. DWORD attrs;
  146. if (dir_len > 2 && dir[0] == L'\\' && dir[1] == L'\\') {
  147. /* It's a UNC path so ignore cwd */
  148. cwd_len = 0;
  149. } else if (dir_len >= 1 && (dir[0] == L'/' || dir[0] == L'\\')) {
  150. /* It's a full path without drive letter, use cwd's drive letter only */
  151. cwd_len = 2;
  152. } else if (dir_len >= 2 && dir[1] == L':' &&
  153. (dir_len < 3 || (dir[2] != L'/' && dir[2] != L'\\'))) {
  154. /* It's a relative path with drive letter (ext.g. D:../some/file)
  155. * Replace drive letter in dir by full cwd if it points to the same drive,
  156. * otherwise use the dir only.
  157. */
  158. if (cwd_len < 2 || _wcsnicmp(cwd, dir, 2) != 0) {
  159. cwd_len = 0;
  160. } else {
  161. dir += 2;
  162. dir_len -= 2;
  163. }
  164. } else if (dir_len > 2 && dir[1] == L':') {
  165. /* It's an absolute path with drive letter
  166. * Don't use the cwd at all
  167. */
  168. cwd_len = 0;
  169. }
  170. /* Allocate buffer for output */
  171. result = result_pos = (WCHAR*)malloc(sizeof(WCHAR) *
  172. (cwd_len + 1 + dir_len + 1 + name_len + 1 + ext_len + 1));
  173. /* Copy cwd */
  174. wcsncpy(result_pos, cwd, cwd_len);
  175. result_pos += cwd_len;
  176. /* Add a path separator if cwd didn't end with one */
  177. if (cwd_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
  178. result_pos[0] = L'\\';
  179. result_pos++;
  180. }
  181. /* Copy dir */
  182. wcsncpy(result_pos, dir, dir_len);
  183. result_pos += dir_len;
  184. /* Add a separator if the dir didn't end with one */
  185. if (dir_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
  186. result_pos[0] = L'\\';
  187. result_pos++;
  188. }
  189. /* Copy filename */
  190. wcsncpy(result_pos, name, name_len);
  191. result_pos += name_len;
  192. if (ext_len) {
  193. /* Add a dot if the filename didn't end with one */
  194. if (name_len && result_pos[-1] != '.') {
  195. result_pos[0] = L'.';
  196. result_pos++;
  197. }
  198. /* Copy extension */
  199. wcsncpy(result_pos, ext, ext_len);
  200. result_pos += ext_len;
  201. }
  202. /* Null terminator */
  203. result_pos[0] = L'\0';
  204. attrs = GetFileAttributesW(result);
  205. if (attrs != INVALID_FILE_ATTRIBUTES &&
  206. !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  207. return result;
  208. }
  209. free(result);
  210. return NULL;
  211. }
  212. /*
  213. * Helper function for search_path
  214. */
  215. static WCHAR* path_search_walk_ext(const WCHAR *dir,
  216. size_t dir_len,
  217. const WCHAR *name,
  218. size_t name_len,
  219. WCHAR *cwd,
  220. size_t cwd_len,
  221. int name_has_ext) {
  222. WCHAR* result;
  223. /* If the name itself has a nonempty extension, try this extension first */
  224. if (name_has_ext) {
  225. result = search_path_join_test(dir, dir_len,
  226. name, name_len,
  227. L"", 0,
  228. cwd, cwd_len);
  229. if (result != NULL) {
  230. return result;
  231. }
  232. }
  233. /* Try .com extension */
  234. result = search_path_join_test(dir, dir_len,
  235. name, name_len,
  236. L"com", 3,
  237. cwd, cwd_len);
  238. if (result != NULL) {
  239. return result;
  240. }
  241. /* Try .exe extension */
  242. result = search_path_join_test(dir, dir_len,
  243. name, name_len,
  244. L"exe", 3,
  245. cwd, cwd_len);
  246. if (result != NULL) {
  247. return result;
  248. }
  249. return NULL;
  250. }
  251. /*
  252. * search_path searches the system path for an executable filename -
  253. * the windows API doesn't provide this as a standalone function nor as an
  254. * option to CreateProcess.
  255. *
  256. * It tries to return an absolute filename.
  257. *
  258. * Furthermore, it tries to follow the semantics that cmd.exe, with this
  259. * exception that PATHEXT environment variable isn't used. Since CreateProcess
  260. * can start only .com and .exe files, only those extensions are tried. This
  261. * behavior equals that of msvcrt's spawn functions.
  262. *
  263. * - Do not search the path if the filename already contains a path (either
  264. * relative or absolute).
  265. *
  266. * - If there's really only a filename, check the current directory for file,
  267. * then search all path directories.
  268. *
  269. * - If filename specified has *any* extension, search for the file with the
  270. * specified extension first.
  271. *
  272. * - If the literal filename is not found in a directory, try *appending*
  273. * (not replacing) .com first and then .exe.
  274. *
  275. * - The path variable may contain relative paths; relative paths are relative
  276. * to the cwd.
  277. *
  278. * - Directories in path may or may not end with a trailing backslash.
  279. *
  280. * - CMD does not trim leading/trailing whitespace from path/pathex entries
  281. * nor from the environment variables as a whole.
  282. *
  283. * - When cmd.exe cannot read a directory, it will just skip it and go on
  284. * searching. However, unlike posix-y systems, it will happily try to run a
  285. * file that is not readable/executable; if the spawn fails it will not
  286. * continue searching.
  287. *
  288. * UNC path support: we are dealing with UNC paths in both the path and the
  289. * filename. This is a deviation from what cmd.exe does (it does not let you
  290. * start a program by specifying an UNC path on the command line) but this is
  291. * really a pointless restriction.
  292. *
  293. */
  294. static WCHAR* search_path(const WCHAR *file,
  295. WCHAR *cwd,
  296. const WCHAR *path) {
  297. int file_has_dir;
  298. WCHAR* result = NULL;
  299. WCHAR *file_name_start;
  300. WCHAR *dot;
  301. const WCHAR *dir_start, *dir_end, *dir_path;
  302. size_t dir_len;
  303. int name_has_ext;
  304. size_t file_len = wcslen(file);
  305. size_t cwd_len = wcslen(cwd);
  306. /* If the caller supplies an empty filename,
  307. * we're not gonna return c:\windows\.exe -- GFY!
  308. */
  309. if (file_len == 0
  310. || (file_len == 1 && file[0] == L'.')) {
  311. return NULL;
  312. }
  313. /* Find the start of the filename so we can split the directory from the */
  314. /* name. */
  315. for (file_name_start = (WCHAR*)file + file_len;
  316. file_name_start > file
  317. && file_name_start[-1] != L'\\'
  318. && file_name_start[-1] != L'/'
  319. && file_name_start[-1] != L':';
  320. file_name_start--);
  321. file_has_dir = file_name_start != file;
  322. /* Check if the filename includes an extension */
  323. dot = wcschr(file_name_start, L'.');
  324. name_has_ext = (dot != NULL && dot[1] != L'\0');
  325. if (file_has_dir) {
  326. /* The file has a path inside, don't use path */
  327. result = path_search_walk_ext(
  328. file, file_name_start - file,
  329. file_name_start, file_len - (file_name_start - file),
  330. cwd, cwd_len,
  331. name_has_ext);
  332. } else {
  333. dir_end = path;
  334. /* The file is really only a name; look in cwd first, then scan path */
  335. result = path_search_walk_ext(L"", 0,
  336. file, file_len,
  337. cwd, cwd_len,
  338. name_has_ext);
  339. while (result == NULL) {
  340. if (*dir_end == L'\0') {
  341. break;
  342. }
  343. /* Skip the separator that dir_end now points to */
  344. if (dir_end != path || *path == L';') {
  345. dir_end++;
  346. }
  347. /* Next slice starts just after where the previous one ended */
  348. dir_start = dir_end;
  349. /* Slice until the next ; or \0 is found */
  350. dir_end = wcschr(dir_start, L';');
  351. if (dir_end == NULL) {
  352. dir_end = wcschr(dir_start, L'\0');
  353. }
  354. /* If the slice is zero-length, don't bother */
  355. if (dir_end - dir_start == 0) {
  356. continue;
  357. }
  358. dir_path = dir_start;
  359. dir_len = dir_end - dir_start;
  360. /* Adjust if the path is quoted. */
  361. if (dir_path[0] == '"' || dir_path[0] == '\'') {
  362. ++dir_path;
  363. --dir_len;
  364. }
  365. if (dir_path[dir_len - 1] == '"' || dir_path[dir_len - 1] == '\'') {
  366. --dir_len;
  367. }
  368. result = path_search_walk_ext(dir_path, dir_len,
  369. file, file_len,
  370. cwd, cwd_len,
  371. name_has_ext);
  372. }
  373. }
  374. return result;
  375. }
  376. /*
  377. * Quotes command line arguments
  378. * Returns a pointer to the end (next char to be written) of the buffer
  379. */
  380. WCHAR* quote_cmd_arg(const WCHAR *source, WCHAR *target) {
  381. size_t len = wcslen(source);
  382. size_t i;
  383. int quote_hit;
  384. WCHAR* start;
  385. if (len == 0) {
  386. /* Need double quotation for empty argument */
  387. *(target++) = L'"';
  388. *(target++) = L'"';
  389. return target;
  390. }
  391. if (NULL == wcspbrk(source, L" \t\"")) {
  392. /* No quotation needed */
  393. wcsncpy(target, source, len);
  394. target += len;
  395. return target;
  396. }
  397. if (NULL == wcspbrk(source, L"\"\\")) {
  398. /*
  399. * No embedded double quotes or backlashes, so I can just wrap
  400. * quote marks around the whole thing.
  401. */
  402. *(target++) = L'"';
  403. wcsncpy(target, source, len);
  404. target += len;
  405. *(target++) = L'"';
  406. return target;
  407. }
  408. /*
  409. * Expected input/output:
  410. * input : hello"world
  411. * output: "hello\"world"
  412. * input : hello""world
  413. * output: "hello\"\"world"
  414. * input : hello\world
  415. * output: hello\world
  416. * input : hello\\world
  417. * output: hello\\world
  418. * input : hello\"world
  419. * output: "hello\\\"world"
  420. * input : hello\\"world
  421. * output: "hello\\\\\"world"
  422. * input : hello world\
  423. * output: "hello world\"
  424. */
  425. *(target++) = L'"';
  426. start = target;
  427. quote_hit = 1;
  428. for (i = len; i > 0; --i) {
  429. *(target++) = source[i - 1];
  430. if (quote_hit && source[i - 1] == L'\\') {
  431. *(target++) = L'\\';
  432. } else if(source[i - 1] == L'"') {
  433. quote_hit = 1;
  434. *(target++) = L'\\';
  435. } else {
  436. quote_hit = 0;
  437. }
  438. }
  439. target[0] = L'\0';
  440. wcsrev(start);
  441. *(target++) = L'"';
  442. return target;
  443. }
  444. int make_program_args(char** args, int verbatim_arguments, WCHAR** dst_ptr) {
  445. char** arg;
  446. WCHAR* dst = NULL;
  447. WCHAR* temp_buffer = NULL;
  448. size_t dst_len = 0;
  449. size_t temp_buffer_len = 0;
  450. WCHAR* pos;
  451. int arg_count = 0;
  452. int err = 0;
  453. /* Count the required size. */
  454. for (arg = args; *arg; arg++) {
  455. DWORD arg_len;
  456. arg_len = MultiByteToWideChar(CP_UTF8,
  457. 0,
  458. *arg,
  459. -1,
  460. NULL,
  461. 0);
  462. if (arg_len == 0) {
  463. return GetLastError();
  464. }
  465. dst_len += arg_len;
  466. if (arg_len > temp_buffer_len)
  467. temp_buffer_len = arg_len;
  468. arg_count++;
  469. }
  470. /* Adjust for potential quotes. Also assume the worst-case scenario */
  471. /* that every character needs escaping, so we need twice as much space. */
  472. dst_len = dst_len * 2 + arg_count * 2;
  473. /* Allocate buffer for the final command line. */
  474. dst = (WCHAR*) malloc(dst_len * sizeof(WCHAR));
  475. if (dst == NULL) {
  476. err = ERROR_OUTOFMEMORY;
  477. goto error;
  478. }
  479. /* Allocate temporary working buffer. */
  480. temp_buffer = (WCHAR*) malloc(temp_buffer_len * sizeof(WCHAR));
  481. if (temp_buffer == NULL) {
  482. err = ERROR_OUTOFMEMORY;
  483. goto error;
  484. }
  485. pos = dst;
  486. for (arg = args; *arg; arg++) {
  487. DWORD arg_len;
  488. /* Convert argument to wide char. */
  489. arg_len = MultiByteToWideChar(CP_UTF8,
  490. 0,
  491. *arg,
  492. -1,
  493. temp_buffer,
  494. (int) (dst + dst_len - pos));
  495. if (arg_len == 0) {
  496. err = GetLastError();
  497. goto error;
  498. }
  499. if (verbatim_arguments) {
  500. /* Copy verbatim. */
  501. wcscpy(pos, temp_buffer);
  502. pos += arg_len - 1;
  503. } else {
  504. /* Quote/escape, if needed. */
  505. pos = quote_cmd_arg(temp_buffer, pos);
  506. }
  507. *pos++ = *(arg + 1) ? L' ' : L'\0';
  508. }
  509. free(temp_buffer);
  510. *dst_ptr = dst;
  511. return 0;
  512. error:
  513. free(dst);
  514. free(temp_buffer);
  515. return err;
  516. }
  517. int env_strncmp(const wchar_t* a, int na, const wchar_t* b) {
  518. wchar_t* a_eq;
  519. wchar_t* b_eq;
  520. wchar_t* A;
  521. wchar_t* B;
  522. int nb;
  523. int r;
  524. if (na < 0) {
  525. a_eq = wcschr(a, L'=');
  526. assert(a_eq);
  527. na = (int)(long)(a_eq - a);
  528. } else {
  529. na--;
  530. }
  531. b_eq = wcschr(b, L'=');
  532. assert(b_eq);
  533. nb = b_eq - b;
  534. A = alloca((na+1) * sizeof(wchar_t));
  535. B = alloca((nb+1) * sizeof(wchar_t));
  536. r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, a, na, A, na);
  537. assert(r==na);
  538. A[na] = L'\0';
  539. r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, b, nb, B, nb);
  540. assert(r==nb);
  541. B[nb] = L'\0';
  542. while (1) {
  543. wchar_t AA = *A++;
  544. wchar_t BB = *B++;
  545. if (AA < BB) {
  546. return -1;
  547. } else if (AA > BB) {
  548. return 1;
  549. } else if (!AA && !BB) {
  550. return 0;
  551. }
  552. }
  553. }
  554. static int qsort_wcscmp(const void *a, const void *b) {
  555. wchar_t* astr = *(wchar_t* const*)a;
  556. wchar_t* bstr = *(wchar_t* const*)b;
  557. return env_strncmp(astr, -1, bstr);
  558. }
  559. /*
  560. * The way windows takes environment variables is different than what C does;
  561. * Windows wants a contiguous block of null-terminated strings, terminated
  562. * with an additional null.
  563. *
  564. * Windows has a few "essential" environment variables. winsock will fail
  565. * to initialize if SYSTEMROOT is not defined; some APIs make reference to
  566. * TEMP. SYSTEMDRIVE is probably also important. We therefore ensure that
  567. * these get defined if the input environment block does not contain any
  568. * values for them.
  569. *
  570. * Also add variables known to Cygwin to be required for correct
  571. * subprocess operation in many cases:
  572. * https://github.com/Alexpux/Cygwin/blob/b266b04fbbd3a595f02ea149e4306d3ab9b1fe3d/winsup/cygwin/environ.cc#L955
  573. *
  574. */
  575. int make_program_env(char* env_block[], WCHAR** dst_ptr) {
  576. WCHAR* dst;
  577. WCHAR* ptr;
  578. char** env;
  579. size_t env_len = 0;
  580. int len;
  581. size_t i;
  582. DWORD var_size;
  583. size_t env_block_count = 1; /* 1 for null-terminator */
  584. WCHAR* dst_copy;
  585. WCHAR** ptr_copy;
  586. WCHAR** env_copy;
  587. DWORD* required_vars_value_len = alloca(n_required_vars * sizeof(DWORD*));
  588. /* first pass: determine size in UTF-16 */
  589. for (env = env_block; *env; env++) {
  590. int len;
  591. if (strchr(*env, '=')) {
  592. len = MultiByteToWideChar(CP_UTF8,
  593. 0,
  594. *env,
  595. -1,
  596. NULL,
  597. 0);
  598. if (len <= 0) {
  599. return GetLastError();
  600. }
  601. env_len += len;
  602. env_block_count++;
  603. }
  604. }
  605. /* second pass: copy to UTF-16 environment block */
  606. dst_copy = malloc(env_len * sizeof(WCHAR));
  607. if (!dst_copy) {
  608. return ERROR_OUTOFMEMORY;
  609. }
  610. env_copy = alloca(env_block_count * sizeof(WCHAR*));
  611. ptr = dst_copy;
  612. ptr_copy = env_copy;
  613. for (env = env_block; *env; env++) {
  614. if (strchr(*env, '=')) {
  615. len = MultiByteToWideChar(CP_UTF8,
  616. 0,
  617. *env,
  618. -1,
  619. ptr,
  620. (int) (env_len - (ptr - dst_copy)));
  621. if (len <= 0) {
  622. DWORD err = GetLastError();
  623. free(dst_copy);
  624. return err;
  625. }
  626. *ptr_copy++ = ptr;
  627. ptr += len;
  628. }
  629. }
  630. *ptr_copy = NULL;
  631. assert(env_len == ptr - dst_copy);
  632. /* sort our (UTF-16) copy */
  633. qsort(env_copy, env_block_count-1, sizeof(wchar_t*), qsort_wcscmp);
  634. /* third pass: check for required variables */
  635. for (ptr_copy = env_copy, i = 0; i < n_required_vars; ) {
  636. int cmp;
  637. if (!*ptr_copy) {
  638. cmp = -1;
  639. } else {
  640. cmp = env_strncmp(required_vars[i].wide_eq,
  641. required_vars[i].len,
  642. *ptr_copy);
  643. }
  644. if (cmp < 0) {
  645. /* missing required var */
  646. var_size = GetEnvironmentVariableW(required_vars[i].wide, NULL, 0);
  647. required_vars_value_len[i] = var_size;
  648. if (var_size != 0) {
  649. env_len += required_vars[i].len;
  650. env_len += var_size;
  651. }
  652. i++;
  653. } else {
  654. ptr_copy++;
  655. if (cmp == 0)
  656. i++;
  657. }
  658. }
  659. /* final pass: copy, in sort order, and inserting required variables */
  660. dst = malloc((1+env_len) * sizeof(WCHAR));
  661. if (!dst) {
  662. free(dst_copy);
  663. return ERROR_OUTOFMEMORY;
  664. }
  665. for (ptr = dst, ptr_copy = env_copy, i = 0;
  666. *ptr_copy || i < n_required_vars;
  667. ptr += len) {
  668. int cmp;
  669. if (i >= n_required_vars) {
  670. cmp = 1;
  671. } else if (!*ptr_copy) {
  672. cmp = -1;
  673. } else {
  674. cmp = env_strncmp(required_vars[i].wide_eq,
  675. required_vars[i].len,
  676. *ptr_copy);
  677. }
  678. if (cmp < 0) {
  679. /* missing required var */
  680. len = required_vars_value_len[i];
  681. if (len) {
  682. wcscpy(ptr, required_vars[i].wide_eq);
  683. ptr += required_vars[i].len;
  684. var_size = GetEnvironmentVariableW(required_vars[i].wide,
  685. ptr,
  686. (int) (env_len - (ptr - dst)));
  687. if (var_size != len-1) { /* race condition? */
  688. uv_fatal_error(GetLastError(), "GetEnvironmentVariableW");
  689. }
  690. }
  691. i++;
  692. } else {
  693. /* copy var from env_block */
  694. len = wcslen(*ptr_copy) + 1;
  695. wmemcpy(ptr, *ptr_copy, len);
  696. ptr_copy++;
  697. if (cmp == 0)
  698. i++;
  699. }
  700. }
  701. /* Terminate with an extra NULL. */
  702. assert(env_len == (ptr - dst));
  703. *ptr = L'\0';
  704. free(dst_copy);
  705. *dst_ptr = dst;
  706. return 0;
  707. }
  708. /*
  709. * Attempt to find the value of the PATH environment variable in the child's
  710. * preprocessed environment.
  711. *
  712. * If found, a pointer into `env` is returned. If not found, NULL is returned.
  713. */
  714. static WCHAR* find_path(WCHAR *env) {
  715. for (; env != NULL && *env != 0; env += wcslen(env) + 1) {
  716. if (wcsncmp(env, L"PATH=", 5) == 0)
  717. return &env[5];
  718. }
  719. return NULL;
  720. }
  721. /*
  722. * Called on Windows thread-pool thread to indicate that
  723. * a child process has exited.
  724. */
  725. static void CALLBACK exit_wait_callback(void* data, BOOLEAN didTimeout) {
  726. uv_process_t* process = (uv_process_t*) data;
  727. uv_loop_t* loop = process->loop;
  728. assert(didTimeout == FALSE);
  729. assert(process);
  730. assert(!process->exit_cb_pending);
  731. process->exit_cb_pending = 1;
  732. /* Post completed */
  733. POST_COMPLETION_FOR_REQ(loop, &process->exit_req);
  734. }
  735. /* Called on main thread after a child process has exited. */
  736. void uv_process_proc_exit(uv_loop_t* loop, uv_process_t* handle) {
  737. int64_t exit_code;
  738. DWORD status;
  739. assert(handle->exit_cb_pending);
  740. handle->exit_cb_pending = 0;
  741. /* If we're closing, don't call the exit callback. Just schedule a close */
  742. /* callback now. */
  743. if (handle->flags & UV__HANDLE_CLOSING) {
  744. uv_want_endgame(loop, (uv_handle_t*) handle);
  745. return;
  746. }
  747. /* Unregister from process notification. */
  748. if (handle->wait_handle != INVALID_HANDLE_VALUE) {
  749. UnregisterWait(handle->wait_handle);
  750. handle->wait_handle = INVALID_HANDLE_VALUE;
  751. }
  752. /* Set the handle to inactive: no callbacks will be made after the exit */
  753. /* callback.*/
  754. uv__handle_stop(handle);
  755. if (GetExitCodeProcess(handle->process_handle, &status)) {
  756. exit_code = status;
  757. } else {
  758. /* Unable to to obtain the exit code. This should never happen. */
  759. exit_code = uv_translate_sys_error(GetLastError());
  760. }
  761. /* Fire the exit callback. */
  762. if (handle->exit_cb) {
  763. handle->exit_cb(handle, exit_code, handle->exit_signal);
  764. }
  765. }
  766. void uv_process_close(uv_loop_t* loop, uv_process_t* handle) {
  767. uv__handle_closing(handle);
  768. if (handle->wait_handle != INVALID_HANDLE_VALUE) {
  769. /* This blocks until either the wait was cancelled, or the callback has */
  770. /* completed. */
  771. BOOL r = UnregisterWaitEx(handle->wait_handle, INVALID_HANDLE_VALUE);
  772. if (!r) {
  773. /* This should never happen, and if it happens, we can't recover... */
  774. uv_fatal_error(GetLastError(), "UnregisterWaitEx");
  775. }
  776. handle->wait_handle = INVALID_HANDLE_VALUE;
  777. }
  778. if (!handle->exit_cb_pending) {
  779. uv_want_endgame(loop, (uv_handle_t*)handle);
  780. }
  781. }
  782. void uv_process_endgame(uv_loop_t* loop, uv_process_t* handle) {
  783. assert(!handle->exit_cb_pending);
  784. assert(handle->flags & UV__HANDLE_CLOSING);
  785. assert(!(handle->flags & UV_HANDLE_CLOSED));
  786. /* Clean-up the process handle. */
  787. CloseHandle(handle->process_handle);
  788. uv__handle_close(handle);
  789. }
  790. int uv_spawn(uv_loop_t* loop,
  791. uv_process_t* process,
  792. const uv_process_options_t* options) {
  793. int i;
  794. int err = 0;
  795. WCHAR* path = NULL, *alloc_path = NULL;
  796. BOOL result;
  797. WCHAR* application_path = NULL, *application = NULL, *arguments = NULL,
  798. *env = NULL, *cwd = NULL;
  799. STARTUPINFOW startup;
  800. PROCESS_INFORMATION info;
  801. DWORD process_flags;
  802. uv_process_init(loop, process);
  803. process->exit_cb = options->exit_cb;
  804. if (options->flags & (UV_PROCESS_SETGID | UV_PROCESS_SETUID)) {
  805. return UV_ENOTSUP;
  806. }
  807. if (options->file == NULL ||
  808. options->args == NULL) {
  809. return UV_EINVAL;
  810. }
  811. assert(options->file != NULL);
  812. assert(!(options->flags & ~(UV_PROCESS_DETACHED |
  813. UV_PROCESS_SETGID |
  814. UV_PROCESS_SETUID |
  815. UV_PROCESS_WINDOWS_HIDE |
  816. UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
  817. err = uv_utf8_to_utf16_alloc(options->file, &application);
  818. if (err)
  819. goto done;
  820. err = make_program_args(
  821. options->args,
  822. options->flags & UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS,
  823. &arguments);
  824. if (err)
  825. goto done;
  826. if (options->env) {
  827. err = make_program_env(options->env, &env);
  828. if (err)
  829. goto done;
  830. }
  831. if (options->cwd) {
  832. /* Explicit cwd */
  833. err = uv_utf8_to_utf16_alloc(options->cwd, &cwd);
  834. if (err)
  835. goto done;
  836. } else {
  837. /* Inherit cwd */
  838. DWORD cwd_len, r;
  839. cwd_len = GetCurrentDirectoryW(0, NULL);
  840. if (!cwd_len) {
  841. err = GetLastError();
  842. goto done;
  843. }
  844. cwd = (WCHAR*) malloc(cwd_len * sizeof(WCHAR));
  845. if (cwd == NULL) {
  846. err = ERROR_OUTOFMEMORY;
  847. goto done;
  848. }
  849. r = GetCurrentDirectoryW(cwd_len, cwd);
  850. if (r == 0 || r >= cwd_len) {
  851. err = GetLastError();
  852. goto done;
  853. }
  854. }
  855. /* Get PATH environment variable. */
  856. path = find_path(env);
  857. if (path == NULL) {
  858. DWORD path_len, r;
  859. path_len = GetEnvironmentVariableW(L"PATH", NULL, 0);
  860. if (path_len == 0) {
  861. err = GetLastError();
  862. goto done;
  863. }
  864. alloc_path = (WCHAR*) malloc(path_len * sizeof(WCHAR));
  865. if (alloc_path == NULL) {
  866. err = ERROR_OUTOFMEMORY;
  867. goto done;
  868. }
  869. path = alloc_path;
  870. r = GetEnvironmentVariableW(L"PATH", path, path_len);
  871. if (r == 0 || r >= path_len) {
  872. err = GetLastError();
  873. goto done;
  874. }
  875. }
  876. err = uv__stdio_create(loop, options, &process->child_stdio_buffer);
  877. if (err)
  878. goto done;
  879. application_path = search_path(application,
  880. cwd,
  881. path);
  882. if (application_path == NULL) {
  883. /* Not found. */
  884. err = ERROR_FILE_NOT_FOUND;
  885. goto done;
  886. }
  887. startup.cb = sizeof(startup);
  888. startup.lpReserved = NULL;
  889. startup.lpDesktop = NULL;
  890. startup.lpTitle = NULL;
  891. startup.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  892. startup.cbReserved2 = uv__stdio_size(process->child_stdio_buffer);
  893. startup.lpReserved2 = (BYTE*) process->child_stdio_buffer;
  894. startup.hStdInput = uv__stdio_handle(process->child_stdio_buffer, 0);
  895. startup.hStdOutput = uv__stdio_handle(process->child_stdio_buffer, 1);
  896. startup.hStdError = uv__stdio_handle(process->child_stdio_buffer, 2);
  897. if (options->flags & UV_PROCESS_WINDOWS_HIDE) {
  898. /* Use SW_HIDE to avoid any potential process window. */
  899. startup.wShowWindow = SW_HIDE;
  900. } else {
  901. startup.wShowWindow = SW_SHOWDEFAULT;
  902. }
  903. process_flags = CREATE_UNICODE_ENVIRONMENT;
  904. if (options->flags & UV_PROCESS_DETACHED) {
  905. /* Note that we're not setting the CREATE_BREAKAWAY_FROM_JOB flag. That
  906. * means that libuv might not let you create a fully daemonized process
  907. * when run under job control. However the type of job control that libuv
  908. * itself creates doesn't trickle down to subprocesses so they can still
  909. * daemonize.
  910. *
  911. * A reason to not do this is that CREATE_BREAKAWAY_FROM_JOB makes the
  912. * CreateProcess call fail if we're under job control that doesn't allow
  913. * breakaway.
  914. */
  915. process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
  916. }
  917. if (!CreateProcessW(application_path,
  918. arguments,
  919. NULL,
  920. NULL,
  921. 1,
  922. process_flags,
  923. env,
  924. cwd,
  925. &startup,
  926. &info)) {
  927. /* CreateProcessW failed. */
  928. err = GetLastError();
  929. goto done;
  930. }
  931. /* Spawn succeeded */
  932. /* Beyond this point, failure is reported asynchronously. */
  933. process->process_handle = info.hProcess;
  934. process->pid = info.dwProcessId;
  935. /* If the process isn't spawned as detached, assign to the global job */
  936. /* object so windows will kill it when the parent process dies. */
  937. if (!(options->flags & UV_PROCESS_DETACHED)) {
  938. uv_once(&uv_global_job_handle_init_guard_, uv__init_global_job_handle);
  939. if (!AssignProcessToJobObject(uv_global_job_handle_, info.hProcess)) {
  940. /* AssignProcessToJobObject might fail if this process is under job
  941. * control and the job doesn't have the
  942. * JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag set, on a Windows version
  943. * that doesn't support nested jobs.
  944. *
  945. * When that happens we just swallow the error and continue without
  946. * establishing a kill-child-on-parent-exit relationship, otherwise
  947. * there would be no way for libuv applications run under job control
  948. * to spawn processes at all.
  949. */
  950. DWORD err = GetLastError();
  951. if (err != ERROR_ACCESS_DENIED)
  952. uv_fatal_error(err, "AssignProcessToJobObject");
  953. }
  954. }
  955. /* Set IPC pid to all IPC pipes. */
  956. for (i = 0; i < options->stdio_count; i++) {
  957. const uv_stdio_container_t* fdopt = &options->stdio[i];
  958. if (fdopt->flags & UV_CREATE_PIPE &&
  959. fdopt->data.stream->type == UV_NAMED_PIPE &&
  960. ((uv_pipe_t*) fdopt->data.stream)->ipc) {
  961. ((uv_pipe_t*) fdopt->data.stream)->pipe.conn.ipc_pid = info.dwProcessId;
  962. }
  963. }
  964. /* Setup notifications for when the child process exits. */
  965. result = RegisterWaitForSingleObject(&process->wait_handle,
  966. process->process_handle, exit_wait_callback, (void*)process, INFINITE,
  967. WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE);
  968. if (!result) {
  969. uv_fatal_error(GetLastError(), "RegisterWaitForSingleObject");
  970. }
  971. CloseHandle(info.hThread);
  972. assert(!err);
  973. /* Make the handle active. It will remain active until the exit callback */
  974. /* is made or the handle is closed, whichever happens first. */
  975. uv__handle_start(process);
  976. /* Cleanup, whether we succeeded or failed. */
  977. done:
  978. free(application);
  979. free(application_path);
  980. free(arguments);
  981. free(cwd);
  982. free(env);
  983. free(alloc_path);
  984. if (process->child_stdio_buffer != NULL) {
  985. /* Clean up child stdio handles. */
  986. uv__stdio_destroy(process->child_stdio_buffer);
  987. process->child_stdio_buffer = NULL;
  988. }
  989. return uv_translate_sys_error(err);
  990. }
  991. static int uv__kill(HANDLE process_handle, int signum) {
  992. switch (signum) {
  993. case SIGTERM:
  994. case SIGKILL:
  995. case SIGINT: {
  996. /* Unconditionally terminate the process. On Windows, killed processes */
  997. /* normally return 1. */
  998. DWORD status;
  999. int err;
  1000. if (TerminateProcess(process_handle, 1))
  1001. return 0;
  1002. /* If the process already exited before TerminateProcess was called, */
  1003. /* TerminateProcess will fail with ERROR_ACCESS_DENIED. */
  1004. err = GetLastError();
  1005. if (err == ERROR_ACCESS_DENIED &&
  1006. GetExitCodeProcess(process_handle, &status) &&
  1007. status != STILL_ACTIVE) {
  1008. return UV_ESRCH;
  1009. }
  1010. return uv_translate_sys_error(err);
  1011. }
  1012. case 0: {
  1013. /* Health check: is the process still alive? */
  1014. DWORD status;
  1015. if (!GetExitCodeProcess(process_handle, &status))
  1016. return uv_translate_sys_error(GetLastError());
  1017. if (status != STILL_ACTIVE)
  1018. return UV_ESRCH;
  1019. return 0;
  1020. }
  1021. default:
  1022. /* Unsupported signal. */
  1023. return UV_ENOSYS;
  1024. }
  1025. }
  1026. int uv_process_kill(uv_process_t* process, int signum) {
  1027. int err;
  1028. if (process->process_handle == INVALID_HANDLE_VALUE) {
  1029. return UV_EINVAL;
  1030. }
  1031. err = uv__kill(process->process_handle, signum);
  1032. if (err) {
  1033. return err; /* err is already translated. */
  1034. }
  1035. process->exit_signal = signum;
  1036. return 0;
  1037. }
  1038. int uv_kill(int pid, int signum) {
  1039. int err;
  1040. HANDLE process_handle = OpenProcess(PROCESS_TERMINATE |
  1041. PROCESS_QUERY_INFORMATION, FALSE, pid);
  1042. if (process_handle == NULL) {
  1043. err = GetLastError();
  1044. if (err == ERROR_INVALID_PARAMETER) {
  1045. return UV_ESRCH;
  1046. } else {
  1047. return uv_translate_sys_error(err);
  1048. }
  1049. }
  1050. err = uv__kill(process_handle, signum);
  1051. CloseHandle(process_handle);
  1052. return err; /* err is already translated. */
  1053. }