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