1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
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:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
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
29 #include <malloc.h> /* alloca */
33 #include "handle-inl.h"
40 typedef struct env_var {
41 const WCHAR* const wide;
42 const WCHAR* const wide_eq;
43 const size_t len; /* including null or '=' */
46 #define E_V(str) { L##str, L##str L"=", sizeof(str) }
48 static const env_var_t required_vars[] = { /* keep me sorted */
63 static HANDLE uv_global_job_handle_;
64 static uv_once_t uv_global_job_handle_init_guard_ = UV_ONCE_INIT;
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.
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).
83 SECURITY_ATTRIBUTES attr;
84 JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
86 memset(&attr, 0, sizeof attr);
87 attr.bInheritHandle = FALSE;
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;
96 uv_global_job_handle_ = CreateJobObjectW(&attr, NULL);
97 if (uv_global_job_handle_ == NULL)
98 uv_fatal_error(GetLastError(), "CreateJobObjectW");
100 if (!SetInformationJobObject(uv_global_job_handle_,
101 JobObjectExtendedLimitInformation,
104 uv_fatal_error(GetLastError(), "SetInformationJobObject");
108 static int uv__utf8_to_utf16_alloc(const char* s, WCHAR** ws_ptr) {
112 ws_len = MultiByteToWideChar(CP_UTF8,
119 return GetLastError();
122 ws = (WCHAR*) uv__malloc(ws_len * sizeof(WCHAR));
124 return ERROR_OUTOFMEMORY;
127 r = MultiByteToWideChar(CP_UTF8,
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;
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;
150 UV_REQ_INIT(&handle->exit_req, UV_PROCESS_EXIT);
151 handle->exit_req.data = handle;
156 * Path search functions
160 * Helper function for search_path
162 static WCHAR* search_path_join_test(const WCHAR* dir,
170 WCHAR *result, *result_pos;
173 ((dir[0] == L'\\' || dir[0] == L'/') &&
174 (dir[1] == L'\\' || dir[1] == L'/'))) {
175 /* It's a UNC path so ignore cwd */
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 */
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.
186 if (cwd_len < 2 || _wcsnicmp(cwd, dir, 2) != 0) {
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
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));
204 wcsncpy(result_pos, cwd, cwd_len);
205 result_pos += cwd_len;
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'\\';
214 wcsncpy(result_pos, dir, dir_len);
215 result_pos += dir_len;
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'\\';
224 wcsncpy(result_pos, name, name_len);
225 result_pos += name_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'.';
235 wcsncpy(result_pos, ext, ext_len);
236 result_pos += ext_len;
239 /* Null terminator */
240 result_pos[0] = L'\0';
242 attrs = GetFileAttributesW(result);
244 if (attrs != INVALID_FILE_ATTRIBUTES &&
245 !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {
255 * Helper function for search_path
257 static WCHAR* path_search_walk_ext(const WCHAR *dir,
266 /* If the name itself has a nonempty extension, try this extension first */
268 result = search_path_join_test(dir, dir_len,
272 if (result != NULL) {
277 /* Try .com extension */
278 result = search_path_join_test(dir, dir_len,
282 if (result != NULL) {
286 /* Try .exe extension */
287 result = search_path_join_test(dir, dir_len,
291 if (result != NULL) {
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.
304 * It tries to return an absolute filename.
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.
311 * - Do not search the path if the filename already contains a path (either
312 * relative or absolute).
314 * - If there's really only a filename, check the current directory for file,
315 * then search all path directories.
317 * - If filename specified has *any* extension, search for the file with the
318 * specified extension first.
320 * - If the literal filename is not found in a directory, try *appending*
321 * (not replacing) .com first and then .exe.
323 * - The path variable may contain relative paths; relative paths are relative
326 * - Directories in path may or may not end with a trailing backslash.
328 * - CMD does not trim leading/trailing whitespace from path/pathex entries
329 * nor from the environment variables as a whole.
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.
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.
342 static WCHAR* search_path(const WCHAR *file,
346 WCHAR* result = NULL;
347 WCHAR *file_name_start;
349 const WCHAR *dir_start, *dir_end, *dir_path;
353 size_t file_len = wcslen(file);
354 size_t cwd_len = wcslen(cwd);
356 /* If the caller supplies an empty filename,
357 * we're not gonna return c:\windows\.exe -- GFY!
360 || (file_len == 1 && file[0] == L'.')) {
364 /* Find the start of the filename so we can split the directory from the
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':';
373 file_has_dir = file_name_start != file;
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');
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),
390 /* The file is really only a name; look in cwd first, then scan path */
391 result = path_search_walk_ext(L"", 0,
396 while (result == NULL) {
397 if (*dir_end == L'\0') {
401 /* Skip the separator that dir_end now points to */
402 if (dir_end != path || *path == L';') {
406 /* Next slice starts just after where the previous one ended */
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');
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');
422 /* If the slice is zero-length, don't bother */
423 if (dir_end - dir_start == 0) {
427 dir_path = dir_start;
428 dir_len = dir_end - dir_start;
430 /* Adjust if the path is quoted. */
431 if (dir_path[0] == '"' || dir_path[0] == '\'') {
436 if (dir_path[dir_len - 1] == '"' || dir_path[dir_len - 1] == '\'') {
440 result = path_search_walk_ext(dir_path, dir_len,
452 * Quotes command line arguments
453 * Returns a pointer to the end (next char to be written) of the buffer
455 WCHAR* quote_cmd_arg(const WCHAR *source, WCHAR *target) {
456 size_t len = wcslen(source);
462 /* Need double quotation for empty argument */
468 if (NULL == wcspbrk(source, L" \t\"")) {
469 /* No quotation needed */
470 wcsncpy(target, source, len);
475 if (NULL == wcspbrk(source, L"\"\\")) {
477 * No embedded double quotes or backlashes, so I can just wrap
478 * quote marks around the whole thing.
481 wcsncpy(target, source, len);
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\\"
509 for (i = len; i > 0; --i) {
510 *(target++) = source[i - 1];
512 if (quote_hit && source[i - 1] == L'\\') {
514 } else if(source[i - 1] == L'"') {
528 int make_program_args(char** args, int verbatim_arguments, WCHAR** dst_ptr) {
531 WCHAR* temp_buffer = NULL;
533 size_t temp_buffer_len = 0;
538 /* Count the required size. */
539 for (arg = args; *arg; arg++) {
542 arg_len = MultiByteToWideChar(CP_UTF8,
549 return GetLastError();
554 if (arg_len > temp_buffer_len)
555 temp_buffer_len = arg_len;
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;
564 /* Allocate buffer for the final command line. */
565 dst = (WCHAR*) uv__malloc(dst_len * sizeof(WCHAR));
567 err = ERROR_OUTOFMEMORY;
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;
579 for (arg = args; *arg; arg++) {
582 /* Convert argument to wide char. */
583 arg_len = MultiByteToWideChar(CP_UTF8,
588 (int) (dst + dst_len - pos));
590 err = GetLastError();
594 if (verbatim_arguments) {
596 wcscpy(pos, temp_buffer);
599 /* Quote/escape, if needed. */
600 pos = quote_cmd_arg(temp_buffer, pos);
603 *pos++ = *(arg + 1) ? L' ' : L'\0';
606 uv__free(temp_buffer);
613 uv__free(temp_buffer);
618 int env_strncmp(const wchar_t* a, int na, const wchar_t* b) {
627 a_eq = wcschr(a, L'=');
629 na = (int)(long)(a_eq - a);
633 b_eq = wcschr(b, L'=');
637 A = alloca((na+1) * sizeof(wchar_t));
638 B = alloca((nb+1) * sizeof(wchar_t));
640 r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, a, na, A, na);
643 r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, b, nb, B, nb);
652 } else if (AA > BB) {
654 } else if (!AA && !BB) {
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);
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.
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
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
684 int make_program_env(char* env_block[], WCHAR** dst_ptr) {
692 size_t env_block_count = 1; /* 1 for null-terminator */
696 DWORD required_vars_value_len[ARRAY_SIZE(required_vars)];
698 /* first pass: determine size in UTF-16 */
699 for (env = env_block; *env; env++) {
701 if (strchr(*env, '=')) {
702 len = MultiByteToWideChar(CP_UTF8,
709 return GetLastError();
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;
721 env_copy = alloca(env_block_count * sizeof(WCHAR*));
725 for (env = env_block; *env; env++) {
726 if (strchr(*env, '=')) {
727 len = MultiByteToWideChar(CP_UTF8,
732 (int) (env_len - (ptr - dst_copy)));
734 DWORD err = GetLastError();
743 assert(env_len == 0 || env_len == (size_t) (ptr - dst_copy));
745 /* sort our (UTF-16) copy */
746 qsort(env_copy, env_block_count-1, sizeof(wchar_t*), qsort_wcscmp);
748 /* third pass: check for required variables */
749 for (ptr_copy = env_copy, i = 0; i < ARRAY_SIZE(required_vars); ) {
754 cmp = env_strncmp(required_vars[i].wide_eq,
755 required_vars[i].len,
759 /* missing required var */
760 var_size = GetEnvironmentVariableW(required_vars[i].wide, NULL, 0);
761 required_vars_value_len[i] = var_size;
763 env_len += required_vars[i].len;
774 /* final pass: copy, in sort order, and inserting required variables */
775 dst = uv__malloc((1+env_len) * sizeof(WCHAR));
778 return ERROR_OUTOFMEMORY;
781 for (ptr = dst, ptr_copy = env_copy, i = 0;
782 *ptr_copy || i < ARRAY_SIZE(required_vars);
785 if (i >= ARRAY_SIZE(required_vars)) {
787 } else if (!*ptr_copy) {
790 cmp = env_strncmp(required_vars[i].wide_eq,
791 required_vars[i].len,
795 /* missing required var */
796 len = required_vars_value_len[i];
798 wcscpy(ptr, required_vars[i].wide_eq);
799 ptr += required_vars[i].len;
800 var_size = GetEnvironmentVariableW(required_vars[i].wide,
802 (int) (env_len - (ptr - dst)));
803 if (var_size != (DWORD) (len - 1)) { /* TODO: handle race condition? */
804 uv_fatal_error(GetLastError(), "GetEnvironmentVariableW");
809 /* copy var from env_block */
810 len = wcslen(*ptr_copy) + 1;
811 wmemcpy(ptr, *ptr_copy, len);
818 /* Terminate with an extra NULL. */
819 assert(env_len == (size_t) (ptr - dst));
828 * Attempt to find the value of the PATH environment variable in the child's
829 * preprocessed environment.
831 * If found, a pointer into `env` is returned. If not found, NULL is returned.
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') &&
848 * Called on Windows thread-pool thread to indicate that
849 * a child process has exited.
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;
855 assert(didTimeout == FALSE);
857 assert(!process->exit_cb_pending);
859 process->exit_cb_pending = 1;
862 POST_COMPLETION_FOR_REQ(loop, &process->exit_req);
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) {
871 assert(handle->exit_cb_pending);
872 handle->exit_cb_pending = 0;
874 /* If we're closing, don't call the exit callback. Just schedule a close
876 if (handle->flags & UV_HANDLE_CLOSING) {
877 uv__want_endgame(loop, (uv_handle_t*) handle);
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;
887 /* Set the handle to inactive: no callbacks will be made after the exit
889 uv__handle_stop(handle);
891 if (GetExitCodeProcess(handle->process_handle, &status)) {
894 /* Unable to obtain the exit code. This should never happen. */
895 exit_code = uv_translate_sys_error(GetLastError());
898 /* Fire the exit callback. */
899 if (handle->exit_cb) {
900 handle->exit_cb(handle, exit_code, handle->exit_signal);
905 void uv__process_close(uv_loop_t* loop, uv_process_t* handle) {
906 uv__handle_closing(handle);
908 if (handle->wait_handle != INVALID_HANDLE_VALUE) {
909 /* This blocks until either the wait was cancelled, or the callback has
911 BOOL r = UnregisterWaitEx(handle->wait_handle, INVALID_HANDLE_VALUE);
913 /* This should never happen, and if it happens, we can't recover... */
914 uv_fatal_error(GetLastError(), "UnregisterWaitEx");
917 handle->wait_handle = INVALID_HANDLE_VALUE;
920 if (!handle->exit_cb_pending) {
921 uv__want_endgame(loop, (uv_handle_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));
931 /* Clean-up the process handle. */
932 CloseHandle(handle->process_handle);
934 uv__handle_close(handle);
938 int uv_spawn(uv_loop_t* loop,
939 uv_process_t* process,
940 const uv_process_options_t* options) {
943 WCHAR* path = NULL, *alloc_path = NULL;
945 WCHAR* application_path = NULL, *application = NULL, *arguments = NULL,
946 *env = NULL, *cwd = NULL;
947 STARTUPINFOW startup;
948 PROCESS_INFORMATION info;
951 uv__process_init(loop, process);
952 process->exit_cb = options->exit_cb;
954 if (options->flags & (UV_PROCESS_SETGID | UV_PROCESS_SETUID)) {
958 if (options->file == NULL ||
959 options->args == NULL) {
963 if (options->cpumask != NULL) {
964 if (options->cpumask_size < (size_t)uv_cpumask_size()) {
969 assert(options->file != NULL);
970 assert(!(options->flags & ~(UV_PROCESS_DETACHED |
973 UV_PROCESS_WINDOWS_HIDE |
974 UV_PROCESS_WINDOWS_HIDE_CONSOLE |
975 UV_PROCESS_WINDOWS_HIDE_GUI |
976 UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS)));
978 err = uv__utf8_to_utf16_alloc(options->file, &application);
982 err = make_program_args(
984 options->flags & UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS,
990 err = make_program_env(options->env, &env);
997 err = uv__utf8_to_utf16_alloc(options->cwd, &cwd);
1005 cwd_len = GetCurrentDirectoryW(0, NULL);
1007 err = GetLastError();
1011 cwd = (WCHAR*) uv__malloc(cwd_len * sizeof(WCHAR));
1013 err = ERROR_OUTOFMEMORY;
1017 r = GetCurrentDirectoryW(cwd_len, cwd);
1018 if (r == 0 || r >= cwd_len) {
1019 err = GetLastError();
1024 /* Get PATH environment variable. */
1025 path = find_path(env);
1029 path_len = GetEnvironmentVariableW(L"PATH", NULL, 0);
1030 if (path_len == 0) {
1031 err = GetLastError();
1035 alloc_path = (WCHAR*) uv__malloc(path_len * sizeof(WCHAR));
1036 if (alloc_path == NULL) {
1037 err = ERROR_OUTOFMEMORY;
1042 r = GetEnvironmentVariableW(L"PATH", path, path_len);
1043 if (r == 0 || r >= path_len) {
1044 err = GetLastError();
1049 err = uv__stdio_create(loop, options, &process->child_stdio_buffer);
1053 application_path = search_path(application,
1056 if (application_path == NULL) {
1058 err = ERROR_FILE_NOT_FOUND;
1062 startup.cb = sizeof(startup);
1063 startup.lpReserved = NULL;
1064 startup.lpDesktop = NULL;
1065 startup.lpTitle = NULL;
1066 startup.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
1068 startup.cbReserved2 = uv__stdio_size(process->child_stdio_buffer);
1069 startup.lpReserved2 = (BYTE*) process->child_stdio_buffer;
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);
1075 process_flags = CREATE_UNICODE_ENVIRONMENT;
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)
1083 if (i == options->stdio_count - 1)
1084 process_flags |= CREATE_NO_WINDOW;
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;
1092 startup.wShowWindow = SW_SHOWDEFAULT;
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
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
1106 process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
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;
1115 if (!CreateProcessW(application_path,
1125 /* CreateProcessW failed. */
1126 err = GetLastError();
1130 if (options->cpumask != NULL) {
1131 /* The child is currently suspended. Set its process affinity
1132 or terminate it if we can't. */
1139 cpumasksize = uv_cpumask_size();
1141 if (!GetProcessAffinityMask(info.hProcess, &oldmask, &sysmask)) {
1142 err = GetLastError();
1143 TerminateProcess(info.hProcess, 1);
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;
1154 TerminateProcess(info.hProcess, 1);
1160 if (!SetProcessAffinityMask(info.hProcess, newmask)) {
1161 err = GetLastError();
1162 TerminateProcess(info.hProcess, 1);
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);
1174 /* Spawn succeeded. Beyond this point, failure is reported asynchronously. */
1176 process->process_handle = info.hProcess;
1177 process->pid = info.dwProcessId;
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);
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.
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.
1195 DWORD err = GetLastError();
1196 if (err != ERROR_ACCESS_DENIED)
1197 uv_fatal_error(err, "AssignProcessToJobObject");
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 =
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);
1217 uv_fatal_error(GetLastError(), "RegisterWaitForSingleObject");
1220 CloseHandle(info.hThread);
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);
1228 /* Cleanup, whether we succeeded or failed. */
1230 uv__free(application);
1231 uv__free(application_path);
1232 uv__free(arguments);
1235 uv__free(alloc_path);
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;
1243 return uv_translate_sys_error(err);
1247 static int uv__kill(HANDLE process_handle, int signum) {
1248 if (signum < 0 || signum >= NSIG) {
1256 /* Unconditionally terminate the process. On Windows, killed processes
1257 * normally return 1. */
1261 if (TerminateProcess(process_handle, 1))
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) {
1273 return uv_translate_sys_error(err);
1277 /* Health check: is the process still alive? */
1280 if (!GetExitCodeProcess(process_handle, &status))
1281 return uv_translate_sys_error(GetLastError());
1283 if (status != STILL_ACTIVE)
1290 /* Unsupported signal. */
1296 int uv_process_kill(uv_process_t* process, int signum) {
1299 if (process->process_handle == INVALID_HANDLE_VALUE) {
1303 err = uv__kill(process->process_handle, signum);
1305 return err; /* err is already translated. */
1308 process->exit_signal = signum;
1314 int uv_kill(int pid, int signum) {
1316 HANDLE process_handle;
1319 process_handle = GetCurrentProcess();
1321 process_handle = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION,
1326 if (process_handle == NULL) {
1327 err = GetLastError();
1328 if (err == ERROR_INVALID_PARAMETER) {
1331 return uv_translate_sys_error(err);
1335 err = uv__kill(process_handle, signum);
1336 CloseHandle(process_handle);
1338 return err; /* err is already translated. */