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