• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
22 #include <assert.h>
23 #include <io.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <signal.h>
27 #include <limits.h>
28 #include <wchar.h>
29 #include <malloc.h>    /* _alloca */
30 
31 #include "uv.h"
32 #include "internal.h"
33 #include "handle-inl.h"
34 #include "req-inl.h"
35 #include <dbghelp.h>
36 #include <shlobj.h>
37 #include <psapi.h>     /* GetModuleBaseNameW */
38 
39 
40 #define SIGKILL         9
41 
42 
43 typedef struct env_var {
44   const WCHAR* const wide;
45   const WCHAR* const wide_eq;
46   const size_t len; /* including null or '=' */
47 } env_var_t;
48 
49 #define E_V(str) { L##str, L##str L"=", sizeof(str) }
50 
51 static const env_var_t required_vars[] = { /* keep me sorted */
52   E_V("HOMEDRIVE"),
53   E_V("HOMEPATH"),
54   E_V("LOGONSERVER"),
55   E_V("PATH"),
56   E_V("SYSTEMDRIVE"),
57   E_V("SYSTEMROOT"),
58   E_V("TEMP"),
59   E_V("USERDOMAIN"),
60   E_V("USERNAME"),
61   E_V("USERPROFILE"),
62   E_V("WINDIR"),
63 };
64 
65 
66 static HANDLE uv_global_job_handle_;
67 static uv_once_t uv_global_job_handle_init_guard_ = UV_ONCE_INIT;
68 
69 
uv__init_global_job_handle(void)70 static void uv__init_global_job_handle(void) {
71   /* Create a job object and set it up to kill all contained processes when
72    * it's closed. Since this handle is made non-inheritable and we're not
73    * giving it to anyone, we're the only process holding a reference to it.
74    * That means that if this process exits it is closed and all the processes
75    * it contains are killed. All processes created with uv_spawn that are not
76    * spawned with the UV_PROCESS_DETACHED flag are assigned to this job.
77    *
78    * We're setting the JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag so only the
79    * processes that we explicitly add are affected, and *their* subprocesses
80    * are not. This ensures that our child processes are not limited in their
81    * ability to use job control on Windows versions that don't deal with
82    * nested jobs (prior to Windows 8 / Server 2012). It also lets our child
83    * processes created detached processes without explicitly breaking away
84    * from job control (which uv_spawn doesn't, either).
85    */
86   SECURITY_ATTRIBUTES attr;
87   JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
88 
89   memset(&attr, 0, sizeof attr);
90   attr.bInheritHandle = FALSE;
91 
92   memset(&info, 0, sizeof info);
93   info.BasicLimitInformation.LimitFlags =
94       JOB_OBJECT_LIMIT_BREAKAWAY_OK |
95       JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK |
96       JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION |
97       JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
98 
99   uv_global_job_handle_ = CreateJobObjectW(&attr, NULL);
100   if (uv_global_job_handle_ == NULL)
101     uv_fatal_error(GetLastError(), "CreateJobObjectW");
102 
103   if (!SetInformationJobObject(uv_global_job_handle_,
104                                JobObjectExtendedLimitInformation,
105                                &info,
106                                sizeof info))
107     uv_fatal_error(GetLastError(), "SetInformationJobObject");
108 
109 
110   if (!AssignProcessToJobObject(uv_global_job_handle_, GetCurrentProcess())) {
111     /* Make sure this handle is functional. The Windows kernel has a bug that
112      * if the first use of AssignProcessToJobObject is for a Windows Store
113      * program, subsequent attempts to use the handle with fail with
114      * INVALID_PARAMETER (87). This is possibly because all uses of the handle
115      * must be for the same Terminal Services session. We can ensure it is tied
116      * to our current session now by adding ourself to it. We could remove
117      * ourself afterwards, but there doesn't seem to be a reason to.
118      */
119     DWORD err = GetLastError();
120     if (err != ERROR_ACCESS_DENIED)
121       uv_fatal_error(err, "AssignProcessToJobObject");
122   }
123 }
124 
125 
uv__utf8_to_utf16_alloc(const char * s,WCHAR ** ws_ptr)126 static int uv__utf8_to_utf16_alloc(const char* s, WCHAR** ws_ptr) {
127   return uv__convert_utf8_to_utf16(s, ws_ptr);
128 }
129 
130 
uv__process_init(uv_loop_t * loop,uv_process_t * handle)131 static void uv__process_init(uv_loop_t* loop, uv_process_t* handle) {
132   uv__handle_init(loop, (uv_handle_t*) handle, UV_PROCESS);
133   handle->exit_cb = NULL;
134   handle->pid = 0;
135   handle->exit_signal = 0;
136   handle->wait_handle = INVALID_HANDLE_VALUE;
137   handle->process_handle = INVALID_HANDLE_VALUE;
138   handle->exit_cb_pending = 0;
139 
140   UV_REQ_INIT(&handle->exit_req, UV_PROCESS_EXIT);
141   handle->exit_req.data = handle;
142 }
143 
144 
145 /*
146  * Path search functions
147  */
148 
149 /*
150  * Helper function for search_path
151  */
search_path_join_test(const WCHAR * dir,size_t dir_len,const WCHAR * name,size_t name_len,const WCHAR * ext,size_t ext_len,const WCHAR * cwd,size_t cwd_len)152 static WCHAR* search_path_join_test(const WCHAR* dir,
153                                     size_t dir_len,
154                                     const WCHAR* name,
155                                     size_t name_len,
156                                     const WCHAR* ext,
157                                     size_t ext_len,
158                                     const WCHAR* cwd,
159                                     size_t cwd_len) {
160   WCHAR *result, *result_pos;
161   DWORD attrs;
162   if (dir_len > 2 &&
163       ((dir[0] == L'\\' || dir[0] == L'/') &&
164        (dir[1] == L'\\' || dir[1] == L'/'))) {
165     /* It's a UNC path so ignore cwd */
166     cwd_len = 0;
167   } else if (dir_len >= 1 && (dir[0] == L'/' || dir[0] == L'\\')) {
168     /* It's a full path without drive letter, use cwd's drive letter only */
169     cwd_len = 2;
170   } else if (dir_len >= 2 && dir[1] == L':' &&
171       (dir_len < 3 || (dir[2] != L'/' && dir[2] != L'\\'))) {
172     /* It's a relative path with drive letter (ext.g. D:../some/file)
173      * Replace drive letter in dir by full cwd if it points to the same drive,
174      * otherwise use the dir only.
175      */
176     if (cwd_len < 2 || _wcsnicmp(cwd, dir, 2) != 0) {
177       cwd_len = 0;
178     } else {
179       dir += 2;
180       dir_len -= 2;
181     }
182   } else if (dir_len > 2 && dir[1] == L':') {
183     /* It's an absolute path with drive letter
184      * Don't use the cwd at all
185      */
186     cwd_len = 0;
187   }
188 
189   /* Allocate buffer for output */
190   result = result_pos = (WCHAR*)uv__malloc(sizeof(WCHAR) *
191       (cwd_len + 1 + dir_len + 1 + name_len + 1 + ext_len + 1));
192 
193   /* Copy cwd */
194   wcsncpy(result_pos, cwd, cwd_len);
195   result_pos += cwd_len;
196 
197   /* Add a path separator if cwd didn't end with one */
198   if (cwd_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
199     result_pos[0] = L'\\';
200     result_pos++;
201   }
202 
203   /* Copy dir */
204   wcsncpy(result_pos, dir, dir_len);
205   result_pos += dir_len;
206 
207   /* Add a separator if the dir didn't end with one */
208   if (dir_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
209     result_pos[0] = L'\\';
210     result_pos++;
211   }
212 
213   /* Copy filename */
214   wcsncpy(result_pos, name, name_len);
215   result_pos += name_len;
216 
217   if (ext_len) {
218     /* Add a dot if the filename didn't end with one */
219     if (name_len && result_pos[-1] != '.') {
220       result_pos[0] = L'.';
221       result_pos++;
222     }
223 
224     /* Copy extension */
225     wcsncpy(result_pos, ext, ext_len);
226     result_pos += ext_len;
227   }
228 
229   /* Null terminator */
230   result_pos[0] = L'\0';
231 
232   attrs = GetFileAttributesW(result);
233 
234   if (attrs != INVALID_FILE_ATTRIBUTES &&
235       !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
236     return result;
237   }
238 
239   uv__free(result);
240   return NULL;
241 }
242 
243 
244 /*
245  * Helper function for search_path
246  */
path_search_walk_ext(const WCHAR * dir,size_t dir_len,const WCHAR * name,size_t name_len,WCHAR * cwd,size_t cwd_len,int name_has_ext)247 static WCHAR* path_search_walk_ext(const WCHAR *dir,
248                                    size_t dir_len,
249                                    const WCHAR *name,
250                                    size_t name_len,
251                                    WCHAR *cwd,
252                                    size_t cwd_len,
253                                    int name_has_ext) {
254   WCHAR* result;
255 
256   /* If the name itself has a nonempty extension, try this extension first */
257   if (name_has_ext) {
258     result = search_path_join_test(dir, dir_len,
259                                    name, name_len,
260                                    L"", 0,
261                                    cwd, cwd_len);
262     if (result != NULL) {
263       return result;
264     }
265   }
266 
267   /* Try .com extension */
268   result = search_path_join_test(dir, dir_len,
269                                  name, name_len,
270                                  L"com", 3,
271                                  cwd, cwd_len);
272   if (result != NULL) {
273     return result;
274   }
275 
276   /* Try .exe extension */
277   result = search_path_join_test(dir, dir_len,
278                                  name, name_len,
279                                  L"exe", 3,
280                                  cwd, cwd_len);
281   if (result != NULL) {
282     return result;
283   }
284 
285   return NULL;
286 }
287 
288 
289 /*
290  * search_path searches the system path for an executable filename -
291  * the windows API doesn't provide this as a standalone function nor as an
292  * option to CreateProcess.
293  *
294  * It tries to return an absolute filename.
295  *
296  * Furthermore, it tries to follow the semantics that cmd.exe, with this
297  * exception that PATHEXT environment variable isn't used. Since CreateProcess
298  * can start only .com and .exe files, only those extensions are tried. This
299  * behavior equals that of msvcrt's spawn functions.
300  *
301  * - Do not search the path if the filename already contains a path (either
302  *   relative or absolute).
303  *
304  * - If there's really only a filename, check the current directory for file,
305  *   then search all path directories.
306  *
307  * - If filename specified has *any* extension, or already contains a path
308  *   and the UV_PROCESS_WINDOWS_FILE_PATH_EXACT_NAME flag is specified,
309  *   search for the file with the exact specified filename first.
310  *
311  * - If the literal filename is not found in a directory, try *appending*
312  *   (not replacing) .com first and then .exe.
313  *
314  * - The path variable may contain relative paths; relative paths are relative
315  *   to the cwd.
316  *
317  * - Directories in path may or may not end with a trailing backslash.
318  *
319  * - CMD does not trim leading/trailing whitespace from path/pathex entries
320  *   nor from the environment variables as a whole.
321  *
322  * - When cmd.exe cannot read a directory, it will just skip it and go on
323  *   searching. However, unlike posix-y systems, it will happily try to run a
324  *   file that is not readable/executable; if the spawn fails it will not
325  *   continue searching.
326  *
327  * UNC path support: we are dealing with UNC paths in both the path and the
328  * filename. This is a deviation from what cmd.exe does (it does not let you
329  * start a program by specifying an UNC path on the command line) but this is
330  * really a pointless restriction.
331  *
332  */
search_path(const WCHAR * file,WCHAR * cwd,const WCHAR * path,unsigned int flags)333 static WCHAR* search_path(const WCHAR *file,
334                             WCHAR *cwd,
335                             const WCHAR *path,
336                             unsigned int flags) {
337   int file_has_dir;
338   WCHAR* result = NULL;
339   WCHAR *file_name_start;
340   WCHAR *dot;
341   const WCHAR *dir_start, *dir_end, *dir_path;
342   size_t dir_len;
343   int name_has_ext;
344 
345   size_t file_len = wcslen(file);
346   size_t cwd_len = wcslen(cwd);
347 
348   /* If the caller supplies an empty filename,
349    * we're not gonna return c:\windows\.exe -- GFY!
350    */
351   if (file_len == 0
352       || (file_len == 1 && file[0] == L'.')) {
353     return NULL;
354   }
355 
356   /* Find the start of the filename so we can split the directory from the
357    * name. */
358   for (file_name_start = (WCHAR*)file + file_len;
359        file_name_start > file
360            && file_name_start[-1] != L'\\'
361            && file_name_start[-1] != L'/'
362            && file_name_start[-1] != L':';
363        file_name_start--);
364 
365   file_has_dir = file_name_start != file;
366 
367   /* Check if the filename includes an extension */
368   dot = wcschr(file_name_start, L'.');
369   name_has_ext = (dot != NULL && dot[1] != L'\0');
370 
371   if (file_has_dir) {
372     /* The file has a path inside, don't use path */
373     result = path_search_walk_ext(
374         file, file_name_start - file,
375         file_name_start, file_len - (file_name_start - file),
376         cwd, cwd_len,
377         name_has_ext || (flags & UV_PROCESS_WINDOWS_FILE_PATH_EXACT_NAME));
378 
379   } else {
380     dir_end = path;
381 
382     if (NeedCurrentDirectoryForExePathW(L"")) {
383       /* The file is really only a name; look in cwd first, then scan path */
384       result = path_search_walk_ext(L"", 0,
385                                     file, file_len,
386                                     cwd, cwd_len,
387                                     name_has_ext);
388     }
389 
390     while (result == NULL) {
391       if (dir_end == NULL || *dir_end == L'\0') {
392         break;
393       }
394 
395       /* Skip the separator that dir_end now points to */
396       if (dir_end != path || *path == L';') {
397         dir_end++;
398       }
399 
400       /* Next slice starts just after where the previous one ended */
401       dir_start = dir_end;
402 
403       /* If path is quoted, find quote end */
404       if (*dir_start == L'"' || *dir_start == L'\'') {
405         dir_end = wcschr(dir_start + 1, *dir_start);
406         if (dir_end == NULL) {
407           dir_end = wcschr(dir_start, L'\0');
408         }
409       }
410       /* Slice until the next ; or \0 is found */
411       dir_end = wcschr(dir_end, L';');
412       if (dir_end == NULL) {
413         dir_end = wcschr(dir_start, L'\0');
414       }
415 
416       /* If the slice is zero-length, don't bother */
417       if (dir_end - dir_start == 0) {
418         continue;
419       }
420 
421       dir_path = dir_start;
422       dir_len = dir_end - dir_start;
423 
424       /* Adjust if the path is quoted. */
425       if (dir_path[0] == '"' || dir_path[0] == '\'') {
426         ++dir_path;
427         --dir_len;
428       }
429 
430       if (dir_path[dir_len - 1] == '"' || dir_path[dir_len - 1] == '\'') {
431         --dir_len;
432       }
433 
434       result = path_search_walk_ext(dir_path, dir_len,
435                                     file, file_len,
436                                     cwd, cwd_len,
437                                     name_has_ext);
438     }
439   }
440 
441   return result;
442 }
443 
444 
445 /*
446  * Quotes command line arguments
447  * Returns a pointer to the end (next char to be written) of the buffer
448  */
quote_cmd_arg(const WCHAR * source,WCHAR * target)449 WCHAR* quote_cmd_arg(const WCHAR *source, WCHAR *target) {
450   size_t len = wcslen(source);
451   size_t i;
452   int quote_hit;
453   WCHAR* start;
454 
455   if (len == 0) {
456     /* Need double quotation for empty argument */
457     *(target++) = L'"';
458     *(target++) = L'"';
459     return target;
460   }
461 
462   if (NULL == wcspbrk(source, L" \t\"")) {
463     /* No quotation needed */
464     wcsncpy(target, source, len);
465     target += len;
466     return target;
467   }
468 
469   if (NULL == wcspbrk(source, L"\"\\")) {
470     /*
471      * No embedded double quotes or backlashes, so I can just wrap
472      * quote marks around the whole thing.
473      */
474     *(target++) = L'"';
475     wcsncpy(target, source, len);
476     target += len;
477     *(target++) = L'"';
478     return target;
479   }
480 
481   /*
482    * Expected input/output:
483    *   input : hello"world
484    *   output: "hello\"world"
485    *   input : hello""world
486    *   output: "hello\"\"world"
487    *   input : hello\world
488    *   output: hello\world
489    *   input : hello\\world
490    *   output: hello\\world
491    *   input : hello\"world
492    *   output: "hello\\\"world"
493    *   input : hello\\"world
494    *   output: "hello\\\\\"world"
495    *   input : hello world\
496    *   output: "hello world\\"
497    */
498 
499   *(target++) = L'"';
500   start = target;
501   quote_hit = 1;
502 
503   for (i = len; i > 0; --i) {
504     *(target++) = source[i - 1];
505 
506     if (quote_hit && source[i - 1] == L'\\') {
507       *(target++) = L'\\';
508     } else if(source[i - 1] == L'"') {
509       quote_hit = 1;
510       *(target++) = L'\\';
511     } else {
512       quote_hit = 0;
513     }
514   }
515   target[0] = L'\0';
516   _wcsrev(start);
517   *(target++) = L'"';
518   return target;
519 }
520 
521 
make_program_args(char ** args,int verbatim_arguments,WCHAR ** dst_ptr)522 int make_program_args(char** args, int verbatim_arguments, WCHAR** dst_ptr) {
523   char** arg;
524   WCHAR* dst = NULL;
525   WCHAR* temp_buffer = NULL;
526   size_t dst_len = 0;
527   size_t temp_buffer_len = 0;
528   WCHAR* pos;
529   int arg_count = 0;
530   int err = 0;
531 
532   /* Count the required size. */
533   for (arg = args; *arg; arg++) {
534     ssize_t arg_len;
535 
536     arg_len = uv_wtf8_length_as_utf16(*arg);
537     if (arg_len < 0)
538       return arg_len;
539 
540     dst_len += arg_len;
541 
542     if ((size_t) arg_len > temp_buffer_len)
543       temp_buffer_len = arg_len;
544 
545     arg_count++;
546   }
547 
548   /* Adjust for potential quotes. Also assume the worst-case scenario that
549    * every character needs escaping, so we need twice as much space. */
550   dst_len = dst_len * 2 + arg_count * 2;
551 
552   /* Allocate buffer for the final command line. */
553   dst = uv__malloc(dst_len * sizeof(WCHAR));
554   if (dst == NULL) {
555     err = UV_ENOMEM;
556     goto error;
557   }
558 
559   /* Allocate temporary working buffer. */
560   temp_buffer = uv__malloc(temp_buffer_len * sizeof(WCHAR));
561   if (temp_buffer == NULL) {
562     err = UV_ENOMEM;
563     goto error;
564   }
565 
566   pos = dst;
567   for (arg = args; *arg; arg++) {
568     ssize_t arg_len;
569 
570     /* Convert argument to wide char. */
571     arg_len = uv_wtf8_length_as_utf16(*arg);
572     assert(arg_len > 0);
573     assert(temp_buffer_len >= (size_t) arg_len);
574     uv_wtf8_to_utf16(*arg, temp_buffer, arg_len);
575 
576     if (verbatim_arguments) {
577       /* Copy verbatim. */
578       wcscpy(pos, temp_buffer);
579       pos += arg_len - 1;
580     } else {
581       /* Quote/escape, if needed. */
582       pos = quote_cmd_arg(temp_buffer, pos);
583     }
584 
585     *pos++ = *(arg + 1) ? L' ' : L'\0';
586     assert(pos <= dst + dst_len);
587   }
588 
589   uv__free(temp_buffer);
590 
591   *dst_ptr = dst;
592   return 0;
593 
594 error:
595   uv__free(dst);
596   uv__free(temp_buffer);
597   return err;
598 }
599 
600 
env_strncmp(const wchar_t * a,int na,const wchar_t * b)601 int env_strncmp(const wchar_t* a, int na, const wchar_t* b) {
602   wchar_t* a_eq;
603   wchar_t* b_eq;
604   wchar_t* A;
605   wchar_t* B;
606   int nb;
607   int r;
608 
609   if (na < 0) {
610     a_eq = wcschr(a, L'=');
611     assert(a_eq);
612     na = (int)(long)(a_eq - a);
613   } else {
614     na--;
615   }
616   b_eq = wcschr(b, L'=');
617   assert(b_eq);
618   nb = b_eq - b;
619 
620   A = _alloca((na+1) * sizeof(wchar_t));
621   B = _alloca((nb+1) * sizeof(wchar_t));
622 
623   r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, a, na, A, na);
624   assert(r==na);
625   A[na] = L'\0';
626   r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, b, nb, B, nb);
627   assert(r==nb);
628   B[nb] = L'\0';
629 
630   for (;;) {
631     wchar_t AA = *A++;
632     wchar_t BB = *B++;
633     if (AA < BB) {
634       return -1;
635     } else if (AA > BB) {
636       return 1;
637     } else if (!AA && !BB) {
638       return 0;
639     }
640   }
641 }
642 
643 
qsort_wcscmp(const void * a,const void * b)644 static int qsort_wcscmp(const void *a, const void *b) {
645   wchar_t* astr = *(wchar_t* const*)a;
646   wchar_t* bstr = *(wchar_t* const*)b;
647   return env_strncmp(astr, -1, bstr);
648 }
649 
650 
651 /*
652  * The way windows takes environment variables is different than what C does;
653  * Windows wants a contiguous block of null-terminated strings, terminated
654  * with an additional null.
655  *
656  * Windows has a few "essential" environment variables. winsock will fail
657  * to initialize if SYSTEMROOT is not defined; some APIs make reference to
658  * TEMP. SYSTEMDRIVE is probably also important. We therefore ensure that
659  * these get defined if the input environment block does not contain any
660  * values for them.
661  *
662  * Also add variables known to Cygwin to be required for correct
663  * subprocess operation in many cases:
664  * https://github.com/Alexpux/Cygwin/blob/b266b04fbbd3a595f02ea149e4306d3ab9b1fe3d/winsup/cygwin/environ.cc#L955
665  *
666  */
make_program_env(char * env_block[],WCHAR ** dst_ptr)667 int make_program_env(char* env_block[], WCHAR** dst_ptr) {
668   WCHAR* dst;
669   WCHAR* ptr;
670   char** env;
671   size_t env_len = 0;
672   size_t len;
673   size_t i;
674   size_t var_size;
675   size_t env_block_count = 1; /* 1 for null-terminator */
676   WCHAR* dst_copy;
677   WCHAR** ptr_copy;
678   WCHAR** env_copy;
679   size_t required_vars_value_len[ARRAY_SIZE(required_vars)];
680 
681   /* first pass: determine size in UTF-16 */
682   for (env = env_block; *env; env++) {
683     ssize_t len;
684     if (strchr(*env, '=')) {
685       len = uv_wtf8_length_as_utf16(*env);
686       if (len < 0)
687         return len;
688       env_len += len;
689       env_block_count++;
690     }
691   }
692 
693   /* second pass: copy to UTF-16 environment block */
694   dst_copy = uv__malloc(env_len * sizeof(WCHAR));
695   if (dst_copy == NULL && env_len > 0) {
696     return UV_ENOMEM;
697   }
698   env_copy = _alloca(env_block_count * sizeof(WCHAR*));
699 
700   ptr = dst_copy;
701   ptr_copy = env_copy;
702   for (env = env_block; *env; env++) {
703     ssize_t len;
704     if (strchr(*env, '=')) {
705       len = uv_wtf8_length_as_utf16(*env);
706       assert(len > 0);
707       assert((size_t) len <= env_len - (ptr - dst_copy));
708       uv_wtf8_to_utf16(*env, ptr, len);
709       *ptr_copy++ = ptr;
710       ptr += len;
711     }
712   }
713   *ptr_copy = NULL;
714   assert(env_len == 0 || env_len == (size_t) (ptr - dst_copy));
715 
716   /* sort our (UTF-16) copy */
717   qsort(env_copy, env_block_count-1, sizeof(wchar_t*), qsort_wcscmp);
718 
719   /* third pass: check for required variables */
720   for (ptr_copy = env_copy, i = 0; i < ARRAY_SIZE(required_vars); ) {
721     int cmp;
722     if (!*ptr_copy) {
723       cmp = -1;
724     } else {
725       cmp = env_strncmp(required_vars[i].wide_eq,
726                         required_vars[i].len,
727                         *ptr_copy);
728     }
729     if (cmp < 0) {
730       /* missing required var */
731       var_size = GetEnvironmentVariableW(required_vars[i].wide, NULL, 0);
732       required_vars_value_len[i] = var_size;
733       if (var_size != 0) {
734         env_len += required_vars[i].len;
735         env_len += var_size;
736       }
737       i++;
738     } else {
739       ptr_copy++;
740       if (cmp == 0)
741         i++;
742     }
743   }
744 
745   /* final pass: copy, in sort order, and inserting required variables */
746   dst = uv__malloc((1+env_len) * sizeof(WCHAR));
747   if (!dst) {
748     uv__free(dst_copy);
749     return UV_ENOMEM;
750   }
751 
752   for (ptr = dst, ptr_copy = env_copy, i = 0;
753        *ptr_copy || i < ARRAY_SIZE(required_vars);
754        ptr += len) {
755     int cmp;
756     if (i >= ARRAY_SIZE(required_vars)) {
757       cmp = 1;
758     } else if (!*ptr_copy) {
759       cmp = -1;
760     } else {
761       cmp = env_strncmp(required_vars[i].wide_eq,
762                         required_vars[i].len,
763                         *ptr_copy);
764     }
765     if (cmp < 0) {
766       /* missing required var */
767       len = required_vars_value_len[i];
768       if (len) {
769         wcscpy(ptr, required_vars[i].wide_eq);
770         ptr += required_vars[i].len;
771         var_size = GetEnvironmentVariableW(required_vars[i].wide,
772                                            ptr,
773                                            (int) (env_len - (ptr - dst)));
774         if (var_size != (DWORD) (len - 1)) { /* TODO: handle race condition? */
775           uv_fatal_error(GetLastError(), "GetEnvironmentVariableW");
776         }
777       }
778       i++;
779     } else {
780       /* copy var from env_block */
781       len = wcslen(*ptr_copy) + 1;
782       wmemcpy(ptr, *ptr_copy, len);
783       ptr_copy++;
784       if (cmp == 0)
785         i++;
786     }
787   }
788 
789   /* Terminate with an extra NULL. */
790   assert(env_len == (size_t) (ptr - dst));
791   *ptr = L'\0';
792 
793   uv__free(dst_copy);
794   *dst_ptr = dst;
795   return 0;
796 }
797 
798 /*
799  * Attempt to find the value of the PATH environment variable in the child's
800  * preprocessed environment.
801  *
802  * If found, a pointer into `env` is returned. If not found, NULL is returned.
803  */
find_path(WCHAR * env)804 static WCHAR* find_path(WCHAR *env) {
805   for (; env != NULL && *env != 0; env += wcslen(env) + 1) {
806     if ((env[0] == L'P' || env[0] == L'p') &&
807         (env[1] == L'A' || env[1] == L'a') &&
808         (env[2] == L'T' || env[2] == L't') &&
809         (env[3] == L'H' || env[3] == L'h') &&
810         (env[4] == L'=')) {
811       return &env[5];
812     }
813   }
814 
815   return NULL;
816 }
817 
818 /*
819  * Called on Windows thread-pool thread to indicate that
820  * a child process has exited.
821  */
exit_wait_callback(void * data,BOOLEAN didTimeout)822 static void CALLBACK exit_wait_callback(void* data, BOOLEAN didTimeout) {
823   uv_process_t* process = (uv_process_t*) data;
824   uv_loop_t* loop = process->loop;
825 
826   assert(didTimeout == FALSE);
827   assert(process);
828   assert(!process->exit_cb_pending);
829 
830   process->exit_cb_pending = 1;
831 
832   /* Post completed */
833   POST_COMPLETION_FOR_REQ(loop, &process->exit_req);
834 }
835 
836 
837 /* Called on main thread after a child process has exited. */
uv__process_proc_exit(uv_loop_t * loop,uv_process_t * handle)838 void uv__process_proc_exit(uv_loop_t* loop, uv_process_t* handle) {
839   int64_t exit_code;
840   DWORD status;
841 
842   assert(handle->exit_cb_pending);
843   handle->exit_cb_pending = 0;
844 
845   /* If we're closing, don't call the exit callback. Just schedule a close
846    * callback now. */
847   if (handle->flags & UV_HANDLE_CLOSING) {
848     uv__want_endgame(loop, (uv_handle_t*) handle);
849     return;
850   }
851 
852   /* Unregister from process notification. */
853   if (handle->wait_handle != INVALID_HANDLE_VALUE) {
854     UnregisterWait(handle->wait_handle);
855     handle->wait_handle = INVALID_HANDLE_VALUE;
856   }
857 
858   /* Set the handle to inactive: no callbacks will be made after the exit
859    * callback. */
860   uv__handle_stop(handle);
861 
862   if (GetExitCodeProcess(handle->process_handle, &status)) {
863     exit_code = status;
864   } else {
865     /* Unable to obtain the exit code. This should never happen. */
866     exit_code = uv_translate_sys_error(GetLastError());
867   }
868 
869   /* Fire the exit callback. */
870   if (handle->exit_cb) {
871     handle->exit_cb(handle, exit_code, handle->exit_signal);
872   }
873 }
874 
875 
uv__process_close(uv_loop_t * loop,uv_process_t * handle)876 void uv__process_close(uv_loop_t* loop, uv_process_t* handle) {
877   uv__handle_closing(handle);
878 
879   if (handle->wait_handle != INVALID_HANDLE_VALUE) {
880     /* This blocks until either the wait was cancelled, or the callback has
881      * completed. */
882     BOOL r = UnregisterWaitEx(handle->wait_handle, INVALID_HANDLE_VALUE);
883     if (!r) {
884       /* This should never happen, and if it happens, we can't recover... */
885       uv_fatal_error(GetLastError(), "UnregisterWaitEx");
886     }
887 
888     handle->wait_handle = INVALID_HANDLE_VALUE;
889   }
890 
891   if (!handle->exit_cb_pending) {
892     uv__want_endgame(loop, (uv_handle_t*)handle);
893   }
894 }
895 
896 
uv__process_endgame(uv_loop_t * loop,uv_process_t * handle)897 void uv__process_endgame(uv_loop_t* loop, uv_process_t* handle) {
898   assert(!handle->exit_cb_pending);
899   assert(handle->flags & UV_HANDLE_CLOSING);
900   assert(!(handle->flags & UV_HANDLE_CLOSED));
901 
902   /* Clean-up the process handle. */
903   CloseHandle(handle->process_handle);
904 
905   uv__handle_close(handle);
906 }
907 
908 
uv_spawn(uv_loop_t * loop,uv_process_t * process,const uv_process_options_t * options)909 int uv_spawn(uv_loop_t* loop,
910              uv_process_t* process,
911              const uv_process_options_t* options) {
912   int i;
913   int err = 0;
914   WCHAR* path = NULL, *alloc_path = NULL;
915   BOOL result;
916   WCHAR* application_path = NULL, *application = NULL, *arguments = NULL,
917          *env = NULL, *cwd = NULL;
918   STARTUPINFOW startup;
919   PROCESS_INFORMATION info;
920   DWORD process_flags;
921   BYTE* child_stdio_buffer;
922 
923   uv__process_init(loop, process);
924   process->exit_cb = options->exit_cb;
925   child_stdio_buffer = NULL;
926 
927   if (options->flags & (UV_PROCESS_SETGID | UV_PROCESS_SETUID)) {
928     return UV_ENOTSUP;
929   }
930 
931   if (options->file == NULL ||
932       options->args == NULL) {
933     return UV_EINVAL;
934   }
935 
936   assert(options->file != NULL);
937   assert(!(options->flags & ~(UV_PROCESS_DETACHED |
938                               UV_PROCESS_SETGID |
939                               UV_PROCESS_SETUID |
940                               UV_PROCESS_WINDOWS_FILE_PATH_EXACT_NAME |
941                               UV_PROCESS_WINDOWS_HIDE |
942                               UV_PROCESS_WINDOWS_HIDE_CONSOLE |
943                               UV_PROCESS_WINDOWS_HIDE_GUI |
944                               UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
945 
946   err = uv__utf8_to_utf16_alloc(options->file, &application);
947   if (err)
948     goto done_uv;
949 
950   err = make_program_args(
951       options->args,
952       options->flags & UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS,
953       &arguments);
954   if (err)
955     goto done_uv;
956 
957   if (options->env) {
958      err = make_program_env(options->env, &env);
959      if (err)
960        goto done_uv;
961   }
962 
963   if (options->cwd) {
964     /* Explicit cwd */
965     err = uv__utf8_to_utf16_alloc(options->cwd, &cwd);
966     if (err)
967       goto done_uv;
968 
969   } else {
970     /* Inherit cwd */
971     DWORD cwd_len, r;
972 
973     cwd_len = GetCurrentDirectoryW(0, NULL);
974     if (!cwd_len) {
975       err = GetLastError();
976       goto done;
977     }
978 
979     cwd = (WCHAR*) uv__malloc(cwd_len * sizeof(WCHAR));
980     if (cwd == NULL) {
981       err = ERROR_OUTOFMEMORY;
982       goto done;
983     }
984 
985     r = GetCurrentDirectoryW(cwd_len, cwd);
986     if (r == 0 || r >= cwd_len) {
987       err = GetLastError();
988       goto done;
989     }
990   }
991 
992   /* Get PATH environment variable. */
993   path = find_path(env);
994   if (path == NULL) {
995     DWORD path_len, r;
996 
997     path_len = GetEnvironmentVariableW(L"PATH", NULL, 0);
998     if (path_len != 0) {
999       alloc_path = (WCHAR*) uv__malloc(path_len * sizeof(WCHAR));
1000       if (alloc_path == NULL) {
1001         err = ERROR_OUTOFMEMORY;
1002         goto done;
1003       }
1004       path = alloc_path;
1005 
1006       r = GetEnvironmentVariableW(L"PATH", path, path_len);
1007       if (r == 0 || r >= path_len) {
1008         err = GetLastError();
1009         goto done;
1010       }
1011     }
1012   }
1013 
1014   err = uv__stdio_create(loop, options, &child_stdio_buffer);
1015   if (err)
1016     goto done;
1017 
1018   application_path = search_path(application,
1019                                  cwd,
1020                                  path,
1021                                  options->flags);
1022   if (application_path == NULL) {
1023     /* Not found. */
1024     err = ERROR_FILE_NOT_FOUND;
1025     goto done;
1026   }
1027 
1028   startup.cb = sizeof(startup);
1029   startup.lpReserved = NULL;
1030   startup.lpDesktop = NULL;
1031   startup.lpTitle = NULL;
1032   startup.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1033 
1034   startup.cbReserved2 = uv__stdio_size(child_stdio_buffer);
1035   startup.lpReserved2 = (BYTE*) child_stdio_buffer;
1036 
1037   startup.hStdInput = uv__stdio_handle(child_stdio_buffer, 0);
1038   startup.hStdOutput = uv__stdio_handle(child_stdio_buffer, 1);
1039   startup.hStdError = uv__stdio_handle(child_stdio_buffer, 2);
1040 
1041   process_flags = CREATE_UNICODE_ENVIRONMENT;
1042 
1043   if ((options->flags & UV_PROCESS_WINDOWS_HIDE_CONSOLE) ||
1044       (options->flags & UV_PROCESS_WINDOWS_HIDE)) {
1045     /* Avoid creating console window if stdio is not inherited. */
1046     for (i = 0; i < options->stdio_count; i++) {
1047       if (options->stdio[i].flags & UV_INHERIT_FD)
1048         break;
1049       if (i == options->stdio_count - 1)
1050         process_flags |= CREATE_NO_WINDOW;
1051     }
1052   }
1053   if ((options->flags & UV_PROCESS_WINDOWS_HIDE_GUI) ||
1054       (options->flags & UV_PROCESS_WINDOWS_HIDE)) {
1055     /* Use SW_HIDE to avoid any potential process window. */
1056     startup.wShowWindow = SW_HIDE;
1057   } else {
1058     startup.wShowWindow = SW_SHOWDEFAULT;
1059   }
1060 
1061   if (options->flags & UV_PROCESS_DETACHED) {
1062     /* Note that we're not setting the CREATE_BREAKAWAY_FROM_JOB flag. That
1063      * means that libuv might not let you create a fully daemonized process
1064      * when run under job control. However the type of job control that libuv
1065      * itself creates doesn't trickle down to subprocesses so they can still
1066      * daemonize.
1067      *
1068      * A reason to not do this is that CREATE_BREAKAWAY_FROM_JOB makes the
1069      * CreateProcess call fail if we're under job control that doesn't allow
1070      * breakaway.
1071      */
1072     process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
1073     process_flags |= CREATE_SUSPENDED;
1074   }
1075 
1076   if (!CreateProcessW(application_path,
1077                      arguments,
1078                      NULL,
1079                      NULL,
1080                      1,
1081                      process_flags,
1082                      env,
1083                      cwd,
1084                      &startup,
1085                      &info)) {
1086     /* CreateProcessW failed. */
1087     err = GetLastError();
1088     goto done;
1089   }
1090 
1091   /* If the process isn't spawned as detached, assign to the global job object
1092    * so windows will kill it when the parent process dies. */
1093   if (!(options->flags & UV_PROCESS_DETACHED)) {
1094     uv_once(&uv_global_job_handle_init_guard_, uv__init_global_job_handle);
1095 
1096     if (!AssignProcessToJobObject(uv_global_job_handle_, info.hProcess)) {
1097       /* AssignProcessToJobObject might fail if this process is under job
1098        * control and the job doesn't have the
1099        * JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag set, on a Windows version
1100        * that doesn't support nested jobs.
1101        *
1102        * When that happens we just swallow the error and continue without
1103        * establishing a kill-child-on-parent-exit relationship, otherwise
1104        * there would be no way for libuv applications run under job control
1105        * to spawn processes at all.
1106        */
1107       DWORD err = GetLastError();
1108       if (err != ERROR_ACCESS_DENIED)
1109         uv_fatal_error(err, "AssignProcessToJobObject");
1110     }
1111   }
1112 
1113   if (process_flags & CREATE_SUSPENDED) {
1114     if (ResumeThread(info.hThread) == ((DWORD)-1)) {
1115       err = GetLastError();
1116       TerminateProcess(info.hProcess, 1);
1117       goto done;
1118     }
1119   }
1120 
1121   /* Spawn succeeded. Beyond this point, failure is reported asynchronously. */
1122 
1123   process->process_handle = info.hProcess;
1124   process->pid = info.dwProcessId;
1125 
1126   /* Set IPC pid to all IPC pipes. */
1127   for (i = 0; i < options->stdio_count; i++) {
1128     const uv_stdio_container_t* fdopt = &options->stdio[i];
1129     if (fdopt->flags & UV_CREATE_PIPE &&
1130         fdopt->data.stream->type == UV_NAMED_PIPE &&
1131         ((uv_pipe_t*) fdopt->data.stream)->ipc) {
1132       ((uv_pipe_t*) fdopt->data.stream)->pipe.conn.ipc_remote_pid =
1133           info.dwProcessId;
1134     }
1135   }
1136 
1137   /* Setup notifications for when the child process exits. */
1138   result = RegisterWaitForSingleObject(&process->wait_handle,
1139       process->process_handle, exit_wait_callback, (void*)process, INFINITE,
1140       WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE);
1141   if (!result) {
1142     uv_fatal_error(GetLastError(), "RegisterWaitForSingleObject");
1143   }
1144 
1145   CloseHandle(info.hThread);
1146 
1147   assert(!err);
1148 
1149   /* Make the handle active. It will remain active until the exit callback is
1150    * made or the handle is closed, whichever happens first. */
1151   uv__handle_start(process);
1152 
1153   goto done_uv;
1154 
1155   /* Cleanup, whether we succeeded or failed. */
1156  done:
1157   err = uv_translate_sys_error(err);
1158 
1159  done_uv:
1160   uv__free(application);
1161   uv__free(application_path);
1162   uv__free(arguments);
1163   uv__free(cwd);
1164   uv__free(env);
1165   uv__free(alloc_path);
1166 
1167   if (child_stdio_buffer != NULL) {
1168     /* Clean up child stdio handles. */
1169     uv__stdio_destroy(child_stdio_buffer);
1170     child_stdio_buffer = NULL;
1171   }
1172 
1173   return err;
1174 }
1175 
1176 
uv__kill(HANDLE process_handle,int signum)1177 static int uv__kill(HANDLE process_handle, int signum) {
1178   if (signum < 0 || signum >= NSIG) {
1179     return UV_EINVAL;
1180   }
1181 
1182   /* Create a dump file for the targeted process, if the registry key
1183    * `HKLM:Software\Microsoft\Windows\Windows Error Reporting\LocalDumps`
1184    * exists.  The location of the dumps can be influenced by the `DumpFolder`
1185    * sub-key, which has a default value of `%LOCALAPPDATA%\CrashDumps`, see [0]
1186    * for more detail.  Note that if the dump folder does not exist, we attempt
1187    * to create it, to match behavior with WER itself.
1188    * [0]: https://learn.microsoft.com/en-us/windows/win32/wer/collecting-user-mode-dumps */
1189   if (signum == SIGQUIT) {
1190     HKEY registry_key;
1191     DWORD pid, ret;
1192     WCHAR basename[MAX_PATH];
1193 
1194     /* Get target process name. */
1195     GetModuleBaseNameW(process_handle, NULL, &basename[0], sizeof(basename));
1196 
1197     /* Get PID of target process. */
1198     pid = GetProcessId(process_handle);
1199 
1200     /* Get LocalDumps directory path. */
1201     ret = RegOpenKeyExW(
1202         HKEY_LOCAL_MACHINE,
1203         L"SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\LocalDumps",
1204         0,
1205         KEY_QUERY_VALUE,
1206         &registry_key);
1207     if (ret == ERROR_SUCCESS) {
1208       HANDLE hDumpFile = NULL;
1209       WCHAR dump_folder[MAX_PATH], dump_name[MAX_PATH];
1210       DWORD dump_folder_len = sizeof(dump_folder), key_type = 0;
1211       ret = RegGetValueW(registry_key,
1212                          NULL,
1213                          L"DumpFolder",
1214                          RRF_RT_ANY,
1215                          &key_type,
1216                          (PVOID) dump_folder,
1217                          &dump_folder_len);
1218       if (ret != ERROR_SUCCESS) {
1219         /* Workaround for missing uuid.dll on MinGW. */
1220         static const GUID FOLDERID_LocalAppData_libuv = {
1221           0xf1b32785, 0x6fba, 0x4fcf,
1222               {0x9d, 0x55, 0x7b, 0x8e, 0x7f, 0x15, 0x70, 0x91}
1223         };
1224 
1225         /* Default value for `dump_folder` is `%LOCALAPPDATA%\CrashDumps`. */
1226         WCHAR* localappdata;
1227         SHGetKnownFolderPath(&FOLDERID_LocalAppData_libuv,
1228                              0,
1229                              NULL,
1230                              &localappdata);
1231         _snwprintf_s(dump_folder,
1232                      sizeof(dump_folder),
1233                      _TRUNCATE,
1234                      L"%ls\\CrashDumps",
1235                      localappdata);
1236         CoTaskMemFree(localappdata);
1237       }
1238       RegCloseKey(registry_key);
1239 
1240       /* Create dump folder if it doesn't already exist. */
1241       CreateDirectoryW(dump_folder, NULL);
1242 
1243       /* Construct dump filename from process name and PID. */
1244       _snwprintf_s(dump_name,
1245                    sizeof(dump_name),
1246                    _TRUNCATE,
1247                    L"%ls\\%ls.%d.dmp",
1248                    dump_folder,
1249                    basename,
1250                    pid);
1251 
1252       hDumpFile = CreateFileW(dump_name,
1253                               GENERIC_WRITE,
1254                               0,
1255                               NULL,
1256                               CREATE_NEW,
1257                               FILE_ATTRIBUTE_NORMAL,
1258                               NULL);
1259       if (hDumpFile != INVALID_HANDLE_VALUE) {
1260         DWORD dump_options, sym_options;
1261         FILE_DISPOSITION_INFO DeleteOnClose = { TRUE };
1262 
1263         /* If something goes wrong while writing it out, delete the file. */
1264         SetFileInformationByHandle(hDumpFile,
1265                                    FileDispositionInfo,
1266                                    &DeleteOnClose,
1267                                    sizeof(DeleteOnClose));
1268 
1269         /* Tell wine to dump ELF modules as well. */
1270         sym_options = SymGetOptions();
1271         SymSetOptions(sym_options | 0x40000000);
1272 
1273 /* MiniDumpWithAvxXStateContext might be undef in server2012r2 or mingw < 12 */
1274 #ifndef MiniDumpWithAvxXStateContext
1275 #define MiniDumpWithAvxXStateContext 0x00200000
1276 #endif
1277         /* We default to a fairly complete dump.  In the future, we may want to
1278          * allow clients to customize what kind of dump to create. */
1279         dump_options = MiniDumpWithFullMemory |
1280                        MiniDumpIgnoreInaccessibleMemory |
1281                        MiniDumpWithAvxXStateContext;
1282 
1283         if (MiniDumpWriteDump(process_handle,
1284                               pid,
1285                               hDumpFile,
1286                               dump_options,
1287                               NULL,
1288                               NULL,
1289                               NULL)) {
1290           /* Don't delete the file on close if we successfully wrote it out. */
1291           FILE_DISPOSITION_INFO DontDeleteOnClose = { FALSE };
1292           SetFileInformationByHandle(hDumpFile,
1293                                      FileDispositionInfo,
1294                                      &DontDeleteOnClose,
1295                                      sizeof(DontDeleteOnClose));
1296         }
1297         SymSetOptions(sym_options);
1298         CloseHandle(hDumpFile);
1299       }
1300     }
1301   }
1302 
1303   switch (signum) {
1304     case SIGQUIT:
1305     case SIGTERM:
1306     case SIGKILL:
1307     case SIGINT: {
1308       /* Unconditionally terminate the process. On Windows, killed processes
1309        * normally return 1. */
1310       int err;
1311 
1312       if (TerminateProcess(process_handle, 1))
1313         return 0;
1314 
1315       /* If the process already exited before TerminateProcess was called,.
1316        * TerminateProcess will fail with ERROR_ACCESS_DENIED. */
1317       err = GetLastError();
1318       if (err == ERROR_ACCESS_DENIED &&
1319           WaitForSingleObject(process_handle, 0) == WAIT_OBJECT_0) {
1320         return UV_ESRCH;
1321       }
1322 
1323       return uv_translate_sys_error(err);
1324     }
1325 
1326     case 0: {
1327       /* Health check: is the process still alive? */
1328       switch (WaitForSingleObject(process_handle, 0)) {
1329         case WAIT_OBJECT_0:
1330           return UV_ESRCH;
1331         case WAIT_FAILED:
1332           return uv_translate_sys_error(GetLastError());
1333         case WAIT_TIMEOUT:
1334           return 0;
1335         default:
1336           return UV_UNKNOWN;
1337       }
1338     }
1339 
1340     default:
1341       /* Unsupported signal. */
1342       return UV_ENOSYS;
1343   }
1344 }
1345 
1346 
uv_process_kill(uv_process_t * process,int signum)1347 int uv_process_kill(uv_process_t* process, int signum) {
1348   int err;
1349 
1350   if (process->process_handle == INVALID_HANDLE_VALUE) {
1351     return UV_EINVAL;
1352   }
1353 
1354   err = uv__kill(process->process_handle, signum);
1355   if (err) {
1356     return err;  /* err is already translated. */
1357   }
1358 
1359   process->exit_signal = signum;
1360 
1361   return 0;
1362 }
1363 
1364 
uv_kill(int pid,int signum)1365 int uv_kill(int pid, int signum) {
1366   int err;
1367   HANDLE process_handle;
1368 
1369   if (pid == 0) {
1370     process_handle = GetCurrentProcess();
1371   } else {
1372     process_handle = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION | SYNCHRONIZE,
1373                                  FALSE,
1374                                  pid);
1375   }
1376 
1377   if (process_handle == NULL) {
1378     err = GetLastError();
1379     if (err == ERROR_INVALID_PARAMETER) {
1380       return UV_ESRCH;
1381     } else {
1382       return uv_translate_sys_error(err);
1383     }
1384   }
1385 
1386   err = uv__kill(process_handle, signum);
1387   CloseHandle(process_handle);
1388 
1389   return err;  /* err is already translated. */
1390 }
1391