OSDN Git Service

* fhandler_process.cc: Drop unneeded includes.
[pf3gnuchains/pf3gnuchains4x.git] / winsup / cygwin / spawn.cc
1 /* spawn.cc
2
3    Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4    2005, 2006, 2007, 2008, 2009, 2010, 2011 Red Hat, Inc.
5
6 This file is part of Cygwin.
7
8 This software is a copyrighted work licensed under the terms of the
9 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
10 details. */
11
12 #include "winsup.h"
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <process.h>
16 #include <sys/wait.h>
17 #include <wingdi.h>
18 #include <winuser.h>
19 #include <wchar.h>
20 #include <ctype.h>
21 #include "cygerrno.h"
22 #include <sys/cygwin.h>
23 #include "security.h"
24 #include "path.h"
25 #include "fhandler.h"
26 #include "dtable.h"
27 #include "sigproc.h"
28 #include "cygheap.h"
29 #include "child_info.h"
30 #include "pinfo.h"
31 #include "environ.h"
32 #include "cygtls.h"
33 #include "tls_pbuf.h"
34 #include "winf.h"
35 #include "ntdll.h"
36
37 static suffix_info NO_COPY exe_suffixes[] =
38 {
39   suffix_info ("", 1),
40   suffix_info (".exe", 1),
41   suffix_info (".com"),
42   suffix_info (NULL)
43 };
44
45 #if 0
46 /* CV, 2009-11-05: Used to be used when searching for DLLs in calls to
47    dlopen().  However, dlopen() on other platforms never adds a suffix by
48    its own.  Therefore we use stat_suffixes now, which only adds a .exe
49    suffix for symmetry. */
50 static suffix_info dll_suffixes[] =
51 {
52   suffix_info (".dll"),
53   suffix_info ("", 1),
54   suffix_info (".exe", 1),
55   suffix_info (NULL)
56 };
57 #endif
58
59 /* Add .exe to PROG if not already present and see if that exists.
60    If not, return PROG (converted from posix to win32 rules if necessary).
61    The result is always BUF.
62
63    Returns (possibly NULL) suffix */
64
65 static const char *
66 perhaps_suffix (const char *prog, path_conv& buf, int& err, unsigned opt)
67 {
68   const char *ext;
69
70   err = 0;
71   debug_printf ("prog '%s'", prog);
72   buf.check (prog, PC_SYM_FOLLOW | PC_NULLEMPTY,
73              (opt & FE_DLL) ? stat_suffixes : exe_suffixes);
74
75   if (buf.isdir ())
76     {
77       err = EACCES;
78       ext = NULL;
79     }
80   else if (!buf.exists ())
81     {
82       err = ENOENT;
83       ext = NULL;
84     }
85   else if (buf.known_suffix)
86     ext = buf.get_win32 () + (buf.known_suffix - buf.get_win32 ());
87   else
88     ext = strchr (buf.get_win32 (), '\0');
89
90   debug_printf ("buf %s, suffix found '%s'", (char *) buf.get_win32 (), ext);
91   return ext;
92 }
93
94 /* Find an executable name, possibly by appending known executable
95    suffixes to it.  The win32-translated name is placed in 'buf'.
96    Any found suffix is returned in known_suffix.
97
98    If the file is not found and !null_if_not_found then the win32 version
99    of name is placed in buf and returned.  Otherwise the contents of buf
100    is undefined and NULL is returned.  */
101
102 const char * __stdcall
103 find_exec (const char *name, path_conv& buf, const char *mywinenv,
104            unsigned opt, const char **known_suffix)
105 {
106   const char *suffix = "";
107   debug_printf ("find_exec (%s)", name);
108   const char *retval;
109   tmp_pathbuf tp;
110   char *tmp = tp.c_get ();
111   const char *posix = (opt & FE_NATIVE) ? NULL : name;
112   bool has_slash = !!strpbrk (name, "/\\");
113   int err;
114
115   /* Check to see if file can be opened as is first.
116      Win32 systems always check . first, but PATH may not be set up to
117      do this. */
118   if ((has_slash || opt & FE_CWD)
119       && (suffix = perhaps_suffix (name, buf, err, opt)) != NULL)
120     {
121       if (posix && !has_slash)
122         {
123           tmp[0] = '.';
124           tmp[1] = '/';
125           strcpy (tmp + 2, name);
126           posix = tmp;
127         }
128       retval = buf.get_win32 ();
129       goto out;
130     }
131
132   win_env *winpath;
133   const char *path;
134   const char *posix_path;
135
136   posix = (opt & FE_NATIVE) ? NULL : tmp;
137
138   if (strchr (mywinenv, '/'))
139     {
140       /* it's not really an environment variable at all */
141       int n = cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, mywinenv, NULL, 0);
142       char *s = (char *) alloca (n);
143       if (cygwin_conv_path_list (CCP_POSIX_TO_WIN_A, mywinenv, s, n))
144         goto errout;
145       path = s;
146       posix_path = mywinenv - 1;
147     }
148   else if (has_slash || strchr (name, '\\') || isdrive (name)
149       || !(winpath = getwinenv (mywinenv))
150       || !(path = winpath->get_native ()) || *path == '\0')
151     /* Return the error condition if this is an absolute path or if there
152        is no PATH to search. */
153     goto errout;
154   else
155     posix_path = winpath->get_posix () - 1;
156
157   debug_printf ("%s%s", mywinenv, path);
158   /* Iterate over the specified path, looking for the file with and without
159      executable extensions. */
160   do
161     {
162       posix_path++;
163       char *eotmp = strccpy (tmp, &path, ';');
164       /* An empty path or '.' means the current directory, but we've
165          already tried that.  */
166       if (opt & FE_CWD && (tmp[0] == '\0' || (tmp[0] == '.' && tmp[1] == '\0')))
167         continue;
168
169       *eotmp++ = '\\';
170       strcpy (eotmp, name);
171
172       debug_printf ("trying %s", tmp);
173
174       int err1;
175
176       if ((suffix = perhaps_suffix (tmp, buf, err1, opt)) != NULL)
177         {
178           if (buf.has_acls () && check_file_access (buf, X_OK, true))
179             continue;
180
181           if (posix == tmp)
182             {
183               eotmp = strccpy (tmp, &posix_path, ':');
184               if (eotmp == tmp)
185                 *eotmp++ = '.';
186               *eotmp++ = '/';
187               strcpy (eotmp, name);
188             }
189           retval = buf.get_win32 ();
190           goto out;
191         }
192     }
193   while (*path && *++path && (posix_path = strchr (posix_path, ':')));
194
195  errout:
196   posix = NULL;
197   /* Couldn't find anything in the given path.
198      Take the appropriate action based on null_if_not_found. */
199   if (opt & FE_NNF)
200     retval = NULL;
201   else if (!(opt & FE_NATIVE))
202     retval = name;
203   else
204     {
205       buf.check (name);
206       retval = buf.get_win32 ();
207     }
208
209  out:
210   if (posix)
211     retval = buf.set_path (posix);
212   debug_printf ("%s = find_exec (%s)", (char *) buf.get_win32 (), name);
213   if (known_suffix)
214     *known_suffix = suffix ?: strchr (buf.get_win32 (), '\0');
215   if (!retval && err)
216     set_errno (err);
217   return retval;
218 }
219
220 /* Utility for child_info_spawn::worker.  */
221
222 static HANDLE
223 handle (int fd, bool writing)
224 {
225   HANDLE h;
226   cygheap_fdget cfd (fd);
227
228   if (cfd < 0)
229     h = INVALID_HANDLE_VALUE;
230   else if (cfd->close_on_exec ())
231     h = INVALID_HANDLE_VALUE;
232   else if (!writing)
233     h = cfd->get_handle ();
234   else
235     h = cfd->get_output_handle ();
236
237   return h;
238 }
239
240 int
241 iscmd (const char *argv0, const char *what)
242 {
243   int n;
244   n = strlen (argv0) - strlen (what);
245   if (n >= 2 && argv0[1] != ':')
246     return 0;
247   return n >= 0 && strcasematch (argv0 + n, what) &&
248          (n == 0 || isdirsep (argv0[n - 1]));
249 }
250
251 struct pthread_cleanup
252 {
253   _sig_func_ptr oldint;
254   _sig_func_ptr oldquit;
255   sigset_t oldmask;
256   pthread_cleanup (): oldint (NULL), oldquit (NULL), oldmask ((sigset_t) -1) {}
257 };
258
259 static void
260 do_cleanup (void *args)
261 {
262 # define cleanup ((pthread_cleanup *) args)
263   if (cleanup->oldmask != (sigset_t) -1)
264     {
265       signal (SIGINT, cleanup->oldint);
266       signal (SIGQUIT, cleanup->oldquit);
267       sigprocmask (SIG_SETMASK, &(cleanup->oldmask), NULL);
268     }
269 # undef cleanup
270 }
271
272 NO_COPY child_info_spawn ch_spawn;
273
274 int
275 child_info_spawn::worker (const char *prog_arg, const char *const *argv,
276                           const char *const envp[], int mode,
277                           int in__stdin, int in__stdout)
278 {
279   bool rc;
280   pid_t cygpid;
281   int res = -1;
282
283   /* Check if we have been called from exec{lv}p or spawn{lv}p and mask
284      mode to keep only the spawn mode. */
285   bool p_type_exec = !!(mode & _P_PATH_TYPE_EXEC);
286   mode = _P_MODE (mode);
287
288   if (prog_arg == NULL)
289     {
290       syscall_printf ("prog_arg is NULL");
291       set_errno (EFAULT);       /* As on Linux. */
292       return -1;
293     }
294   if (!prog_arg[0])
295     {
296       syscall_printf ("prog_arg is empty");
297       set_errno (ENOENT);       /* Per POSIX */
298       return -1;
299     }
300
301   syscall_printf ("mode = %d, prog_arg = %.9500s", mode, prog_arg);
302
303   /* FIXME: This is no error condition on Linux. */
304   if (argv == NULL)
305     {
306       syscall_printf ("argv is NULL");
307       set_errno (EINVAL);
308       return -1;
309     }
310
311   /* FIXME: There is a small race here and FIXME: not thread safe! */
312
313   pthread_cleanup cleanup;
314   if (mode == _P_SYSTEM)
315     {
316       sigset_t child_block;
317       cleanup.oldint = signal (SIGINT, SIG_IGN);
318       cleanup.oldquit = signal (SIGQUIT, SIG_IGN);
319       sigemptyset (&child_block);
320       sigaddset (&child_block, SIGCHLD);
321       sigprocmask (SIG_BLOCK, &child_block, &cleanup.oldmask);
322     }
323   pthread_cleanup_push (do_cleanup, (void *) &cleanup);
324   av newargv;
325   linebuf one_line;
326   PWCHAR envblock = NULL;
327   path_conv real_path;
328   bool reset_sendsig = false;
329
330   tmp_pathbuf tp;
331   PWCHAR runpath = tp.w_get ();
332   int c_flags;
333   bool wascygexec;
334
335   bool null_app_name = false;
336   STARTUPINFOW si = {};
337   int looped = 0;
338   HANDLE orig_wr_proc_pipe = NULL;
339
340   myfault efault;
341   if (efault.faulted ())
342     {
343       if (get_errno () == ENOMEM)
344         set_errno (E2BIG);
345       else
346         set_errno (EFAULT);
347       res = -1;
348       goto out;
349     }
350
351   child_info_types chtype;
352   if (mode != _P_OVERLAY)
353     chtype = _CH_SPAWN;
354   else
355     chtype = _CH_EXEC;
356
357   moreinfo = cygheap_exec_info::alloc ();
358
359   /* CreateProcess takes one long string that is the command line (sigh).
360      We need to quote any argument that has whitespace or embedded "'s.  */
361
362   int ac;
363   for (ac = 0; argv[ac]; ac++)
364     /* nothing */;
365
366   newargv.set (ac, argv);
367
368   int err;
369   const char *ext;
370   if ((ext = perhaps_suffix (prog_arg, real_path, err, FE_NADA)) == NULL)
371     {
372       set_errno (err);
373       res = -1;
374       goto out;
375     }
376
377
378   wascygexec = real_path.iscygexec ();
379   res = newargv.fixup (prog_arg, real_path, ext, p_type_exec);
380
381   if (res)
382     goto out;
383
384   if (!real_path.iscygexec () && ::cygheap->cwd.get_error ())
385     {
386       small_printf ("Error: Current working directory %s.\n"
387                     "Can't start native Windows application from here.\n\n",
388                     ::cygheap->cwd.get_error_desc ());
389       set_errno (::cygheap->cwd.get_error ());
390       res = -1;
391       goto out;
392     }
393
394   if (ac == 3 && argv[1][0] == '/' && argv[1][1] == 'c' &&
395       (iscmd (argv[0], "command.com") || iscmd (argv[0], "cmd.exe")))
396     {
397       real_path.check (prog_arg);
398       one_line.add ("\"");
399       if (!real_path.error)
400         one_line.add (real_path.get_win32 ());
401       else
402         one_line.add (argv[0]);
403       one_line.add ("\"");
404       one_line.add (" ");
405       one_line.add (argv[1]);
406       one_line.add (" ");
407       one_line.add (argv[2]);
408       real_path.set_path (argv[0]);
409       null_app_name = true;
410     }
411   else
412     {
413       if (wascygexec)
414         newargv.dup_all ();
415       else if (!one_line.fromargv (newargv, real_path.get_win32 (),
416                                    real_path.iscygexec ()))
417         {
418           res = -1;
419           goto out;
420         }
421
422
423       newargv.all_calloced ();
424       moreinfo->argc = newargv.argc;
425       moreinfo->argv = newargv;
426
427       if (mode != _P_OVERLAY ||
428           !DuplicateHandle (GetCurrentProcess (), myself.shared_handle (),
429                             GetCurrentProcess (), &moreinfo->myself_pinfo,
430                             0, TRUE, DUPLICATE_SAME_ACCESS))
431         moreinfo->myself_pinfo = NULL;
432       else
433         VerifyHandle (moreinfo->myself_pinfo);
434     }
435   WCHAR wone_line[one_line.ix + 1];
436   if (one_line.ix)
437     sys_mbstowcs (wone_line, one_line.ix + 1, one_line.buf);
438   else
439     wone_line[0] = L'\0';
440
441   PROCESS_INFORMATION pi;
442   pi.hProcess = pi.hThread = NULL;
443   pi.dwProcessId = pi.dwThreadId = 0;
444
445   /* Set up needed handles for stdio */
446   si.dwFlags = STARTF_USESTDHANDLES;
447   si.hStdInput = handle ((in__stdin < 0 ? 0 : in__stdin), false);
448   si.hStdOutput = handle ((in__stdout < 0 ? 1 : in__stdout), true);
449   si.hStdError = handle (2, true);
450
451   si.cb = sizeof (si);
452
453   c_flags = GetPriorityClass (GetCurrentProcess ());
454   sigproc_printf ("priority class %d", c_flags);
455   /* We're adding the CREATE_BREAKAWAY_FROM_JOB flag here to workaround issues
456      with the "Program Compatibility Assistant (PCA) Service" observed on
457      Windows 7.  For some reason, when starting long running sessions from
458      mintty, the affected svchost.exe process takes more and more memory and
459      at one point takes over the CPU.  At this point the machine becomes
460      unresponsive.  The only way to get back to normal is to stop the entire
461      mintty session, or to stop the PCA service.  However, a process which
462      is controlled by PCA is part of a compatibility job, which allows child
463      processes to break away from the job.  This helps to avoid this issue. */
464   c_flags |= CREATE_SEPARATE_WOW_VDM | CREATE_UNICODE_ENVIRONMENT
465              | CREATE_BREAKAWAY_FROM_JOB;
466
467   if (mode == _P_DETACH)
468     c_flags |= DETACHED_PROCESS;
469   else
470     fhandler_console::need_invisible ();
471
472   if (mode != _P_OVERLAY)
473     myself->exec_sendsig = NULL;
474   else
475     {
476       /* Reset sendsig so that any process which wants to send a signal
477          to this pid will wait for the new process to become active.
478          Save the old value in case the exec fails.  */
479       if (!myself->exec_sendsig)
480         {
481           myself->exec_sendsig = myself->sendsig;
482           myself->exec_dwProcessId = myself->dwProcessId;
483           myself->sendsig = NULL;
484           reset_sendsig = true;
485         }
486       /* Save a copy of a handle to the current process around the first time we
487          exec so that the pid will not be reused.  Why did I stop cygwin from
488          generating its own pids again? */
489       if (::cygheap->pid_handle)
490         /* already done previously */;
491       else if (DuplicateHandle (GetCurrentProcess (), GetCurrentProcess (),
492                                 GetCurrentProcess (), &::cygheap->pid_handle,
493                                 PROCESS_QUERY_INFORMATION, TRUE, 0))
494         ProtectHandleINH (::cygheap->pid_handle);
495       else
496         system_printf ("duplicate to pid_handle failed, %E");
497     }
498
499   if (null_app_name)
500     runpath = NULL;
501   else
502     {
503       USHORT len = real_path.get_nt_native_path ()->Length / sizeof (WCHAR);
504       if (RtlEqualUnicodePathPrefix (real_path.get_nt_native_path (),
505                                      &ro_u_natp, FALSE))
506         {
507           runpath = real_path.get_wide_win32_path (runpath);
508           /* If the executable path length is < MAX_PATH, make sure the long
509              path win32 prefix is removed from the path to make subsequent
510              not long path aware native Win32 child processes happy. */
511           if (len < MAX_PATH + 4)
512             {
513               if (runpath[5] == ':')
514                 runpath += 4;
515               else if (len < MAX_PATH + 6)
516                 *(runpath += 6) = L'\\';
517             }
518         }
519       else if (len < NT_MAX_PATH - ro_u_globalroot.Length / sizeof (WCHAR))
520         {
521           UNICODE_STRING rpath;
522
523           RtlInitEmptyUnicodeString (&rpath, runpath,
524                                      (NT_MAX_PATH - 1) * sizeof (WCHAR));
525           RtlCopyUnicodeString (&rpath, &ro_u_globalroot);
526           RtlAppendUnicodeStringToString (&rpath,
527                                           real_path.get_nt_native_path ());
528         }
529       else
530         {
531           set_errno (ENAMETOOLONG);
532           res = -1;
533           goto out;
534         }
535     }
536   syscall_printf ("null_app_name %d (%W, %.9500W)", null_app_name,
537                   runpath, wone_line);
538
539   cygbench ("spawn-worker");
540
541   if (!real_path.iscygexec())
542     ::cygheap->fdtab.set_file_pointers_for_exec ();
543
544   moreinfo->envp = build_env (envp, envblock, moreinfo->envc,
545                               real_path.iscygexec ());
546   if (!moreinfo->envp || !envblock)
547     {
548       set_errno (E2BIG);
549       res = -1;
550       goto out;
551     }
552   set (chtype, real_path.iscygexec ());
553   __stdin = in__stdin;
554   __stdout = in__stdout;
555   record_children ();
556
557   si.lpReserved2 = (LPBYTE) this;
558   si.cbReserved2 = sizeof (*this);
559
560   /* Depends on set call above.
561      Some file types might need extra effort in the parent after CreateProcess
562      and before copying the datastructures to the child.  So we have to start
563      the child in suspend state, unfortunately, to avoid a race condition. */
564   if (!newargv.win16_exe
565       && (!iscygwin () || mode != _P_OVERLAY
566           || ::cygheap->fdtab.need_fixup_before ()))
567     c_flags |= CREATE_SUSPENDED;
568   /* If a native application should be spawned, we test here if the spawning
569      process is running in a console and, if so, if it's a foreground or
570      background process.  If it's a background process, we start the native
571      process with the CREATE_NEW_PROCESS_GROUP flag set.  This lets the native
572      process ignore Ctrl-C by default.  If we don't do that, pressing Ctrl-C
573      in a console will break native processes running in the background,
574      because the Ctrl-C event is sent to all processes in the console, unless
575      they ignore it explicitely.  CREATE_NEW_PROCESS_GROUP does that for us. */
576   if (!iscygwin () && myself->ctty >= 0 && iscons_dev (myself->ctty)
577       && fhandler_console::tc_getpgid () != getpgrp ())
578     c_flags |= CREATE_NEW_PROCESS_GROUP;
579   refresh_cygheap ();
580   /* When ruid != euid we create the new process under the current original
581      account and impersonate in child, this way maintaining the different
582      effective vs. real ids.
583      FIXME: If ruid != euid and ruid != saved_uid we currently give
584      up on ruid. The new process will have ruid == euid. */
585 loop:
586   ::cygheap->user.deimpersonate ();
587
588   if (!real_path.iscygexec () && mode == _P_OVERLAY)
589     myself->process_state |= PID_NOTCYGWIN;
590
591   if (!::cygheap->user.issetuid ()
592       || (::cygheap->user.saved_uid == ::cygheap->user.real_uid
593           && ::cygheap->user.saved_gid == ::cygheap->user.real_gid
594           && !::cygheap->user.groups.issetgroups ()
595           && !::cygheap->user.setuid_to_restricted))
596     {
597       rc = CreateProcessW (runpath,       /* image name - with full path */
598                            wone_line,     /* what was passed to exec */
599                            &sec_none_nih, /* process security attrs */
600                            &sec_none_nih, /* thread security attrs */
601                            TRUE,          /* inherit handles from parent */
602                            c_flags,
603                            envblock,      /* environment */
604                            NULL,
605                            &si,
606                            &pi);
607     }
608   else
609     {
610       /* Give access to myself */
611       if (mode == _P_OVERLAY)
612         myself.set_acl();
613
614       WCHAR wstname[1024] = { L'\0' };
615       HWINSTA hwst_orig = NULL, hwst = NULL;
616       HDESK hdsk_orig = NULL, hdsk = NULL;
617       PSECURITY_ATTRIBUTES sa;
618       DWORD n;
619
620       hwst_orig = GetProcessWindowStation ();
621       hdsk_orig = GetThreadDesktop (GetCurrentThreadId ());
622       GetUserObjectInformationW (hwst_orig, UOI_NAME, wstname, 1024, &n);
623       /* Prior to Vista it was possible to start a service with the
624          "Interact with desktop" flag.  This started the service in the
625          interactive window station of the console.  A big security
626          risk, but we don't want to disable this behaviour for older
627          OSes because it's still heavily used by some users.  They have
628          been warned. */
629       if (!::cygheap->user.setuid_to_restricted
630           && wcscasecmp (wstname, L"WinSta0") != 0)
631         {
632           WCHAR sid[128];
633
634           sa = sec_user ((PSECURITY_ATTRIBUTES) alloca (1024),
635                          ::cygheap->user.sid ());
636           /* We're creating a window station per user, not per logon session.
637              First of all we might not have a valid logon session for
638              the user (logon by create_token), and second, it doesn't
639              make sense in terms of security to create a new window
640              station for every logon of the same user.  It just fills up
641              the system with window stations for no good reason. */
642           hwst = CreateWindowStationW (::cygheap->user.get_windows_id (sid), 0,
643                                        GENERIC_READ | GENERIC_WRITE, sa);
644           if (!hwst)
645             system_printf ("CreateWindowStation failed, %E");
646           else if (!SetProcessWindowStation (hwst))
647             system_printf ("SetProcessWindowStation failed, %E");
648           else if (!(hdsk = CreateDesktopW (L"Default", NULL, NULL, 0,
649                                             GENERIC_ALL, sa)))
650             system_printf ("CreateDesktop failed, %E");
651           else
652             {
653               wcpcpy (wcpcpy (wstname, sid), L"\\Default");
654               si.lpDesktop = wstname;
655               debug_printf ("Desktop: %W", si.lpDesktop);
656             }
657         }
658
659       rc = CreateProcessAsUserW (::cygheap->user.primary_token (),
660                            runpath,       /* image name - with full path */
661                            wone_line,     /* what was passed to exec */
662                            &sec_none_nih, /* process security attrs */
663                            &sec_none_nih, /* thread security attrs */
664                            TRUE,          /* inherit handles from parent */
665                            c_flags,
666                            envblock,      /* environment */
667                            NULL,
668                            &si,
669                            &pi);
670       if (hwst)
671         {
672           SetProcessWindowStation (hwst_orig);
673           CloseWindowStation (hwst);
674         }
675       if (hdsk)
676         {
677           SetThreadDesktop (hdsk_orig);
678           CloseDesktop (hdsk);
679         }
680     }
681
682   /* Restore impersonation. In case of _P_OVERLAY this isn't
683      allowed since it would overwrite child data. */
684   if (mode != _P_OVERLAY || !rc)
685     ::cygheap->user.reimpersonate ();
686
687   /* Set errno now so that debugging messages from it appear before our
688      final debugging message [this is a general rule for debugging
689      messages].  */
690   if (!rc)
691     {
692       __seterrno ();
693       syscall_printf ("CreateProcess failed, %E");
694       /* If this was a failed exec, restore the saved sendsig. */
695       if (reset_sendsig)
696         {
697           myself->sendsig = myself->exec_sendsig;
698           myself->exec_sendsig = NULL;
699         }
700       myself->process_state &= ~PID_NOTCYGWIN;
701       res = -1;
702       goto out;
703     }
704
705   /* The CREATE_SUSPENDED case is handled below */
706   if (iscygwin () && !(c_flags & CREATE_SUSPENDED))
707     strace.write_childpid (pi.dwProcessId);
708
709   /* Fixup the parent data structures if needed and resume the child's
710      main thread. */
711   if (::cygheap->fdtab.need_fixup_before ())
712     ::cygheap->fdtab.fixup_before_exec (pi.dwProcessId);
713
714   if (mode != _P_OVERLAY)
715     cygpid = cygwin_pid (pi.dwProcessId);
716   else
717     cygpid = myself->pid;
718
719   /* We print the original program name here so the user can see that too.  */
720   syscall_printf ("%d = child_info_spawn::worker(%s, %.9500s)",
721                   rc ? cygpid : (unsigned int) -1, prog_arg, one_line.buf);
722
723   /* Name the handle similarly to proc_subproc. */
724   ProtectHandle1 (pi.hProcess, childhProc);
725
726   bool synced;
727   pid_t pid;
728   if (mode == _P_OVERLAY)
729     {
730       myself->dwProcessId = pi.dwProcessId;
731       strace.execing = 1;
732       myself.hProcess = hExeced = pi.hProcess;
733       real_path.get_wide_win32_path (myself->progname); // FIXME: race?
734       sigproc_printf ("new process name %W", myself->progname);
735       /* If wr_proc_pipe doesn't exist then this process was not started by a cygwin
736          process.  So, we need to wait around until the process we've just "execed"
737          dies.  Use our own wait facility to wait for our own pid to exit (there
738          is some minor special case code in proc_waiter and friends to accommodate
739          this).
740
741          If wr_proc_pipe exists, then it should be duplicated to the child.
742          If the child has exited already, that's ok.  The parent will pick up
743          on this fact when we exit.  dup_proc_pipe will close our end of the pipe.
744          Note that wr_proc_pipe may also be == INVALID_HANDLE_VALUE.  That will make
745          dup_proc_pipe essentially a no-op.  */
746       if (!newargv.win16_exe && myself->wr_proc_pipe)
747         {
748           if (!looped)
749             myself->sync_proc_pipe ();  /* Make sure that we own wr_proc_pipe
750                                            just in case we've been previously
751                                            execed. */
752           orig_wr_proc_pipe = myself->dup_proc_pipe (pi.hProcess);
753         }
754       pid = myself->pid;
755       if (!iscygwin ())
756         close_all_files ();
757     }
758   else
759     {
760       myself->set_has_pgid_children ();
761       ProtectHandle (pi.hThread);
762       pinfo child (cygpid,
763                    PID_IN_USE | (real_path.iscygexec () ? 0 : PID_NOTCYGWIN));
764       if (!child)
765         {
766           syscall_printf ("pinfo failed");
767           if (get_errno () != ENOMEM)
768             set_errno (EAGAIN);
769           res = -1;
770           goto out;
771         }
772       child->dwProcessId = pi.dwProcessId;
773       child.hProcess = pi.hProcess;
774
775       real_path.get_wide_win32_path (child->progname);
776       /* FIXME: This introduces an unreferenced, open handle into the child.
777          The purpose is to keep the pid shared memory open so that all of
778          the fields filled out by child.remember do not disappear and so there
779          is not a brief period during which the pid is not available.
780          However, we should try to find another way to do this eventually. */
781       DuplicateHandle (GetCurrentProcess (), child.shared_handle (),
782                        pi.hProcess, NULL, 0, 0, DUPLICATE_SAME_ACCESS);
783       child->start_time = time (NULL); /* Register child's starting time. */
784       child->nice = myself->nice;
785       if (!child.remember (mode == _P_DETACH))
786         {
787           /* FIXME: Child in strange state now */
788           CloseHandle (pi.hProcess);
789           ForceCloseHandle (pi.hThread);
790           res = -1;
791           goto out;
792         }
793       pid = child->pid;
794     }
795
796   /* Start the child running */
797   if (c_flags & CREATE_SUSPENDED)
798     {
799       ResumeThread (pi.hThread);
800       if (iscygwin ())
801         strace.write_childpid (pi.dwProcessId);
802     }
803   ForceCloseHandle (pi.hThread);
804
805   sigproc_printf ("spawned windows pid %d", pi.dwProcessId);
806
807   if ((mode == _P_DETACH || mode == _P_NOWAIT) && !iscygwin ())
808     synced = false;
809   else
810     synced = sync (pi.dwProcessId, pi.hProcess, INFINITE);
811
812   switch (mode)
813     {
814     case _P_OVERLAY:
815       myself.hProcess = pi.hProcess;
816       if (!synced)
817         {
818           if (orig_wr_proc_pipe)
819             {
820               myself->wr_proc_pipe_owner = GetCurrentProcessId ();
821               myself->wr_proc_pipe = orig_wr_proc_pipe;
822             }
823           if (!proc_retry (pi.hProcess))
824             {
825               looped++;
826               goto loop;
827             }
828           close_all_files (true);
829         }
830       else
831         {
832           close_all_files (true);
833           if (!myself->wr_proc_pipe
834               && WaitForSingleObject (pi.hProcess, 0) == WAIT_TIMEOUT)
835             {
836               extern bool is_toplevel_proc;
837               is_toplevel_proc = true;
838               myself.remember (false);
839               wait_for_myself ();
840             }
841         }
842       this->cleanup ();
843       myself.exit (EXITCODE_NOSET);
844       break;
845     case _P_WAIT:
846     case _P_SYSTEM:
847       if (waitpid (cygpid, &res, 0) != cygpid)
848         res = -1;
849       break;
850     case _P_DETACH:
851       res = 0;  /* Lost all memory of this child. */
852       break;
853     case _P_NOWAIT:
854     case _P_NOWAITO:
855     case _P_VFORK:
856       res = cygpid;
857       break;
858     default:
859       break;
860     }
861
862 out:
863   this->cleanup ();
864   if (envblock)
865     free (envblock);
866   pthread_cleanup_pop (1);
867   return (int) res;
868 }
869
870 extern "C" int
871 cwait (int *result, int pid, int)
872 {
873   return waitpid (pid, result, 0);
874 }
875
876 /*
877 * Helper function for spawn runtime calls.
878 * Doesn't search the path.
879 */
880
881 extern "C" int
882 spawnve (int mode, const char *path, const char *const *argv,
883        const char *const *envp)
884 {
885   static char *const empty_env[] = { NULL };
886
887   int ret;
888 #ifdef NEWVFORK
889   vfork_save *vf = vfork_storage.val ();
890
891   if (vf != NULL && (vf->pid < 0) && mode == _P_OVERLAY)
892     mode = _P_NOWAIT;
893   else
894     vf = NULL;
895 #endif
896
897   syscall_printf ("spawnve (%s, %s, %x)", path, argv[0], envp);
898
899   if (!envp)
900     envp = empty_env;
901
902   switch (_P_MODE (mode))
903     {
904     case _P_OVERLAY:
905       ch_spawn.worker (path, argv, envp, mode);
906       /* Errno should be set by worker.  */
907       ret = -1;
908       break;
909     case _P_VFORK:
910     case _P_NOWAIT:
911     case _P_NOWAITO:
912     case _P_WAIT:
913     case _P_DETACH:
914     case _P_SYSTEM:
915       ret = ch_spawn.worker (path, argv, envp, mode);
916 #ifdef NEWVFORK
917       if (vf)
918         {
919           if (ret > 0)
920             {
921               debug_printf ("longjmping due to vfork");
922               vf->restore_pid (ret);
923             }
924         }
925 #endif
926       break;
927     default:
928       set_errno (EINVAL);
929       ret = -1;
930       break;
931     }
932   return ret;
933 }
934
935 /*
936 * spawn functions as implemented in the MS runtime library.
937 * Most of these based on (and copied from) newlib/libc/posix/execXX.c
938 */
939
940 extern "C" int
941 spawnl (int mode, const char *path, const char *arg0, ...)
942 {
943   int i;
944   va_list args;
945   const char *argv[256];
946
947   va_start (args, arg0);
948   argv[0] = arg0;
949   i = 1;
950
951   do
952       argv[i] = va_arg (args, const char *);
953   while (argv[i++] != NULL);
954
955   va_end (args);
956
957   return spawnve (mode, path, (char * const  *) argv, cur_environ ());
958 }
959
960 extern "C" int
961 spawnle (int mode, const char *path, const char *arg0, ...)
962 {
963   int i;
964   va_list args;
965   const char * const *envp;
966   const char *argv[256];
967
968   va_start (args, arg0);
969   argv[0] = arg0;
970   i = 1;
971
972   do
973     argv[i] = va_arg (args, const char *);
974   while (argv[i++] != NULL);
975
976   envp = va_arg (args, const char * const *);
977   va_end (args);
978
979   return spawnve (mode, path, (char * const *) argv, (char * const *) envp);
980 }
981
982 extern "C" int
983 spawnlp (int mode, const char *file, const char *arg0, ...)
984 {
985   int i;
986   va_list args;
987   const char *argv[256];
988   path_conv buf;
989
990   va_start (args, arg0);
991   argv[0] = arg0;
992   i = 1;
993
994   do
995       argv[i] = va_arg (args, const char *);
996   while (argv[i++] != NULL);
997
998   va_end (args);
999
1000   return spawnve (mode | _P_PATH_TYPE_EXEC, find_exec (file, buf),
1001                   (char * const *) argv, cur_environ ());
1002 }
1003
1004 extern "C" int
1005 spawnlpe (int mode, const char *file, const char *arg0, ...)
1006 {
1007   int i;
1008   va_list args;
1009   const char * const *envp;
1010   const char *argv[256];
1011   path_conv buf;
1012
1013   va_start (args, arg0);
1014   argv[0] = arg0;
1015   i = 1;
1016
1017   do
1018     argv[i] = va_arg (args, const char *);
1019   while (argv[i++] != NULL);
1020
1021   envp = va_arg (args, const char * const *);
1022   va_end (args);
1023
1024   return spawnve (mode | _P_PATH_TYPE_EXEC, find_exec (file, buf),
1025                   (char * const *) argv, envp);
1026 }
1027
1028 extern "C" int
1029 spawnv (int mode, const char *path, const char * const *argv)
1030 {
1031   return spawnve (mode, path, argv, cur_environ ());
1032 }
1033
1034 extern "C" int
1035 spawnvp (int mode, const char *file, const char * const *argv)
1036 {
1037   path_conv buf;
1038   return spawnve (mode | _P_PATH_TYPE_EXEC, find_exec (file, buf), argv,
1039                   cur_environ ());
1040 }
1041
1042 extern "C" int
1043 spawnvpe (int mode, const char *file, const char * const *argv,
1044           const char * const *envp)
1045 {
1046   path_conv buf;
1047   return spawnve (mode | _P_PATH_TYPE_EXEC, find_exec (file, buf), argv, envp);
1048 }
1049
1050 int
1051 av::fixup (const char *prog_arg, path_conv& real_path, const char *ext,
1052            bool p_type_exec)
1053 {
1054   const char *p;
1055   bool exeext = ascii_strcasematch (ext, ".exe");
1056   if ((exeext && real_path.iscygexec ()) || ascii_strcasematch (ext, ".bat"))
1057     return 0;
1058   if (!*ext && ((p = ext - 4) > real_path.get_win32 ())
1059       && (ascii_strcasematch (p, ".bat") || ascii_strcasematch (p, ".cmd")
1060           || ascii_strcasematch (p, ".btm")))
1061     return 0;
1062   while (1)
1063     {
1064       char *pgm = NULL;
1065       char *arg1 = NULL;
1066       char *ptr, *buf;
1067       OBJECT_ATTRIBUTES attr;
1068       IO_STATUS_BLOCK io;
1069       HANDLE h;
1070       NTSTATUS status;
1071       LARGE_INTEGER size;
1072
1073       status = NtOpenFile (&h, SYNCHRONIZE | GENERIC_READ,
1074                            real_path.get_object_attr (attr, sec_none_nih),
1075                            &io, FILE_SHARE_VALID_FLAGS,
1076                            FILE_SYNCHRONOUS_IO_NONALERT
1077                            | FILE_OPEN_FOR_BACKUP_INTENT
1078                            | FILE_NON_DIRECTORY_FILE);
1079       if (!NT_SUCCESS (status))
1080         {
1081           /* File is not readable?  Doesn't mean it's not executable.
1082              Test for executability and if so, just assume the file is
1083              a cygwin executable and go ahead. */
1084           if (status == STATUS_ACCESS_DENIED && real_path.has_acls ()
1085               && check_file_access (real_path, X_OK, true) == 0)
1086             {
1087               real_path.set_cygexec (true);
1088               break;
1089             }
1090           goto err;
1091         }
1092       if (!GetFileSizeEx (h, &size))
1093         {
1094           NtClose (h);
1095           goto err;
1096         }
1097       if (size.QuadPart > wincap.allocation_granularity ())
1098         size.LowPart = wincap.allocation_granularity ();
1099
1100       HANDLE hm = CreateFileMapping (h, &sec_none_nih, PAGE_READONLY,
1101                                      0, 0, NULL);
1102       NtClose (h);
1103       if (!hm)
1104         {
1105           /* ERROR_FILE_INVALID indicates very likely an empty file. */
1106           if (GetLastError () == ERROR_FILE_INVALID)
1107             {
1108               debug_printf ("zero length file, treat as script.");
1109               goto just_shell;
1110             }
1111           goto err;
1112         }
1113       /* Try to map the first 64K of the image.  That's enough for the local
1114          tests, and it's enough for hook_or_detect_cygwin to compute the IAT
1115          address. */
1116       buf = (char *) MapViewOfFile (hm, FILE_MAP_READ, 0, 0, size.LowPart);
1117       if (!buf)
1118         {
1119           CloseHandle (hm);
1120           goto err;
1121         }
1122
1123       {
1124         myfault efault;
1125         if (efault.faulted ())
1126           {
1127             UnmapViewOfFile (buf);
1128             CloseHandle (hm);
1129             real_path.set_cygexec (false);
1130             break;
1131           }
1132         if (buf[0] == 'M' && buf[1] == 'Z')
1133           {
1134             WORD subsys;
1135             unsigned off = (unsigned char) buf[0x18] | (((unsigned char) buf[0x19]) << 8);
1136             win16_exe = off < sizeof (IMAGE_DOS_HEADER);
1137             if (!win16_exe)
1138               real_path.set_cygexec (!!hook_or_detect_cygwin (buf, NULL,
1139                                                               subsys, hm));
1140             else
1141               real_path.set_cygexec (false);
1142             UnmapViewOfFile (buf);
1143             CloseHandle (hm);
1144             break;
1145           }
1146       }
1147       CloseHandle (hm);
1148
1149       debug_printf ("%s is possibly a script", real_path.get_win32 ());
1150
1151       ptr = buf;
1152       if (*ptr++ == '#' && *ptr++ == '!')
1153         {
1154           ptr += strspn (ptr, " \t");
1155           size_t len = strcspn (ptr, "\r\n");
1156           if (len)
1157             {
1158               char *namebuf = (char *) alloca (len + 1);
1159               memcpy (namebuf, ptr, len);
1160               namebuf[len] = '\0';
1161               for (ptr = pgm = namebuf; *ptr; ptr++)
1162                 if (!arg1 && (*ptr == ' ' || *ptr == '\t'))
1163                   {
1164                     /* Null terminate the initial command and step over any
1165                        additional white space.  If we've hit the end of the
1166                        line, exit the loop.  Otherwise, we've found the first
1167                        argument. Position the current pointer on the last known
1168                        white space. */
1169                     *ptr = '\0';
1170                     char *newptr = ptr + 1;
1171                     newptr += strspn (newptr, " \t");
1172                     if (!*newptr)
1173                       break;
1174                     arg1 = newptr;
1175                     ptr = newptr - 1;
1176                   }
1177             }
1178         }
1179       UnmapViewOfFile (buf);
1180 just_shell:
1181       if (!pgm)
1182         {
1183           if (!p_type_exec)
1184             {
1185               /* Not called from exec[lv]p.  Don't try to treat as script. */
1186               debug_printf ("%s is not a valid executable",
1187                             real_path.get_win32 ());
1188               set_errno (ENOEXEC);
1189               return -1;
1190             }
1191           if (ascii_strcasematch (ext, ".com"))
1192             break;
1193           pgm = (char *) "/bin/sh";
1194           arg1 = NULL;
1195         }
1196
1197       /* Check if script is executable.  Otherwise we start non-executable
1198          scripts successfully, which is incorrect behaviour. */
1199       if (real_path.has_acls ()
1200           && check_file_access (real_path, X_OK, true) < 0)
1201         return -1;      /* errno is already set. */
1202
1203       /* Replace argv[0] with the full path to the script if this is the
1204          first time through the loop. */
1205       replace0_maybe (prog_arg);
1206
1207       /* pointers:
1208        * pgm    interpreter name
1209        * arg1   optional string
1210        */
1211       if (arg1)
1212         unshift (arg1);
1213
1214       /* FIXME: This should not be using FE_NATIVE.  It should be putting
1215          the posix path on the argv list. */
1216       find_exec (pgm, real_path, "PATH=", FE_NATIVE, &ext);
1217       unshift (real_path.get_win32 (), 1);
1218     }
1219   return 0;
1220
1221 err:
1222   __seterrno ();
1223   return -1;
1224 }