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
16 #include <sys/cygwin.h>
25 #include "child_info.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 */
40 perhaps_suffix (const char *prog
, path_conv
& buf
, int& err
, unsigned opt
)
45 debug_printf ("prog '%s'", prog
);
46 buf
.check (prog
, PC_SYM_FOLLOW
| PC_NULLEMPTY
| PC_POSIX
, stat_suffixes
);
53 else if (!buf
.exists ())
58 else if (buf
.known_suffix ())
59 ext
= buf
.get_win32 () + (buf
.known_suffix () - buf
.get_win32 ());
61 ext
= strchr (buf
.get_win32 (), '\0');
63 debug_printf ("buf %s, suffix found '%s'", (char *) buf
.get_win32 (), 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. */
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
;
86 char *tmp
= tp
.c_get ();
87 bool has_slash
= !!strpbrk (name
, "/\\");
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. */
101 tmp_path
= stpcpy (tmp
, "./");
102 stpcpy (tmp_path
, name
);
104 retval
= buf
.get_posix ();
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
))
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
)
122 *stpncpy (tmp
, path
, NT_MAX_PATH
- 1) = '\0';
125 debug_printf ("searchpath %s", path
);
127 tmp_path
= tp
.c_get ();
130 char *eotmp
= strccpy (tmp_path
, &path
, ':');
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')))
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
, ".");
148 stpcpy (eotmp
, name
);
150 debug_printf ("trying %s", tmp_path
);
154 if ((suffix
= perhaps_suffix (tmp_path
, buf
, err1
, opt
)) != NULL
)
156 if (buf
.has_acls () && check_file_access (buf
, X_OK
, true))
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 ();
169 /* Couldn't find anything in the given path.
170 Take the appropriate action based on FE_NNF. */
173 buf
.check (name
, PC_SYM_FOLLOW
| PC_POSIX
);
174 retval
= buf
.get_posix ();
178 debug_printf ("%s = find_exec (%s)", (char *) buf
.get_posix (), name
);
180 *known_suffix
= suffix
?: strchr (buf
.get_win32 (), '\0');
186 /* Utility for child_info_spawn::worker. */
189 handle (int fd
, bool writing
)
192 cygheap_fdget
cfd (fd
);
195 h
= INVALID_HANDLE_VALUE
;
196 else if (cfd
->close_on_exec ())
197 h
= INVALID_HANDLE_VALUE
;
199 h
= cfd
->get_handle_nat ();
201 h
= cfd
->get_output_handle_nat ();
207 iscmd (const char *argv0
, const char *what
)
210 n
= strlen (argv0
) - strlen (what
);
211 if (n
>= 2 && argv0
[1] != ':')
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
;
223 __pthread_cleanup_handler cleanup_handler
;
225 bool is_system_call ()
227 return oldint
!= ILLEGAL_SIG_FUNC_PTR
;
229 system_call_handle (bool issystem
)
232 oldint
= ILLEGAL_SIG_FUNC_PTR
;
235 sig_send (NULL
, __SIGHOLD
);
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
);
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
)
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. */
300 syscall_printf ("prog_arg is empty");
301 set_errno (ENOENT
); /* Per POSIX */
305 syscall_printf ("mode = %d, prog_arg = %.9500s", mode
, prog_arg
);
307 /* FIXME: This is no error condition on Linux. */
310 syscall_printf ("argv is NULL");
317 PWCHAR envblock
= NULL
;
319 bool reset_sendsig
= false;
322 PWCHAR runpath
= tp
.w_get ();
325 STARTUPINFOW si
= {};
328 fhandler_termios::spawn_worker term_spawn_worker
;
330 system_call_handle
system_call (mode
== _P_SYSTEM
);
334 child_info_types chtype
;
335 if (mode
== _P_OVERLAY
)
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. */
346 for (ac
= 0; argv
[ac
]; ac
++)
351 if ((ext
= perhaps_suffix (prog_arg
, real_path
, err
, FE_NADA
)) == NULL
)
358 res
= newargv
.setup (prog_arg
, real_path
, ext
, ac
, argv
, p_type_exec
);
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 ());
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 ()))
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
;
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
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
;
431 if (IsProcessInJob (GetCurrentProcess (), NULL
, &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
;
445 fhandler_console::need_invisible ();
447 if (mode
!= _P_OVERLAY
)
448 myself
->exec_sendsig
= NULL
;
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 (),
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] == ':')
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 ());
491 set_errno (ENAMETOOLONG
);
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 ()
509 if (!moreinfo
->envp
|| !envblock
)
515 set (chtype
, real_path
.iscygexec ());
517 __stdout
= in__stdout
;
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. */
540 ::cygheap
->ctty
? ::cygheap
->ctty
->tc_getpgid () : 0;
541 if (!iscygwin () && ctty_pgid
&& ctty_pgid
!= myself
->pgid
)
542 c_flags
|= CREATE_NEW_PROCESS_GROUP
;
545 if (c_flags
& CREATE_NEW_PROCESS_GROUP
)
546 myself
->process_state
|= PID_NEW_PG
;
548 if (mode
== _P_DETACH
)
550 else if (mode
!= _P_OVERLAY
|| !my_wr_proc_pipe
)
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. */
564 SetHandleInformation (wr_proc_pipe
, HANDLE_FLAG_INHERIT
, 0);
565 SetHandleInformation (parent
, HANDLE_FLAG_INHERIT
, 0);
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
))
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;
584 bool need_send_sig
= false;
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);
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. */
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);
629 init_console_handler (CTTY_IS_VALID (myself
->ctty
));
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 */
657 envblock
, /* environment */
664 /* Give access to myself */
665 if (mode
== _P_OVERLAY
)
669 HWINSTA hwst_orig
= GetProcessWindowStation ();
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
;
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
);
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,
693 system_printf ("CreateDesktop failed, %E");
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 */
709 envblock
, /* environment */
715 SetProcessWindowStation (hwst_orig
);
716 CloseWindowStation (hwst
);
720 SetThreadDesktop (hdsk_orig
);
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
735 syscall_printf ("CreateProcess failed, %E");
736 /* If this was a failed exec, restore the saved 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.
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 ();
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
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
;
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
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
);
801 myself
->set_has_pgid_children ();
802 ProtectHandle (pi
.hThread
);
804 PID_IN_USE
| (real_path
.iscygexec () ? 0 : PID_NOTCYGWIN
));
807 syscall_printf ("pinfo failed");
808 if (get_errno () != ENOMEM
)
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
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
;
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
);
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. */
855 DuplicateHandle (GetCurrentProcess (), wr_proc_pipe
, pi
.hProcess
, NULL
,
856 0, false, DUPLICATE_SAME_ACCESS
);
857 ResumeThread (pi
.hThread
);
859 strace
.write_childpid (pi
.dwProcessId
);
861 ForceCloseHandle (pi
.hThread
);
863 sigproc_printf ("spawned windows pid %d", pi
.dwProcessId
);
866 if ((mode
== _P_DETACH
|| mode
== _P_NOWAIT
) && !iscygwin ())
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;
876 myself
.hProcess
= pi
.hProcess
;
879 if (!proc_retry (pi
.hProcess
))
884 close_all_files (true);
889 close_all_files (true);
891 && WaitForSingleObject (pi
.hProcess
, 0) == WAIT_TIMEOUT
)
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. */
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
);
918 if (waitpid (cygpid
, &res
, 0) != cygpid
)
920 term_spawn_worker
.cleanup ();
923 res
= 0; /* Lost all memory of this child. */
936 if (get_errno () == ENOMEM
)
943 term_spawn_worker
.close_handle_set ();
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.
963 spawnve (int mode
, const char *path
, const char *const *argv
,
964 const char *const *envp
)
966 static char *const empty_env
[] = { NULL
};
970 syscall_printf ("spawnve (%s, %s, %p)", path
, argv
[0], envp
);
975 switch (_P_MODE (mode
))
978 ch_spawn
.worker (path
, argv
, envp
, mode
);
979 /* Errno should be set by worker. */
988 ret
= ch_spawn
.worker (path
, argv
, envp
, mode
);
999 * spawn functions as implemented in the MS runtime library.
1000 * Most of these based on (and copied from) newlib/libc/posix/execXX.c
1004 spawnl (int mode
, const char *path
, const char *arg0
, ...)
1008 const char *argv
[256];
1010 va_start (args
, arg0
);
1015 argv
[i
] = va_arg (args
, const char *);
1016 while (argv
[i
++] != NULL
);
1020 return spawnve (mode
, path
, (char * const *) argv
, environ
);
1024 spawnle (int mode
, const char *path
, const char *arg0
, ...)
1028 const char * const *envp
;
1029 const char *argv
[256];
1031 va_start (args
, arg0
);
1036 argv
[i
] = va_arg (args
, const char *);
1037 while (argv
[i
++] != NULL
);
1039 envp
= va_arg (args
, const char * const *);
1042 return spawnve (mode
, path
, (char * const *) argv
, (char * const *) envp
);
1046 spawnlp (int mode
, const char *file
, const char *arg0
, ...)
1050 const char *argv
[256];
1053 va_start (args
, arg0
);
1058 argv
[i
] = va_arg (args
, const char *);
1059 while (argv
[i
++] != NULL
);
1063 return spawnve (mode
| _P_PATH_TYPE_EXEC
, find_exec (file
, buf
),
1064 (char * const *) argv
, environ
);
1068 spawnlpe (int mode
, const char *file
, const char *arg0
, ...)
1072 const char * const *envp
;
1073 const char *argv
[256];
1076 va_start (args
, arg0
);
1081 argv
[i
] = va_arg (args
, const char *);
1082 while (argv
[i
++] != NULL
);
1084 envp
= va_arg (args
, const char * const *);
1087 return spawnve (mode
| _P_PATH_TYPE_EXEC
, find_exec (file
, buf
),
1088 (char * const *) argv
, envp
);
1092 spawnv (int mode
, const char *path
, const char * const *argv
)
1094 return spawnve (mode
, path
, argv
, environ
);
1098 spawnvp (int mode
, const char *file
, const char * const *argv
)
1101 return spawnve (mode
| _P_PATH_TYPE_EXEC
,
1102 find_exec (file
, buf
, "PATH", FE_NNF
) ?: "",
1107 spawnvpe (int mode
, const char *file
, const char * const *argv
,
1108 const char * const *envp
)
1111 return spawnve (mode
| _P_PATH_TYPE_EXEC
,
1112 find_exec (file
, buf
, "PATH", FE_NNF
) ?: "",
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
)
1121 bool exeext
= ascii_strcasematch (ext
, ".exe");
1122 new (this) av (ac_in
, av_in
);
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 */;
1139 OBJECT_ATTRIBUTES attr
;
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);
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);
1169 SetLastError (RtlNtStatusToDosError (status
));
1172 if (!GetFileSizeEx (h
, &size
))
1177 if (size
.QuadPart
> (LONGLONG
) wincap
.allocation_granularity ())
1178 size
.LowPart
= wincap
.allocation_granularity ();
1180 HANDLE hm
= CreateFileMapping (h
, &sec_none_nih
, PAGE_READONLY
,
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.");
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
1196 buf
= (char *) MapViewOfFile (hm
, FILE_MAP_READ
, 0, 0, size
.LowPart
);
1206 if (buf
[0] == 'M' && buf
[1] == 'Z')
1209 unsigned off
= (unsigned char) buf
[0x18] | (((unsigned char) buf
[0x19]) << 8);
1210 win16_exe
= off
< sizeof (IMAGE_DOS_HEADER
);
1212 real_path
.set_cygexec (hook_or_detect_cygwin (buf
, NULL
,
1215 real_path
.set_cygexec (false);
1216 UnmapViewOfFile (buf
);
1223 UnmapViewOfFile (buf
);
1225 real_path
.set_cygexec (false);
1232 debug_printf ("%s is possibly a script", real_path
.get_win32 ());
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')
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
1255 char *newptr
= ptr
+ 1;
1256 newptr
+= strspn (newptr
, " \t");
1264 UnmapViewOfFile (buf
);
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. */
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
);
1282 pgm
= (char *) "/bin/sh";
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
);
1291 * pgm interpreter name
1292 * arg1 optional string
1297 find_exec (pgm
, real_path
, "PATH", FE_NADA
, &ext
);
1298 unshift (real_path
.get_posix ());
1300 if (real_path
.iscygexec ())
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. */
1318 __posix_spawn_sem_create (void **semp
)
1321 OBJECT_ATTRIBUTES attr
;
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
);
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. */
1341 __posix_spawn_sem_release (void *sem
, int error
)
1343 ReleaseSemaphore (sem
, error
+ 1, NULL
);
1346 /* Helper to check the semaphore value. */
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. */
1360 __posix_spawn_sem_wait_and_close (void *sem
, void *proc
)
1363 HANDLE w4
[2] = { sem
, proc
};
1365 switch (WaitForMultipleObjects (2, w4
, FALSE
, INFINITE
))
1368 ret
= __posix_spawn_sem_query (sem
);
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
1374 ret
= __posix_spawn_sem_query (sem
);
1379 ret
= geterrno_from_win_error ();
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. */
1392 __posix_spawn_execvpe (const char *path
, char * const *argv
, char *const *envp
,
1393 HANDLE sem
, int use_env_path
)
1397 static char *const empty_env
[] = { NULL
};
1400 ch_spawn
.set_sem (sem
);
1401 ch_spawn
.worker (use_env_path
? (find_exec (path
, buf
, "PATH", FE_NNF
) ?: "")
1403 argv
, envp
, _P_OVERLAY
);
1404 __posix_spawn_sem_release (sem
, errno
);