Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Utilities / cmlibuv / src / win / process.c
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
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
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
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  */
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  */
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  */
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  */
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
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
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
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  */
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  */
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  */
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. */
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
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
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
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   if (options->cpumask != NULL) {
964     if (options->cpumask_size < (size_t)uv_cpumask_size()) {
965       return UV_EINVAL;
966     }
967   }
968
969   assert(options->file != NULL);
970   assert(!(options->flags & ~(UV_PROCESS_DETACHED |
971                               UV_PROCESS_SETGID |
972                               UV_PROCESS_SETUID |
973                               UV_PROCESS_WINDOWS_HIDE |
974                               UV_PROCESS_WINDOWS_HIDE_CONSOLE |
975                               UV_PROCESS_WINDOWS_HIDE_GUI |
976                               UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
977
978   err = uv__utf8_to_utf16_alloc(options->file, &application);
979   if (err)
980     goto done;
981
982   err = make_program_args(
983       options->args,
984       options->flags & UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS,
985       &arguments);
986   if (err)
987     goto done;
988
989   if (options->env) {
990      err = make_program_env(options->env, &env);
991      if (err)
992        goto done;
993   }
994
995   if (options->cwd) {
996     /* Explicit cwd */
997     err = uv__utf8_to_utf16_alloc(options->cwd, &cwd);
998     if (err)
999       goto done;
1000
1001   } else {
1002     /* Inherit cwd */
1003     DWORD cwd_len, r;
1004
1005     cwd_len = GetCurrentDirectoryW(0, NULL);
1006     if (!cwd_len) {
1007       err = GetLastError();
1008       goto done;
1009     }
1010
1011     cwd = (WCHAR*) uv__malloc(cwd_len * sizeof(WCHAR));
1012     if (cwd == NULL) {
1013       err = ERROR_OUTOFMEMORY;
1014       goto done;
1015     }
1016
1017     r = GetCurrentDirectoryW(cwd_len, cwd);
1018     if (r == 0 || r >= cwd_len) {
1019       err = GetLastError();
1020       goto done;
1021     }
1022   }
1023
1024   /* Get PATH environment variable. */
1025   path = find_path(env);
1026   if (path == NULL) {
1027     DWORD path_len, r;
1028
1029     path_len = GetEnvironmentVariableW(L"PATH", NULL, 0);
1030     if (path_len == 0) {
1031       err = GetLastError();
1032       goto done;
1033     }
1034
1035     alloc_path = (WCHAR*) uv__malloc(path_len * sizeof(WCHAR));
1036     if (alloc_path == NULL) {
1037       err = ERROR_OUTOFMEMORY;
1038       goto done;
1039     }
1040     path = alloc_path;
1041
1042     r = GetEnvironmentVariableW(L"PATH", path, path_len);
1043     if (r == 0 || r >= path_len) {
1044       err = GetLastError();
1045       goto done;
1046     }
1047   }
1048
1049   err = uv__stdio_create(loop, options, &process->child_stdio_buffer);
1050   if (err)
1051     goto done;
1052
1053   application_path = search_path(application,
1054                                  cwd,
1055                                  path);
1056   if (application_path == NULL) {
1057     /* Not found. */
1058     err = ERROR_FILE_NOT_FOUND;
1059     goto done;
1060   }
1061
1062   startup.cb = sizeof(startup);
1063   startup.lpReserved = NULL;
1064   startup.lpDesktop = NULL;
1065   startup.lpTitle = NULL;
1066   startup.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1067
1068   startup.cbReserved2 = uv__stdio_size(process->child_stdio_buffer);
1069   startup.lpReserved2 = (BYTE*) process->child_stdio_buffer;
1070
1071   startup.hStdInput = uv__stdio_handle(process->child_stdio_buffer, 0);
1072   startup.hStdOutput = uv__stdio_handle(process->child_stdio_buffer, 1);
1073   startup.hStdError = uv__stdio_handle(process->child_stdio_buffer, 2);
1074
1075   process_flags = CREATE_UNICODE_ENVIRONMENT;
1076
1077   if ((options->flags & UV_PROCESS_WINDOWS_HIDE_CONSOLE) ||
1078       (options->flags & UV_PROCESS_WINDOWS_HIDE)) {
1079     /* Avoid creating console window if stdio is not inherited. */
1080     for (i = 0; i < options->stdio_count; i++) {
1081       if (options->stdio[i].flags & UV_INHERIT_FD)
1082         break;
1083       if (i == options->stdio_count - 1)
1084         process_flags |= CREATE_NO_WINDOW;
1085     }
1086   }
1087   if ((options->flags & UV_PROCESS_WINDOWS_HIDE_GUI) ||
1088       (options->flags & UV_PROCESS_WINDOWS_HIDE)) {
1089     /* Use SW_HIDE to avoid any potential process window. */
1090     startup.wShowWindow = SW_HIDE;
1091   } else {
1092     startup.wShowWindow = SW_SHOWDEFAULT;
1093   }
1094
1095   if (options->flags & UV_PROCESS_DETACHED) {
1096     /* Note that we're not setting the CREATE_BREAKAWAY_FROM_JOB flag. That
1097      * means that libuv might not let you create a fully daemonized process
1098      * when run under job control. However the type of job control that libuv
1099      * itself creates doesn't trickle down to subprocesses so they can still
1100      * daemonize.
1101      *
1102      * A reason to not do this is that CREATE_BREAKAWAY_FROM_JOB makes the
1103      * CreateProcess call fail if we're under job control that doesn't allow
1104      * breakaway.
1105      */
1106     process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
1107   }
1108
1109   if (options->cpumask != NULL) {
1110     /* Create the child in a suspended state so we have a chance to set
1111        its process affinity before it runs.  */
1112     process_flags |= CREATE_SUSPENDED;
1113   }
1114
1115   if (!CreateProcessW(application_path,
1116                      arguments,
1117                      NULL,
1118                      NULL,
1119                      1,
1120                      process_flags,
1121                      env,
1122                      cwd,
1123                      &startup,
1124                      &info)) {
1125     /* CreateProcessW failed. */
1126     err = GetLastError();
1127     goto done;
1128   }
1129
1130   if (options->cpumask != NULL) {
1131     /* The child is currently suspended.  Set its process affinity
1132        or terminate it if we can't.  */
1133     int i;
1134     int cpumasksize;
1135     DWORD_PTR sysmask;
1136     DWORD_PTR oldmask;
1137     DWORD_PTR newmask;
1138
1139     cpumasksize = uv_cpumask_size();
1140
1141     if (!GetProcessAffinityMask(info.hProcess, &oldmask, &sysmask)) {
1142       err = GetLastError();
1143       TerminateProcess(info.hProcess, 1);
1144       goto done;
1145     }
1146
1147     newmask = 0;
1148     for (i = 0; i < cpumasksize; i++) {
1149       if (options->cpumask[i]) {
1150         if (oldmask & (((DWORD_PTR)1) << i)) {
1151           newmask |= ((DWORD_PTR)1) << i;
1152         } else {
1153           err = UV_EINVAL;
1154           TerminateProcess(info.hProcess, 1);
1155           goto done;
1156         }
1157       }
1158     }
1159
1160     if (!SetProcessAffinityMask(info.hProcess, newmask)) {
1161       err = GetLastError();
1162       TerminateProcess(info.hProcess, 1);
1163       goto done;
1164     }
1165
1166     /* The process affinity of the child is set.  Let it run.  */
1167     if (ResumeThread(info.hThread) == ((DWORD)-1)) {
1168       err = GetLastError();
1169       TerminateProcess(info.hProcess, 1);
1170       goto done;
1171     }
1172   }
1173
1174   /* Spawn succeeded. Beyond this point, failure is reported asynchronously. */
1175
1176   process->process_handle = info.hProcess;
1177   process->pid = info.dwProcessId;
1178
1179   /* If the process isn't spawned as detached, assign to the global job object
1180    * so windows will kill it when the parent process dies. */
1181   if (!(options->flags & UV_PROCESS_DETACHED)) {
1182     uv_once(&uv_global_job_handle_init_guard_, uv__init_global_job_handle);
1183
1184     if (!AssignProcessToJobObject(uv_global_job_handle_, info.hProcess)) {
1185       /* AssignProcessToJobObject might fail if this process is under job
1186        * control and the job doesn't have the
1187        * JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag set, on a Windows version
1188        * that doesn't support nested jobs.
1189        *
1190        * When that happens we just swallow the error and continue without
1191        * establishing a kill-child-on-parent-exit relationship, otherwise
1192        * there would be no way for libuv applications run under job control
1193        * to spawn processes at all.
1194        */
1195       DWORD err = GetLastError();
1196       if (err != ERROR_ACCESS_DENIED)
1197         uv_fatal_error(err, "AssignProcessToJobObject");
1198     }
1199   }
1200
1201   /* Set IPC pid to all IPC pipes. */
1202   for (i = 0; i < options->stdio_count; i++) {
1203     const uv_stdio_container_t* fdopt = &options->stdio[i];
1204     if (fdopt->flags & UV_CREATE_PIPE &&
1205         fdopt->data.stream->type == UV_NAMED_PIPE &&
1206         ((uv_pipe_t*) fdopt->data.stream)->ipc) {
1207       ((uv_pipe_t*) fdopt->data.stream)->pipe.conn.ipc_remote_pid =
1208           info.dwProcessId;
1209     }
1210   }
1211
1212   /* Setup notifications for when the child process exits. */
1213   result = RegisterWaitForSingleObject(&process->wait_handle,
1214       process->process_handle, exit_wait_callback, (void*)process, INFINITE,
1215       WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE);
1216   if (!result) {
1217     uv_fatal_error(GetLastError(), "RegisterWaitForSingleObject");
1218   }
1219
1220   CloseHandle(info.hThread);
1221
1222   assert(!err);
1223
1224   /* Make the handle active. It will remain active until the exit callback is
1225    * made or the handle is closed, whichever happens first. */
1226   uv__handle_start(process);
1227
1228   /* Cleanup, whether we succeeded or failed. */
1229  done:
1230   uv__free(application);
1231   uv__free(application_path);
1232   uv__free(arguments);
1233   uv__free(cwd);
1234   uv__free(env);
1235   uv__free(alloc_path);
1236
1237   if (process->child_stdio_buffer != NULL) {
1238     /* Clean up child stdio handles. */
1239     uv__stdio_destroy(process->child_stdio_buffer);
1240     process->child_stdio_buffer = NULL;
1241   }
1242
1243   return uv_translate_sys_error(err);
1244 }
1245
1246
1247 static int uv__kill(HANDLE process_handle, int signum) {
1248   if (signum < 0 || signum >= NSIG) {
1249     return UV_EINVAL;
1250   }
1251
1252   switch (signum) {
1253     case SIGTERM:
1254     case SIGKILL:
1255     case SIGINT: {
1256       /* Unconditionally terminate the process. On Windows, killed processes
1257        * normally return 1. */
1258       DWORD status;
1259       int err;
1260
1261       if (TerminateProcess(process_handle, 1))
1262         return 0;
1263
1264       /* If the process already exited before TerminateProcess was called,.
1265        * TerminateProcess will fail with ERROR_ACCESS_DENIED. */
1266       err = GetLastError();
1267       if (err == ERROR_ACCESS_DENIED &&
1268           GetExitCodeProcess(process_handle, &status) &&
1269           status != STILL_ACTIVE) {
1270         return UV_ESRCH;
1271       }
1272
1273       return uv_translate_sys_error(err);
1274     }
1275
1276     case 0: {
1277       /* Health check: is the process still alive? */
1278       DWORD status;
1279
1280       if (!GetExitCodeProcess(process_handle, &status))
1281         return uv_translate_sys_error(GetLastError());
1282
1283       if (status != STILL_ACTIVE)
1284         return UV_ESRCH;
1285
1286       return 0;
1287     }
1288
1289     default:
1290       /* Unsupported signal. */
1291       return UV_ENOSYS;
1292   }
1293 }
1294
1295
1296 int uv_process_kill(uv_process_t* process, int signum) {
1297   int err;
1298
1299   if (process->process_handle == INVALID_HANDLE_VALUE) {
1300     return UV_EINVAL;
1301   }
1302
1303   err = uv__kill(process->process_handle, signum);
1304   if (err) {
1305     return err;  /* err is already translated. */
1306   }
1307
1308   process->exit_signal = signum;
1309
1310   return 0;
1311 }
1312
1313
1314 int uv_kill(int pid, int signum) {
1315   int err;
1316   HANDLE process_handle;
1317
1318   if (pid == 0) {
1319     process_handle = GetCurrentProcess();
1320   } else {
1321     process_handle = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION,
1322                                  FALSE,
1323                                  pid);
1324   }
1325
1326   if (process_handle == NULL) {
1327     err = GetLastError();
1328     if (err == ERROR_INVALID_PARAMETER) {
1329       return UV_ESRCH;
1330     } else {
1331       return uv_translate_sys_error(err);
1332     }
1333   }
1334
1335   err = uv__kill(process_handle, signum);
1336   CloseHandle(process_handle);
1337
1338   return err;  /* err is already translated. */
1339 }