Cygwin: strptime: add release note
[newlib-cygwin.git] / winsup / cygwin / spawn.cc
blob71d75bbf4e911122c08a40fc1abbc266d3878ffa
1 /* spawn.cc
3 This file is part of Cygwin.
5 This software is a copyrighted work licensed under the terms of the
6 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
7 details. */
9 #include "winsup.h"
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <process.h>
13 #include <sys/wait.h>
14 #include <wchar.h>
15 #include <ctype.h>
16 #include <sys/cygwin.h>
17 #include "cygerrno.h"
18 #include "security.h"
19 #include "sigproc.h"
20 #include "pinfo.h"
21 #include "path.h"
22 #include "fhandler.h"
23 #include "dtable.h"
24 #include "cygheap.h"
25 #include "child_info.h"
26 #include "environ.h"
27 #include "cygtls.h"
28 #include "tls_pbuf.h"
29 #include "winf.h"
30 #include "ntdll.h"
31 #include "shared_info.h"
33 /* Add .exe to PROG if not already present and see if that exists.
34 If not, return PROG (converted from posix to win32 rules if necessary).
35 The result is always BUF.
37 Returns (possibly NULL) suffix */
39 static const char *
40 perhaps_suffix (const char *prog, path_conv& buf, int& err, unsigned opt)
42 const char *ext;
44 err = 0;
45 debug_printf ("prog '%s'", prog);
46 buf.check (prog, PC_SYM_FOLLOW | PC_NULLEMPTY | PC_POSIX, stat_suffixes);
48 if (buf.isdir ())
50 err = EACCES;
51 ext = NULL;
53 else if (!buf.exists ())
55 err = ENOENT;
56 ext = NULL;
58 else if (buf.known_suffix ())
59 ext = buf.get_win32 () + (buf.known_suffix () - buf.get_win32 ());
60 else
61 ext = strchr (buf.get_win32 (), '\0');
63 debug_printf ("buf %s, suffix found '%s'", (char *) buf.get_win32 (), ext);
64 return ext;
67 /* Find an executable name, possibly by appending known executable suffixes
68 to it. The path_conv struct 'buf' is filled and contains both, win32 and
69 posix path of the target file. Any found suffix is returned in known_suffix.
70 Eventually the posix path in buf is overwritten with the exact path as it
71 gets constructed for the path search. The reason is that the path is used
72 to create argv[0] in av::setup, and this requires that the filename stays
73 intact, instead of being resolved if the file is a symlink.
75 If the file is not found and !FE_NNF then the POSIX version of name is
76 placed in buf and returned. Otherwise the contents of buf is undefined
77 and NULL is returned. */
78 const char *
79 find_exec (const char *name, path_conv& buf, const char *search,
80 unsigned opt, const char **known_suffix)
82 const char *suffix = "";
83 const char *retval = NULL;
84 tmp_pathbuf tp;
85 char *tmp_path;
86 char *tmp = tp.c_get ();
87 bool has_slash = !!strpbrk (name, "/\\");
88 int err = 0;
89 bool eopath = false;
91 debug_printf ("find_exec (%s)", name);
93 /* Check to see if file can be opened as is first. */
94 if ((has_slash || opt & FE_CWD)
95 && (suffix = perhaps_suffix (name, buf, err, opt)) != NULL)
97 /* Overwrite potential symlink target with original path.
98 See comment preceeding this method. */
99 tmp_path = tmp;
100 if (!has_slash)
101 tmp_path = stpcpy (tmp, "./");
102 stpcpy (tmp_path, name);
103 buf.set_posix (tmp);
104 retval = buf.get_posix ();
105 goto out;
108 const char *path;
109 /* If it starts with a slash, it's a PATH-like pathlist. Otherwise it's
110 the name of an environment variable. */
111 if (strchr (search, '/'))
112 *stpncpy (tmp, search, NT_MAX_PATH - 1) = '\0';
113 else if (has_slash || isdrive (name))
114 goto errout;
115 /* Search the current directory when PATH is absent. This feature is
116 added for Linux compatibility, but it is deprecated. POSIX notes
117 that a conforming application shall use an explicit path name to
118 specify the current working directory. */
119 else if (!(path = getenv (search)) || !*path)
120 strcpy (tmp, ".");
121 else
122 *stpncpy (tmp, path, NT_MAX_PATH - 1) = '\0';
124 path = tmp;
125 debug_printf ("searchpath %s", path);
127 tmp_path = tp.c_get ();
130 char *eotmp = strccpy (tmp_path, &path, ':');
131 if (*path)
132 path++;
133 else
134 eopath = true;
135 /* An empty path or '.' means the current directory, but we've
136 already tried that. */
137 if ((opt & FE_CWD) && (tmp_path[0] == '\0'
138 || (tmp_path[0] == '.' && tmp_path[1] == '\0')))
139 continue;
140 /* An empty path means the current directory. This feature is
141 added for Linux compatibility, but it is deprecated. POSIX
142 notes that a conforming application shall use an explicit
143 pathname to specify the current working directory. */
144 else if (tmp_path[0] == '\0')
145 eotmp = stpcpy (tmp_path, ".");
147 *eotmp++ = '/';
148 stpcpy (eotmp, name);
150 debug_printf ("trying %s", tmp_path);
152 int err1;
154 if ((suffix = perhaps_suffix (tmp_path, buf, err1, opt)) != NULL)
156 if (buf.has_acls () && check_file_access (buf, X_OK, true))
157 continue;
158 /* Overwrite potential symlink target with original path.
159 See comment preceeding this method. */
160 buf.set_posix (tmp_path);
161 retval = buf.get_posix ();
162 goto out;
166 while (!eopath);
168 errout:
169 /* Couldn't find anything in the given path.
170 Take the appropriate action based on FE_NNF. */
171 if (!(opt & FE_NNF))
173 buf.check (name, PC_SYM_FOLLOW | PC_POSIX);
174 retval = buf.get_posix ();
177 out:
178 debug_printf ("%s = find_exec (%s)", (char *) buf.get_posix (), name);
179 if (known_suffix)
180 *known_suffix = suffix ?: strchr (buf.get_win32 (), '\0');
181 if (!retval && err)
182 set_errno (err);
183 return retval;
186 /* Utility for child_info_spawn::worker. */
188 static HANDLE
189 handle (int fd, bool writing)
191 HANDLE h;
192 cygheap_fdget cfd (fd);
194 if (cfd < 0)
195 h = INVALID_HANDLE_VALUE;
196 else if (cfd->close_on_exec ())
197 h = INVALID_HANDLE_VALUE;
198 else if (!writing)
199 h = cfd->get_handle_nat ();
200 else
201 h = cfd->get_output_handle_nat ();
203 return h;
207 iscmd (const char *argv0, const char *what)
209 int n;
210 n = strlen (argv0) - strlen (what);
211 if (n >= 2 && argv0[1] != ':')
212 return 0;
213 return n >= 0 && strcasematch (argv0 + n, what) &&
214 (n == 0 || isdirsep (argv0[n - 1]));
217 #define ILLEGAL_SIG_FUNC_PTR ((_sig_func_ptr) (-2))
218 struct system_call_handle
220 _sig_func_ptr oldint;
221 _sig_func_ptr oldquit;
222 sigset_t oldmask;
223 __pthread_cleanup_handler cleanup_handler;
225 bool is_system_call ()
227 return oldint != ILLEGAL_SIG_FUNC_PTR;
229 system_call_handle (bool issystem)
231 if (!issystem)
232 oldint = ILLEGAL_SIG_FUNC_PTR;
233 else
235 sig_send (NULL, __SIGHOLD);
236 oldint = NULL;
239 void arm()
241 if (is_system_call ())
243 sigset_t child_block;
244 oldint = signal (SIGINT, SIG_IGN);
245 oldquit = signal (SIGQUIT, SIG_IGN);
246 sigemptyset (&child_block);
247 sigaddset (&child_block, SIGCHLD);
248 sigprocmask (SIG_BLOCK, &child_block, &oldmask);
249 sig_send (NULL, __SIGNOHOLD);
251 cleanup_handler = { system_call_handle::cleanup, this, NULL };
252 _pthread_cleanup_push (&cleanup_handler);
255 ~system_call_handle ()
257 if (is_system_call ())
258 _pthread_cleanup_pop (1);
260 static void cleanup (void *arg)
262 # define this_ ((system_call_handle *) arg)
263 if (this_->is_system_call ())
265 signal (SIGINT, this_->oldint);
266 signal (SIGQUIT, this_->oldquit);
267 sigprocmask (SIG_SETMASK, &(this_->oldmask), NULL);
270 # undef this_
273 child_info_spawn NO_COPY ch_spawn;
275 extern "C" void __posix_spawn_sem_release (void *sem, int error);
277 extern DWORD mutex_timeout; /* defined in fhandler_termios.cc */
280 child_info_spawn::worker (const char *prog_arg, const char *const *argv,
281 const char *const envp[], int mode,
282 int in__stdin, int in__stdout)
284 bool rc;
285 int res = -1;
287 /* Check if we have been called from exec{lv}p or spawn{lv}p and mask
288 mode to keep only the spawn mode. */
289 bool p_type_exec = !!(mode & _P_PATH_TYPE_EXEC);
290 mode = _P_MODE (mode);
292 if (prog_arg == NULL)
294 syscall_printf ("prog_arg is NULL");
295 set_errno (EFAULT); /* As on Linux. */
296 return -1;
298 if (!prog_arg[0])
300 syscall_printf ("prog_arg is empty");
301 set_errno (ENOENT); /* Per POSIX */
302 return -1;
305 syscall_printf ("mode = %d, prog_arg = %.9500s", mode, prog_arg);
307 /* FIXME: This is no error condition on Linux. */
308 if (argv == NULL)
310 syscall_printf ("argv is NULL");
311 set_errno (EINVAL);
312 return -1;
315 av newargv;
316 linebuf cmd;
317 PWCHAR envblock = NULL;
318 path_conv real_path;
319 bool reset_sendsig = false;
321 tmp_pathbuf tp;
322 PWCHAR runpath = tp.w_get ();
323 int c_flags;
325 STARTUPINFOW si = {};
326 int looped = 0;
328 fhandler_termios::spawn_worker term_spawn_worker;
330 system_call_handle system_call (mode == _P_SYSTEM);
332 __try
334 child_info_types chtype;
335 if (mode == _P_OVERLAY)
336 chtype = _CH_EXEC;
337 else
338 chtype = _CH_SPAWN;
340 moreinfo = cygheap_exec_info::alloc ();
342 /* CreateProcess takes one long string that is the command line (sigh).
343 We need to quote any argument that has whitespace or embedded "'s. */
345 int ac;
346 for (ac = 0; argv[ac]; ac++)
349 int err;
350 const char *ext;
351 if ((ext = perhaps_suffix (prog_arg, real_path, err, FE_NADA)) == NULL)
353 set_errno (err);
354 res = -1;
355 __leave;
358 res = newargv.setup (prog_arg, real_path, ext, ac, argv, p_type_exec);
360 if (res)
361 __leave;
363 if (!real_path.iscygexec () && ::cygheap->cwd.get_error ())
365 small_printf ("Error: Current working directory %s.\n"
366 "Can't start native Windows application from here.\n\n",
367 ::cygheap->cwd.get_error_desc ());
368 set_errno (::cygheap->cwd.get_error ());
369 res = -1;
370 __leave;
373 if (real_path.iscygexec ())
375 moreinfo->argc = newargv.argc;
376 moreinfo->argv = newargv;
378 if ((wincmdln || !real_path.iscygexec ())
379 && !cmd.fromargv (newargv, real_path.get_win32 (),
380 real_path.iscygexec ()))
382 res = -1;
383 __leave;
387 if (mode != _P_OVERLAY || !real_path.iscygexec ()
388 || !DuplicateHandle (GetCurrentProcess (), myself.shared_handle (),
389 GetCurrentProcess (), &moreinfo->myself_pinfo,
390 0, TRUE, DUPLICATE_SAME_ACCESS))
391 moreinfo->myself_pinfo = NULL;
392 else
393 VerifyHandle (moreinfo->myself_pinfo);
395 PROCESS_INFORMATION pi;
396 pi.hProcess = pi.hThread = NULL;
397 pi.dwProcessId = pi.dwThreadId = 0;
399 c_flags = GetPriorityClass (GetCurrentProcess ());
400 sigproc_printf ("priority class %d", c_flags);
402 c_flags |= CREATE_SEPARATE_WOW_VDM | CREATE_UNICODE_ENVIRONMENT;
404 /* Add CREATE_DEFAULT_ERROR_MODE flag for non-Cygwin processes so they
405 get the default error mode instead of inheriting the mode Cygwin
406 uses. This allows things like Windows Error Reporting/JIT debugging
407 to work with processes launched from a Cygwin shell. */
408 if (winjitdebug && !real_path.iscygexec ())
409 c_flags |= CREATE_DEFAULT_ERROR_MODE;
411 /* We're adding the CREATE_BREAKAWAY_FROM_JOB flag here to workaround
412 issues with the "Program Compatibility Assistant (PCA) Service".
413 For some reason, when starting long running sessions from mintty(*),
414 the affected svchost.exe process takes more and more memory and at one
415 point takes over the CPU. At this point the machine becomes
416 unresponsive. The only way to get back to normal is to stop the
417 entire mintty session, or to stop the PCA service. However, a process
418 which is controlled by PCA is part of a compatibility job, which
419 allows child processes to break away from the job. This helps to
420 avoid this issue.
422 First we call IsProcessInJob. It fetches the information whether or
423 not we're part of a job 20 times faster than QueryInformationJobObject.
425 (*) Note that this is not mintty's fault. It has just been observed
426 with mintty in the first place. See the archives for more info:
427 http://cygwin.com/ml/cygwin-developers/2012-02/msg00018.html */
428 JOBOBJECT_BASIC_LIMIT_INFORMATION jobinfo;
429 BOOL is_in_job;
431 if (IsProcessInJob (GetCurrentProcess (), NULL, &is_in_job)
432 && is_in_job
433 && QueryInformationJobObject (NULL, JobObjectBasicLimitInformation,
434 &jobinfo, sizeof jobinfo, NULL)
435 && (jobinfo.LimitFlags & (JOB_OBJECT_LIMIT_BREAKAWAY_OK
436 | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK)))
438 debug_printf ("Add CREATE_BREAKAWAY_FROM_JOB");
439 c_flags |= CREATE_BREAKAWAY_FROM_JOB;
442 if (mode == _P_DETACH)
443 c_flags |= DETACHED_PROCESS;
444 else
445 fhandler_console::need_invisible ();
447 if (mode != _P_OVERLAY)
448 myself->exec_sendsig = NULL;
449 else
451 /* Reset sendsig so that any process which wants to send a signal
452 to this pid will wait for the new process to become active.
453 Save the old value in case the exec fails. */
454 if (!myself->exec_sendsig)
456 myself->exec_sendsig = myself->sendsig;
457 myself->exec_dwProcessId = myself->dwProcessId;
458 myself->sendsig = NULL;
459 reset_sendsig = true;
463 USHORT len = real_path.get_nt_native_path ()->Length / sizeof (WCHAR);
464 if (RtlEqualUnicodePathPrefix (real_path.get_nt_native_path (),
465 &ro_u_natp, FALSE))
467 runpath = real_path.get_wide_win32_path (runpath);
468 /* If the executable path length is < MAX_PATH, make sure the long
469 path win32 prefix is removed from the path to make subsequent
470 not long path aware native Win32 child processes happy. */
471 if (len < MAX_PATH + 4)
473 if (runpath[5] == ':')
474 runpath += 4;
475 else if (len < MAX_PATH + 6)
476 *(runpath += 6) = L'\\';
479 else if (len < NT_MAX_PATH - ro_u_globalroot.Length / sizeof (WCHAR))
481 UNICODE_STRING rpath;
483 RtlInitEmptyUnicodeString (&rpath, runpath,
484 (NT_MAX_PATH - 1) * sizeof (WCHAR));
485 RtlCopyUnicodeString (&rpath, &ro_u_globalroot);
486 RtlAppendUnicodeStringToString (&rpath,
487 real_path.get_nt_native_path ());
489 else
491 set_errno (ENAMETOOLONG);
492 res = -1;
493 __leave;
496 cygbench ("spawn-worker");
498 if (!real_path.iscygexec())
499 ::cygheap->fdtab.set_file_pointers_for_exec ();
501 /* If we switch the user, merge the user's Windows environment. */
502 bool switch_user = ::cygheap->user.issetuid ()
503 && (::cygheap->user.saved_uid
504 != ::cygheap->user.real_uid);
505 moreinfo->envp = build_env (envp, envblock, moreinfo->envc,
506 real_path.iscygexec (),
507 switch_user ? ::cygheap->user.primary_token ()
508 : NULL);
509 if (!moreinfo->envp || !envblock)
511 set_errno (E2BIG);
512 res = -1;
513 __leave;
515 set (chtype, real_path.iscygexec ());
516 __stdin = in__stdin;
517 __stdout = in__stdout;
518 record_children ();
520 si.lpReserved2 = (LPBYTE) this;
521 si.cbReserved2 = sizeof (*this);
523 /* Depends on set call above.
524 Some file types might need extra effort in the parent after CreateProcess
525 and before copying the datastructures to the child. So we have to start
526 the child in suspend state, unfortunately, to avoid a race condition. */
527 if (!newargv.win16_exe
528 && (!iscygwin () || mode != _P_OVERLAY
529 || ::cygheap->fdtab.need_fixup_before ()))
530 c_flags |= CREATE_SUSPENDED;
531 /* If a native application should be spawned, we test here if the spawning
532 process is running in a console and, if so, if it's a foreground or
533 background process. If it's a background process, we start the native
534 process with the CREATE_NEW_PROCESS_GROUP flag set. This lets the native
535 process ignore Ctrl-C by default. If we don't do that, pressing Ctrl-C
536 in a console will break native processes running in the background,
537 because the Ctrl-C event is sent to all processes in the console, unless
538 they ignore it explicitely. CREATE_NEW_PROCESS_GROUP does that for us. */
539 pid_t ctty_pgid =
540 ::cygheap->ctty ? ::cygheap->ctty->tc_getpgid () : 0;
541 if (!iscygwin () && ctty_pgid && ctty_pgid != myself->pgid)
542 c_flags |= CREATE_NEW_PROCESS_GROUP;
543 refresh_cygheap ();
545 if (c_flags & CREATE_NEW_PROCESS_GROUP)
546 myself->process_state |= PID_NEW_PG;
548 if (mode == _P_DETACH)
549 /* all set */;
550 else if (mode != _P_OVERLAY || !my_wr_proc_pipe)
551 prefork ();
552 else
553 wr_proc_pipe = my_wr_proc_pipe;
555 /* Don't allow child to inherit these handles if it's not a Cygwin program.
556 wr_proc_pipe will be injected later. parent won't be used by the child
557 so there is no reason for the child to have it open as it can confuse
558 ps into thinking that children of windows processes are all part of
559 the same "execed" process.
560 FIXME: Someday, make it so that parent is never created when starting
561 non-Cygwin processes. */
562 if (!iscygwin ())
564 SetHandleInformation (wr_proc_pipe, HANDLE_FLAG_INHERIT, 0);
565 SetHandleInformation (parent, HANDLE_FLAG_INHERIT, 0);
567 /* FIXME: racy */
568 if (mode != _P_OVERLAY)
569 SetHandleInformation (my_wr_proc_pipe, HANDLE_FLAG_INHERIT, 0);
570 parent_winpid = GetCurrentProcessId ();
572 PSECURITY_ATTRIBUTES sa = (PSECURITY_ATTRIBUTES) alloca (1024);
573 if (!sec_user_nih (sa, cygheap->user.sid (),
574 well_known_authenticated_users_sid,
575 PROCESS_QUERY_LIMITED_INFORMATION))
576 sa = &sec_none_nih;
578 int fileno_stdin = in__stdin < 0 ? 0 : in__stdin;
579 int fileno_stdout = in__stdout < 0 ? 1 : in__stdout;
580 int fileno_stderr = 2;
582 if (!iscygwin ())
584 bool need_send_sig = false;
585 int fd;
586 cygheap_fdenum cfd (false);
587 while ((fd = cfd.next ()) >= 0)
588 if (cfd->get_dev () == FH_PIPEW
589 && (fd == fileno_stdout || fd == fileno_stderr))
591 fhandler_pipe *pipe = (fhandler_pipe *)(fhandler_base *) cfd;
592 pipe->set_pipe_non_blocking (false);
593 if (pipe->request_close_query_hdl ())
594 need_send_sig = true;
596 else if (cfd->get_dev () == FH_PIPER && fd == fileno_stdin)
598 fhandler_pipe *pipe = (fhandler_pipe *)(fhandler_base *) cfd;
599 pipe->set_pipe_non_blocking (false);
602 if (need_send_sig)
604 tty_min dummy_tty;
605 dummy_tty.ntty = (fh_devices) myself->ctty;
606 dummy_tty.pgid = myself->pgid;
607 tty_min *t = cygwin_shared->tty.get_cttyp ();
608 if (!t) /* If tty is not allocated, use dummy_tty instead. */
609 t = &dummy_tty;
610 /* Emit __SIGNONCYGCHLD to let all processes in the
611 process group close query_hdl. */
612 t->kill_pgrp (__SIGNONCYGCHLD);
616 bool no_pcon = mode != _P_OVERLAY && mode != _P_WAIT;
617 term_spawn_worker.setup (iscygwin (), handle (fileno_stdin, false),
618 runpath, no_pcon, reset_sendsig, envblock);
620 /* Set up needed handles for stdio */
621 si.dwFlags = STARTF_USESTDHANDLES;
622 si.hStdInput = handle (fileno_stdin, false);
623 si.hStdOutput = handle (fileno_stdout, true);
624 si.hStdError = handle (fileno_stderr, true);
626 si.cb = sizeof (si);
628 if (!iscygwin ())
629 init_console_handler (CTTY_IS_VALID (myself->ctty));
631 loop:
632 /* When ruid != euid we create the new process under the current original
633 account and impersonate in child, this way maintaining the different
634 effective vs. real ids.
635 FIXME: If ruid != euid and ruid != saved_uid we currently give
636 up on ruid. The new process will have ruid == euid. */
637 ::cygheap->user.deimpersonate ();
639 if (!real_path.iscygexec () && mode == _P_OVERLAY)
640 myself->process_state |= PID_NOTCYGWIN;
642 cygpid = (mode != _P_OVERLAY) ? create_cygwin_pid () : myself->pid;
644 wchar_t wcmd[(size_t) cmd];
645 if (!::cygheap->user.issetuid ()
646 || (::cygheap->user.saved_uid == ::cygheap->user.real_uid
647 && ::cygheap->user.saved_gid == ::cygheap->user.real_gid
648 && !::cygheap->user.groups.issetgroups ()
649 && !::cygheap->user.setuid_to_restricted))
651 rc = CreateProcessW (runpath, /* image name w/ full path */
652 cmd.wcs (wcmd), /* what was passed to exec */
653 sa, /* process security attrs */
654 sa, /* thread security attrs */
655 TRUE, /* inherit handles */
656 c_flags,
657 envblock, /* environment */
658 NULL,
659 &si,
660 &pi);
662 else
664 /* Give access to myself */
665 if (mode == _P_OVERLAY)
666 myself.set_acl();
668 HWINSTA hwst = NULL;
669 HWINSTA hwst_orig = GetProcessWindowStation ();
670 HDESK hdsk = NULL;
671 HDESK hdsk_orig = GetThreadDesktop (GetCurrentThreadId ());
672 /* Don't create WindowStation and Desktop for restricted child. */
673 if (!::cygheap->user.setuid_to_restricted)
675 PSECURITY_ATTRIBUTES sa;
676 WCHAR sid[128];
677 WCHAR wstname[1024] = { L'\0' };
679 sa = sec_user ((PSECURITY_ATTRIBUTES) alloca (1024),
680 ::cygheap->user.sid ());
681 /* We're creating a window station per user, not per logon
682 session. It doesn't make sense in terms of security to
683 create a new window station for every logon of the same user.
684 It just fills up the system with window stations. */
685 hwst = CreateWindowStationW (::cygheap->user.get_windows_id (sid),
686 0, GENERIC_READ | GENERIC_WRITE, sa);
687 if (!hwst)
688 system_printf ("CreateWindowStation failed, %E");
689 else if (!SetProcessWindowStation (hwst))
690 system_printf ("SetProcessWindowStation failed, %E");
691 else if (!(hdsk = CreateDesktopW (L"Default", NULL, NULL, 0,
692 GENERIC_ALL, sa)))
693 system_printf ("CreateDesktop failed, %E");
694 else
696 wcpcpy (wcpcpy (wstname, sid), L"\\Default");
697 si.lpDesktop = wstname;
698 debug_printf ("Desktop: %W", si.lpDesktop);
702 rc = CreateProcessAsUserW (::cygheap->user.primary_token (),
703 runpath, /* image name w/ full path */
704 cmd.wcs (wcmd), /* what was passed to exec */
705 sa, /* process security attrs */
706 sa, /* thread security attrs */
707 TRUE, /* inherit handles */
708 c_flags,
709 envblock, /* environment */
710 NULL,
711 &si,
712 &pi);
713 if (hwst)
715 SetProcessWindowStation (hwst_orig);
716 CloseWindowStation (hwst);
718 if (hdsk)
720 SetThreadDesktop (hdsk_orig);
721 CloseDesktop (hdsk);
725 if (mode != _P_OVERLAY)
726 SetHandleInformation (my_wr_proc_pipe, HANDLE_FLAG_INHERIT,
727 HANDLE_FLAG_INHERIT);
729 /* Set errno now so that debugging messages from it appear before our
730 final debugging message [this is a general rule for debugging
731 messages]. */
732 if (!rc)
734 __seterrno ();
735 syscall_printf ("CreateProcess failed, %E");
736 /* If this was a failed exec, restore the saved sendsig. */
737 if (reset_sendsig)
739 myself->sendsig = myself->exec_sendsig;
740 myself->exec_sendsig = NULL;
742 myself->process_state &= ~PID_NOTCYGWIN;
743 /* Reset handle inheritance to default when the execution of a'
744 non-Cygwin process fails. Only need to do this for _P_OVERLAY
745 since the handle will be closed otherwise. Don't need to do
746 this for 'parent' since it will be closed in every case.
747 See FIXME above. */
748 if (!iscygwin () && mode == _P_OVERLAY)
749 SetHandleInformation (wr_proc_pipe, HANDLE_FLAG_INHERIT,
750 HANDLE_FLAG_INHERIT);
751 if (wr_proc_pipe == my_wr_proc_pipe)
752 wr_proc_pipe = NULL; /* We still own it: don't nuke in destructor */
754 /* Restore impersonation. In case of _P_OVERLAY this isn't
755 allowed since it would overwrite child data. */
756 if (mode != _P_OVERLAY)
757 ::cygheap->user.reimpersonate ();
759 res = -1;
760 __leave;
763 /* The CREATE_SUSPENDED case is handled below */
764 if (iscygwin () && !(c_flags & CREATE_SUSPENDED))
765 strace.write_childpid (pi.dwProcessId);
767 /* Fixup the parent data structures if needed and resume the child's
768 main thread. */
769 if (::cygheap->fdtab.need_fixup_before ())
770 ::cygheap->fdtab.fixup_before_exec (pi.dwProcessId);
772 /* Print the original program name here so the user can see that too. */
773 syscall_printf ("pid %d, prog_arg %s, cmd line %.9500s)",
774 rc ? cygpid : (unsigned int) -1, prog_arg, (const char *) cmd);
776 /* Name the handle similarly to proc_subproc. */
777 ProtectHandle1 (pi.hProcess, childhProc);
779 if (mode == _P_OVERLAY)
781 myself->dwProcessId = pi.dwProcessId;
782 strace.execing = 1;
783 myself.hProcess = hExeced = pi.hProcess;
784 HANDLE old_winpid_hdl = myself.shared_winpid_handle ();
785 /* We have to create a new winpid symlink on behalf of the child
786 process. For Cygwin processes we also have to create a reference
787 in the child. */
788 myself.create_winpid_symlink ();
789 if (real_path.iscygexec ())
790 DuplicateHandle (GetCurrentProcess (),
791 myself.shared_winpid_handle (),
792 pi.hProcess, NULL, 0, 0, DUPLICATE_SAME_ACCESS);
793 NtClose (old_winpid_hdl);
794 real_path.get_wide_win32_path (myself->progname); // FIXME: race?
795 sigproc_printf ("new process name %W", myself->progname);
796 if (!iscygwin ())
797 close_all_files ();
799 else
801 myself->set_has_pgid_children ();
802 ProtectHandle (pi.hThread);
803 pinfo child (cygpid,
804 PID_IN_USE | (real_path.iscygexec () ? 0 : PID_NOTCYGWIN));
805 if (!child)
807 syscall_printf ("pinfo failed");
808 if (get_errno () != ENOMEM)
809 set_errno (EAGAIN);
810 res = -1;
811 __leave;
813 child->dwProcessId = pi.dwProcessId;
814 child.hProcess = pi.hProcess;
816 real_path.get_wide_win32_path (child->progname);
817 /* This introduces an unreferenced, open handle into the child.
818 The purpose is to keep the pid shared memory open so that all
819 of the fields filled out by child.remember do not disappear
820 and so there is not a brief period during which the pid is
821 not available. */
822 DuplicateHandle (GetCurrentProcess (), child.shared_handle (),
823 pi.hProcess, NULL, 0, 0, DUPLICATE_SAME_ACCESS);
824 if (!real_path.iscygexec ())
826 /* If the child process is not a Cygwin process, we have to
827 create a new winpid symlink and induce it into the child
828 process as well to keep it over the lifetime of the child. */
829 child.create_winpid_symlink ();
830 DuplicateHandle (GetCurrentProcess (),
831 child.shared_winpid_handle (),
832 pi.hProcess, NULL, 0, 0, DUPLICATE_SAME_ACCESS);
834 child->start_time = time (NULL); /* Register child's starting time. */
835 child->nice = myself->nice;
836 postfork (child);
837 if (mode != _P_DETACH
838 && (!child.remember () || !child.attach ()))
840 /* FIXME: Child in strange state now */
841 CloseHandle (pi.hProcess);
842 ForceCloseHandle (pi.hThread);
843 res = -1;
844 __leave;
848 /* Start the child running */
849 if (c_flags & CREATE_SUSPENDED)
851 /* Inject a non-inheritable wr_proc_pipe handle into child so that we
852 can accurately track when the child exits without keeping this
853 process waiting around for it to exit. */
854 if (!iscygwin ())
855 DuplicateHandle (GetCurrentProcess (), wr_proc_pipe, pi.hProcess, NULL,
856 0, false, DUPLICATE_SAME_ACCESS);
857 ResumeThread (pi.hThread);
858 if (iscygwin ())
859 strace.write_childpid (pi.dwProcessId);
861 ForceCloseHandle (pi.hThread);
863 sigproc_printf ("spawned windows pid %d", pi.dwProcessId);
865 bool synced;
866 if ((mode == _P_DETACH || mode == _P_NOWAIT) && !iscygwin ())
867 synced = false;
868 else
869 /* Just mark a non-cygwin process as 'synced'. We will still eventually
870 wait for it to exit in maybe_set_exit_code_from_windows(). */
871 synced = iscygwin () ? sync (pi.dwProcessId, pi.hProcess, INFINITE) : true;
873 switch (mode)
875 case _P_OVERLAY:
876 myself.hProcess = pi.hProcess;
877 if (!synced)
879 if (!proc_retry (pi.hProcess))
881 looped++;
882 goto loop;
884 close_all_files (true);
886 else
888 if (iscygwin ())
889 close_all_files (true);
890 if (!my_wr_proc_pipe
891 && WaitForSingleObject (pi.hProcess, 0) == WAIT_TIMEOUT)
892 wait_for_myself ();
894 if (sem)
895 __posix_spawn_sem_release (sem, 0);
896 if (term_spawn_worker.need_cleanup ())
898 LONG prev_sigExeced = sigExeced;
899 while (WaitForSingleObject (pi.hProcess, 100) == WAIT_TIMEOUT)
900 /* If child process does not exit in predetermined time
901 period, the process does not seem to be terminated by
902 the signal sigExeced. Therefore, clear sigExeced here. */
903 prev_sigExeced =
904 InterlockedCompareExchange (&sigExeced, 0, prev_sigExeced);
905 term_spawn_worker.cleanup ();
906 term_spawn_worker.close_handle_set ();
908 /* Make sure that ctrl_c_handler() is not on going. Calling
909 init_console_handler(false) locks until returning from
910 ctrl_c_handler(). This insures that setting sigExeced
911 on Ctrl-C key has been completed. */
912 init_console_handler (false);
913 myself.exit (EXITCODE_NOSET);
914 break;
915 case _P_WAIT:
916 case _P_SYSTEM:
917 system_call.arm ();
918 if (waitpid (cygpid, &res, 0) != cygpid)
919 res = -1;
920 term_spawn_worker.cleanup ();
921 break;
922 case _P_DETACH:
923 res = 0; /* Lost all memory of this child. */
924 break;
925 case _P_NOWAIT:
926 case _P_NOWAITO:
927 case _P_VFORK:
928 res = cygpid;
929 break;
930 default:
931 break;
934 __except (NO_ERROR)
936 if (get_errno () == ENOMEM)
937 set_errno (E2BIG);
938 else
939 set_errno (EFAULT);
940 res = -1;
942 __endtry
943 term_spawn_worker.close_handle_set ();
944 this->cleanup ();
945 if (envblock)
946 free (envblock);
948 return (int) res;
951 extern "C" int
952 cwait (int *result, int pid, int)
954 return waitpid (pid, result, 0);
958 * Helper function for spawn runtime calls.
959 * Doesn't search the path.
962 extern "C" int
963 spawnve (int mode, const char *path, const char *const *argv,
964 const char *const *envp)
966 static char *const empty_env[] = { NULL };
968 int ret;
970 syscall_printf ("spawnve (%s, %s, %p)", path, argv[0], envp);
972 if (!envp)
973 envp = empty_env;
975 switch (_P_MODE (mode))
977 case _P_OVERLAY:
978 ch_spawn.worker (path, argv, envp, mode);
979 /* Errno should be set by worker. */
980 ret = -1;
981 break;
982 case _P_VFORK:
983 case _P_NOWAIT:
984 case _P_NOWAITO:
985 case _P_WAIT:
986 case _P_DETACH:
987 case _P_SYSTEM:
988 ret = ch_spawn.worker (path, argv, envp, mode);
989 break;
990 default:
991 set_errno (EINVAL);
992 ret = -1;
993 break;
995 return ret;
999 * spawn functions as implemented in the MS runtime library.
1000 * Most of these based on (and copied from) newlib/libc/posix/execXX.c
1003 extern "C" int
1004 spawnl (int mode, const char *path, const char *arg0, ...)
1006 int i;
1007 va_list args;
1008 const char *argv[256];
1010 va_start (args, arg0);
1011 argv[0] = arg0;
1012 i = 1;
1015 argv[i] = va_arg (args, const char *);
1016 while (argv[i++] != NULL);
1018 va_end (args);
1020 return spawnve (mode, path, (char * const *) argv, environ);
1023 extern "C" int
1024 spawnle (int mode, const char *path, const char *arg0, ...)
1026 int i;
1027 va_list args;
1028 const char * const *envp;
1029 const char *argv[256];
1031 va_start (args, arg0);
1032 argv[0] = arg0;
1033 i = 1;
1036 argv[i] = va_arg (args, const char *);
1037 while (argv[i++] != NULL);
1039 envp = va_arg (args, const char * const *);
1040 va_end (args);
1042 return spawnve (mode, path, (char * const *) argv, (char * const *) envp);
1045 extern "C" int
1046 spawnlp (int mode, const char *file, const char *arg0, ...)
1048 int i;
1049 va_list args;
1050 const char *argv[256];
1051 path_conv buf;
1053 va_start (args, arg0);
1054 argv[0] = arg0;
1055 i = 1;
1058 argv[i] = va_arg (args, const char *);
1059 while (argv[i++] != NULL);
1061 va_end (args);
1063 return spawnve (mode | _P_PATH_TYPE_EXEC, find_exec (file, buf),
1064 (char * const *) argv, environ);
1067 extern "C" int
1068 spawnlpe (int mode, const char *file, const char *arg0, ...)
1070 int i;
1071 va_list args;
1072 const char * const *envp;
1073 const char *argv[256];
1074 path_conv buf;
1076 va_start (args, arg0);
1077 argv[0] = arg0;
1078 i = 1;
1081 argv[i] = va_arg (args, const char *);
1082 while (argv[i++] != NULL);
1084 envp = va_arg (args, const char * const *);
1085 va_end (args);
1087 return spawnve (mode | _P_PATH_TYPE_EXEC, find_exec (file, buf),
1088 (char * const *) argv, envp);
1091 extern "C" int
1092 spawnv (int mode, const char *path, const char * const *argv)
1094 return spawnve (mode, path, argv, environ);
1097 extern "C" int
1098 spawnvp (int mode, const char *file, const char * const *argv)
1100 path_conv buf;
1101 return spawnve (mode | _P_PATH_TYPE_EXEC,
1102 find_exec (file, buf, "PATH", FE_NNF) ?: "",
1103 argv, environ);
1106 extern "C" int
1107 spawnvpe (int mode, const char *file, const char * const *argv,
1108 const char * const *envp)
1110 path_conv buf;
1111 return spawnve (mode | _P_PATH_TYPE_EXEC,
1112 find_exec (file, buf, "PATH", FE_NNF) ?: "",
1113 argv, envp);
1117 av::setup (const char *prog_arg, path_conv& real_path, const char *ext,
1118 int ac_in, const char *const *av_in, bool p_type_exec)
1120 const char *p;
1121 bool exeext = ascii_strcasematch (ext, ".exe");
1122 new (this) av (ac_in, av_in);
1123 if (!argc)
1125 set_errno (E2BIG);
1126 return -1;
1128 if ((exeext && real_path.iscygexec ()) || ascii_strcasematch (ext, ".bat")
1129 || (!*ext && ((p = ext - 4) > real_path.get_win32 ())
1130 && (ascii_strcasematch (p, ".bat") || ascii_strcasematch (p, ".cmd")
1131 || ascii_strcasematch (p, ".btm"))))
1132 /* no extra checks needed */;
1133 else
1134 while (1)
1136 char *pgm = NULL;
1137 char *arg1 = NULL;
1138 char *ptr, *buf;
1139 OBJECT_ATTRIBUTES attr;
1140 IO_STATUS_BLOCK io;
1141 HANDLE h;
1142 NTSTATUS status;
1143 LARGE_INTEGER size;
1145 status = NtOpenFile (&h, SYNCHRONIZE | GENERIC_READ,
1146 real_path.get_object_attr (attr, sec_none_nih),
1147 &io, FILE_SHARE_VALID_FLAGS,
1148 FILE_SYNCHRONOUS_IO_NONALERT
1149 | FILE_OPEN_FOR_BACKUP_INTENT
1150 | FILE_NON_DIRECTORY_FILE);
1151 if (status == STATUS_IO_REPARSE_TAG_NOT_HANDLED)
1153 /* This is most likely an app execution alias (such as the
1154 Windows Store version of Python, i.e. not a Cygwin program */
1155 real_path.set_cygexec (false);
1156 break;
1158 if (!NT_SUCCESS (status))
1160 /* File is not readable? Doesn't mean it's not executable.
1161 Test for executability and if so, just assume the file is
1162 a cygwin executable and go ahead. */
1163 if (status == STATUS_ACCESS_DENIED && real_path.has_acls ()
1164 && check_file_access (real_path, X_OK, true) == 0)
1166 real_path.set_cygexec (true);
1167 break;
1169 SetLastError (RtlNtStatusToDosError (status));
1170 goto err;
1172 if (!GetFileSizeEx (h, &size))
1174 NtClose (h);
1175 goto err;
1177 if (size.QuadPart > (LONGLONG) wincap.allocation_granularity ())
1178 size.LowPart = wincap.allocation_granularity ();
1180 HANDLE hm = CreateFileMapping (h, &sec_none_nih, PAGE_READONLY,
1181 0, 0, NULL);
1182 NtClose (h);
1183 if (!hm)
1185 /* ERROR_FILE_INVALID indicates very likely an empty file. */
1186 if (GetLastError () == ERROR_FILE_INVALID)
1188 debug_printf ("zero length file, treat as script.");
1189 goto just_shell;
1191 goto err;
1193 /* Try to map the first 64K of the image. That's enough for the local
1194 tests, and it's enough for hook_or_detect_cygwin to compute the IAT
1195 address. */
1196 buf = (char *) MapViewOfFile (hm, FILE_MAP_READ, 0, 0, size.LowPart);
1197 if (!buf)
1199 CloseHandle (hm);
1200 goto err;
1204 __try
1206 if (buf[0] == 'M' && buf[1] == 'Z')
1208 WORD subsys;
1209 unsigned off = (unsigned char) buf[0x18] | (((unsigned char) buf[0x19]) << 8);
1210 win16_exe = off < sizeof (IMAGE_DOS_HEADER);
1211 if (!win16_exe)
1212 real_path.set_cygexec (hook_or_detect_cygwin (buf, NULL,
1213 subsys, hm));
1214 else
1215 real_path.set_cygexec (false);
1216 UnmapViewOfFile (buf);
1217 CloseHandle (hm);
1218 break;
1221 __except (NO_ERROR)
1223 UnmapViewOfFile (buf);
1224 CloseHandle (hm);
1225 real_path.set_cygexec (false);
1226 break;
1228 __endtry
1230 CloseHandle (hm);
1232 debug_printf ("%s is possibly a script", real_path.get_win32 ());
1234 ptr = buf;
1235 if (*ptr++ == '#' && *ptr++ == '!')
1237 ptr += strspn (ptr, " \t");
1238 size_t len = strcspn (ptr, "\r\n");
1239 while (ptr[len - 1] == ' ' || ptr[len - 1] == '\t')
1240 len--;
1241 if (len)
1243 char *namebuf = (char *) alloca (len + 1);
1244 memcpy (namebuf, ptr, len);
1245 namebuf[len] = '\0';
1246 for (ptr = pgm = namebuf; *ptr; ptr++)
1247 if (!arg1 && (*ptr == ' ' || *ptr == '\t'))
1249 /* Null terminate the initial command and step over any
1250 additional white space. If we've hit the end of the
1251 line, exit the loop. Otherwise, we've found the first
1252 argument. Position the current pointer on the last known
1253 white space. */
1254 *ptr = '\0';
1255 char *newptr = ptr + 1;
1256 newptr += strspn (newptr, " \t");
1257 if (!*newptr)
1258 break;
1259 arg1 = newptr;
1260 ptr = newptr - 1;
1264 UnmapViewOfFile (buf);
1265 just_shell:
1266 /* Check if script is executable. Otherwise we start non-executable
1267 scripts successfully, which is incorrect behaviour. */
1268 if (real_path.has_acls ()
1269 && check_file_access (real_path, X_OK, true) < 0)
1270 return -1; /* errno is already set. */
1272 if (!pgm)
1274 if (!p_type_exec)
1276 /* Not called from exec[lv]p. Don't try to treat as script. */
1277 debug_printf ("%s is not a valid executable",
1278 real_path.get_win32 ());
1279 set_errno (ENOEXEC);
1280 return -1;
1282 pgm = (char *) "/bin/sh";
1283 arg1 = NULL;
1286 /* Replace argv[0] with the full path to the script if this is the
1287 first time through the loop. */
1288 replace0_maybe (prog_arg);
1290 /* pointers:
1291 * pgm interpreter name
1292 * arg1 optional string
1294 if (arg1)
1295 unshift (arg1);
1297 find_exec (pgm, real_path, "PATH", FE_NADA, &ext);
1298 unshift (real_path.get_posix ());
1300 if (real_path.iscygexec ())
1301 dup_all ();
1302 return 0;
1304 err:
1305 __seterrno ();
1306 return -1;
1309 /* The following __posix_spawn_* functions are called from newlib's posix_spawn
1310 implementation. The original code in newlib has been taken from FreeBSD,
1311 and the core code relies on specific, non-portable behaviour of vfork(2).
1312 Our replacement implementation uses a semaphore to synchronize parent and
1313 child process. Note: __posix_spawn_fork in fork.cc is part of the set. */
1315 /* Create an inheritable semaphore. Set it to 0 (== non-signalled), so the
1316 parent can wait on the semaphore immediately. */
1317 extern "C" int
1318 __posix_spawn_sem_create (void **semp)
1320 HANDLE sem;
1321 OBJECT_ATTRIBUTES attr;
1322 NTSTATUS status;
1324 if (!semp)
1325 return EINVAL;
1326 InitializeObjectAttributes (&attr, NULL, OBJ_INHERIT, NULL, NULL);
1327 status = NtCreateSemaphore (&sem, SEMAPHORE_ALL_ACCESS, &attr, 0, INT_MAX);
1328 if (!NT_SUCCESS (status))
1329 return geterrno_from_nt_status (status);
1330 *semp = sem;
1331 return 0;
1334 /* Signal the semaphore. "error" should be 0 if all went fine and the
1335 exec'd child process is up and running, a useful POSIX error code otherwise.
1336 After releasing the semaphore, the value of the semaphore reflects
1337 the error code + 1. Thus, after WFMO in__posix_spawn_sem_wait_and_close,
1338 querying the value of the semaphore returns either 0 if all went well,
1339 or a value > 0 equivalent to the POSIX error code. */
1340 extern "C" void
1341 __posix_spawn_sem_release (void *sem, int error)
1343 ReleaseSemaphore (sem, error + 1, NULL);
1346 /* Helper to check the semaphore value. */
1347 static inline int
1348 __posix_spawn_sem_query (void *sem)
1350 SEMAPHORE_BASIC_INFORMATION sbi;
1352 NtQuerySemaphore (sem, SemaphoreBasicInformation, &sbi, sizeof sbi, NULL);
1353 return sbi.CurrentCount;
1356 /* Called from parent to wait for fork/exec completion. We're waiting for
1357 the semaphore as well as the child's process handle, so even if the
1358 child crashes without signalling the semaphore, we won't wait infinitely. */
1359 extern "C" int
1360 __posix_spawn_sem_wait_and_close (void *sem, void *proc)
1362 int ret = 0;
1363 HANDLE w4[2] = { sem, proc };
1365 switch (WaitForMultipleObjects (2, w4, FALSE, INFINITE))
1367 case WAIT_OBJECT_0:
1368 ret = __posix_spawn_sem_query (sem);
1369 break;
1370 case WAIT_OBJECT_0 + 1:
1371 /* If we return here due to the child process dying, the semaphore is
1372 very likely not signalled. Check this here and return a valid error
1373 code. */
1374 ret = __posix_spawn_sem_query (sem);
1375 if (ret == 0)
1376 ret = ECHILD;
1377 break;
1378 default:
1379 ret = geterrno_from_win_error ();
1380 break;
1383 CloseHandle (sem);
1384 return ret;
1387 /* Replacement for execve/execvpe, called from forked child in newlib's
1388 posix_spawn. The relevant difference is the additional semaphore
1389 so the worker method (which is not supposed to return on success)
1390 can signal the semaphore after sync'ing with the exec'd child. */
1391 extern "C" int
1392 __posix_spawn_execvpe (const char *path, char * const *argv, char *const *envp,
1393 HANDLE sem, int use_env_path)
1395 path_conv buf;
1397 static char *const empty_env[] = { NULL };
1398 if (!envp)
1399 envp = empty_env;
1400 ch_spawn.set_sem (sem);
1401 ch_spawn.worker (use_env_path ? (find_exec (path, buf, "PATH", FE_NNF) ?: "")
1402 : path,
1403 argv, envp, _P_OVERLAY);
1404 __posix_spawn_sem_release (sem, errno);
1405 return -1;