process.c 37 KB

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