1 /* dcrt0.cc -- essentially the main() for the Cygwin dll
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
10 #include "create_posix_thread.h"
16 #include <sys/param.h>
22 #include "perprocess.h"
27 #include "child_info_magic.h"
29 #include "shared_info.h"
30 #include "cygwin_version.h"
32 #include "cygmalloc.h"
35 #include "exception.h"
40 #define MAX_AT_FILE_LEVEL 10
42 #define PREMAIN_LEN (sizeof (user_data->premain) / sizeof (user_data->premain[0]))
44 extern "C" void cygwin_exit (int) __attribute__ ((noreturn
));
45 extern "C" void __sinit (_reent
*);
47 static int NO_COPY envc
;
48 static char NO_COPY
**envp
;
50 bool NO_COPY jit_debug
;
55 void (**pfunc
) () = user_data
->dtors
;
58 user_data
->dtors
= NULL
;
65 do_global_ctors (void (**in_pfunc
)(), int force
)
67 if (!force
&& __in_forkee
== FORKING
)
68 return; // inherit constructed stuff from parent pid
70 /* Run ctors backwards, so skip the first entry and find how many
71 there are, then run them. */
73 void (**pfunc
) () = in_pfunc
;
77 while (--pfunc
> in_pfunc
)
82 * Replaces @file in the command line with the contents of the file.
83 * There may be multiple @file's in a single command line
84 * A \@file is replaced with @file so that echo \@foo would print
85 * @foo and not the contents of foo.
88 insert_file (char *name
, char *&cmd
)
94 PWCHAR wname
= tp
.w_get ();
95 sys_mbstowcs (wname
, NT_MAX_PATH
, name
+ 1);
96 f
= CreateFileW (wname
,
97 GENERIC_READ
, /* open for reading */
98 FILE_SHARE_VALID_FLAGS
, /* share for reading */
99 &sec_none_nih
, /* default security */
100 OPEN_EXISTING
, /* existing file only */
101 FILE_ATTRIBUTE_NORMAL
, /* normal file */
102 NULL
); /* no attr. template */
104 if (f
== INVALID_HANDLE_VALUE
)
106 debug_printf ("couldn't open file '%s', %E", name
);
110 /* This only supports files up to about 4 billion bytes in
111 size. I am making the bold assumption that this is big
112 enough for this feature */
113 size
= GetFileSize (f
, NULL
);
114 if (size
== 0xFFFFFFFF)
117 debug_printf ("couldn't get file size for '%s', %E", name
);
121 int new_size
= strlen (cmd
) + size
+ 2;
122 char *tmp
= (char *) malloc (new_size
);
126 debug_printf ("malloc failed, %E");
130 /* realloc passed as it should */
133 rf_result
= ReadFile (f
, tmp
, size
, &rf_read
, NULL
);
135 if (!rf_result
|| (rf_read
!= size
))
138 debug_printf ("ReadFile failed, %E");
143 strcpy (tmp
+ size
, cmd
);
152 return ch
== '"' || ch
== '\'';
155 /* Step over a run of characters delimited by quotes */
156 static /*__inline*/ char *
157 quoted (char *cmd
, int winshell
)
165 strcpy (cmd
, cmd
+ 1);
166 if (*(p
= strchrnul (cmd
, quote
)))
171 const char *s
= quote
== '\'' ? "'" : "\\\"";
172 /* This must have been run from a Windows shell, so preserve
173 quotes for globify to play with later. */
174 while (*cmd
&& *++cmd
)
175 if ((p
= strpbrk (cmd
, s
)) == NULL
)
177 cmd
= strchr (cmd
, '\0'); // no closing quote
182 else if (quote
== '"' && p
[1] == '"')
185 cmd
= ++p
; // a quoted quote
189 cmd
= p
+ 1; // point to after end
195 /* Perform a glob on word if it contains wildcard characters.
196 Also quote every character between quotes to force glob to
197 treat the characters literally. */
199 /* Either X:[...] or \\server\[...] */
200 #define is_dos_path(s) (isdrive(s) \
203 && isalpha ((s)[2]) \
204 && strchr ((s) + 3, '\\')))
207 globify (char *word
, char **&argv
, int &argc
, int &argvlen
)
209 if (*word
!= '~' && strpbrk (word
, "?*[\"\'(){}") == NULL
)
214 int dos_spec
= is_dos_path (word
);
215 if (!dos_spec
&& isquote (*word
) && word
[1] && word
[2])
216 dos_spec
= is_dos_path (word
+ 1);
218 /* We'll need more space if there are quoting characters in
219 word. If that is the case, doubling the size of the
220 string should provide more than enough space. */
221 if (strpbrk (word
, "'\""))
223 char pattern
[strlen (word
) + ((dos_spec
+ 1) * n
) + 1];
225 /* Fill pattern with characters from word, quoting any
226 characters found within quotes. */
227 for (p
= pattern
, s
= word
; *s
!= '\000'; s
++, p
++)
230 if (dos_spec
&& *s
== '\\')
237 while (*++s
&& *s
!= quote
)
239 if (dos_spec
|| *s
!= '\\')
241 else if (s
[1] == quote
|| s
[1] == '\\')
244 size_t cnt
= isascii (*s
) ? 1 : mbtowc (NULL
, s
, MB_CUR_MAX
);
245 if (cnt
<= 1 || cnt
== (size_t)-1)
265 /* Attempt to match the argument. Return just word (minus quoting) if no match. */
266 if (glob (pattern
, GLOB_TILDE
| GLOB_NOCHECK
| GLOB_BRACE
| GLOB_QUOTE
, NULL
, &gl
) || !gl
.gl_pathc
)
269 /* Allocate enough space in argv for the matched filenames. */
271 if ((argc
+= gl
.gl_pathc
) > argvlen
)
274 argv
= (char **) realloc (argv
, (1 + argvlen
) * sizeof (argv
[0]));
277 /* Copy the matched filenames to argv. */
278 char **gv
= gl
.gl_pathv
;
279 char **av
= argv
+ n
;
282 debug_printf ("argv[%d] = '%s'", n
++, *gv
);
286 /* Clean up after glob. */
291 /* Build argv, argc from string passed from Windows. */
294 build_argv (char *cmd
, char **&argv
, int &argc
, int winshell
)
297 int nesting
= 0; // monitor "nesting" from insert_file
303 /* Scan command line until there is nothing left. */
313 /* Found the beginning of an argument. */
315 char *sawquote
= NULL
;
318 if (*cmd
!= '"' && (!winshell
|| *cmd
!= '\''))
319 cmd
++; // Skip over this character
321 /* Skip over characters until the closing quote */
324 /* Handle quoting. Only strip off quotes if the parent is
325 a Cygwin process, or if the word starts with a '@'.
326 In this case, the insert_file function needs an unquoted
327 DOS filename and globbing isn't performed anyway. */
328 cmd
= quoted (cmd
, winshell
&& argc
> 0 && *word
!= '@');
330 if (issep (*cmd
)) // End of argument if space
334 *cmd
++ = '\0'; // Terminate `word'
336 /* Possibly look for @file construction assuming that this isn't
337 the very first argument and the @ wasn't quoted */
338 if (argc
&& sawquote
!= word
&& *word
== '@')
340 if (++nesting
> MAX_AT_FILE_LEVEL
)
341 api_fatal ("Too many levels of nesting for %s", word
);
342 if (insert_file (word
, cmd
))
343 continue; // There's new stuff in cmd now
346 /* See if we need to allocate more space for argv */
350 argv
= (char **) realloc (argv
, (1 + argvlen
) * sizeof (argv
[0]));
353 /* Add word to argv file after (optional) wildcard expansion. */
354 if (!winshell
|| !argc
|| !globify (word
, argv
, argc
, argvlen
))
356 debug_printf ("argv[%d] = '%s'", argc
, word
);
364 debug_printf ("argc %d", argc
);
367 /* sanity and sync check */
369 check_sanity_and_sync (per_process
*p
)
371 /* Sanity check to make sure developers didn't change the per_process */
372 /* struct without updating SIZEOF_PER_PROCESS [it makes them think twice */
373 /* about changing it]. */
374 if (sizeof (per_process
) != SIZEOF_PER_PROCESS
)
375 api_fatal ("per_process sanity check failed");
377 /* magic_biscuit must be SIZEOF_PER_PROCESS. */
378 if (p
->magic_biscuit
!= SIZEOF_PER_PROCESS
)
379 api_fatal ("Incompatible cygwin .dll -- incompatible per_process info %u != %u",
380 p
->magic_biscuit
, SIZEOF_PER_PROCESS
);
382 /* Complain if incompatible API changes made */
383 if (p
->api_major
> cygwin_version
.api_major
)
384 api_fatal ("cygwin DLL and APP are out of sync -- API version mismatch %u > %u",
385 p
->api_major
, cygwin_version
.api_major
);
388 child_info NO_COPY
*child_proc_info
;
390 /* Extend the stack prior to fork longjmp. */
392 child_info_fork::alloc_stack ()
394 PTEB teb
= NtCurrentTeb ();
395 if (teb
->Tib
.StackBase
!= stackbase
)
400 /* If guardsize is -1, we have been started from a pthread with an
401 application-provided stack, and the stack has just to be used as is. */
402 if (guardsize
== (size_t) -1)
404 /* Reserve entire stack. */
405 stacksize
= (PBYTE
) stackbase
- (PBYTE
) stackaddr
;
406 if (!VirtualAlloc (stackaddr
, stacksize
, MEM_RESERVE
, PAGE_NOACCESS
))
408 api_fatal ("fork: can't reserve memory for parent stack "
409 "%p - %p, (child has %p - %p), %E",
410 stackaddr
, stackbase
, teb
->DeallocationStack
,
413 /* Commit the area commited in parent. */
414 stacksize
= (PBYTE
) stackbase
- (PBYTE
) stacklimit
;
415 stack_ptr
= VirtualAlloc (stacklimit
, stacksize
, MEM_COMMIT
,
418 api_fatal ("can't commit memory for stack %p(%ly), %E",
419 stacklimit
, stacksize
);
420 /* Set up guardpages. */
421 ULONG real_guardsize
= guardsize
422 ? roundup2 (guardsize
, wincap
.page_size ())
423 : wincap
.def_guard_page_size ();
424 if (stack_ptr
> stackaddr
)
426 stack_ptr
= (void *) ((PBYTE
) stack_ptr
- real_guardsize
);
427 if (!VirtualAlloc (stack_ptr
, real_guardsize
, MEM_COMMIT
,
428 PAGE_READWRITE
| PAGE_GUARD
))
429 api_fatal ("fork: couldn't allocate new stack guard page %p, %E",
432 /* Set thread stack guarantee matching the guardsize.
433 Note that the guardsize is one page bigger than the guarantee. */
434 if (real_guardsize
> wincap
.def_guard_page_size ())
436 real_guardsize
-= wincap
.page_size ();
437 SetThreadStackGuarantee (&real_guardsize
);
442 /* Fork has been called from main thread. Simply commit the region
443 of the stack commited in the parent but not yet commited in the
444 child and create new guardpages. */
445 if (NtCurrentTeb ()->Tib
.StackLimit
> stacklimit
)
447 SIZE_T commitsize
= (PBYTE
) NtCurrentTeb ()->Tib
.StackLimit
448 - (PBYTE
) stacklimit
;
449 if (!VirtualAlloc (stacklimit
, commitsize
, MEM_COMMIT
, PAGE_READWRITE
))
450 api_fatal ("can't commit child memory for stack %p(%ly), %E",
451 stacklimit
, commitsize
);
452 PVOID guardpage
= (PBYTE
) stacklimit
- wincap
.def_guard_page_size ();
453 if (!VirtualAlloc (guardpage
, wincap
.def_guard_page_size (),
454 MEM_COMMIT
, PAGE_READWRITE
| PAGE_GUARD
))
455 api_fatal ("fork: couldn't allocate new stack guard page %p, %E",
457 NtCurrentTeb ()->Tib
.StackLimit
= stacklimit
;
459 /* This only affects forked children of a process started from a native
460 64 bit process, but it doesn't hurt to do it unconditionally. Fix
461 StackBase in the child to be the same as in the parent, so that the
462 computation of _my_tls is correct. */
463 teb
->Tib
.StackBase
= (PVOID
) stackbase
;
470 static int NO_COPY sent_break
;
473 debug_printf ("break here");
479 if (GetEnvironmentVariableA ("CYGWIN_TESTING", NULL
, 0))
484 if (GetEnvironmentVariableA ("CYGWIN_DEBUG", buf
, sizeof (buf
) - 1))
487 GetModuleFileName (NULL
, buf1
, PATH_MAX
);
488 char *p
= strpbrk (buf
, ":=");
490 p
= (char *) "gdb.exe -nw";
493 if (strcasestr (buf1
, buf
))
495 extern PWCHAR debugger_command
;
497 debugger_command
= (PWCHAR
) HeapAlloc (GetProcessHeap (), 0,
498 (2 * NT_MAX_PATH
+ 20)
500 if (!debugger_command
)
502 error_start_init (p
);
505 console_printf ("*** Sending Break. gdb may issue spurious SIGTRAP message.\n");
513 get_cygwin_startup_info ()
517 GetStartupInfo (&si
);
518 child_info
*res
= (child_info
*) si
.lpReserved2
;
520 if (si
.cbReserved2
< EXEC_MAGIC_SIZE
|| !res
521 || res
->intro
!= PROC_MAGIC_GENERIC
|| res
->magic
!= CHILD_INFO_MAGIC
)
523 strace
.activate (false);
528 if ((res
->intro
& OPROC_MAGIC_MASK
) == OPROC_MAGIC_GENERIC
)
529 multiple_cygwin_problem ("proc intro", res
->intro
, 0);
531 unsigned should_be_cb
= 0;
535 __in_forkee
= FORKING
;
536 should_be_cb
= sizeof (child_info_fork
);
541 should_be_cb
= sizeof (child_info_spawn
);
542 if (should_be_cb
!= res
->cb
)
543 multiple_cygwin_problem ("proc size", res
->cb
, should_be_cb
);
544 else if (sizeof (fhandler_union
) != res
->fhandler_union_cb
)
545 multiple_cygwin_problem ("fhandler size", res
->fhandler_union_cb
,
546 sizeof (fhandler_union
));
547 if (res
->isstraced ())
549 while (!being_debugged ())
551 strace
.activate (res
->type
== _CH_FORK
);
555 system_printf ("unknown exec type %u", res
->type
);
566 #define dll_data_start &__data_start__
567 #define dll_data_end &__data_end__
568 #define dll_bss_start &__bss_start__
569 #define dll_bss_end &__bss_end__
572 child_info_fork::handle_fork ()
574 cygheap_fixup_in_child (false);
576 myself
.thisproc (NULL
);
577 myself
->uid
= cygheap
->user
.real_uid
;
578 myself
->gid
= cygheap
->user
.real_gid
;
580 child_copy (parent
, false, silentfail (),
581 "dll data", dll_data_start
, dll_data_end
,
582 "dll bss", dll_bss_start
, dll_bss_end
,
583 "user heap", cygheap
->user_heap
.base
, cygheap
->user_heap
.ptr
,
586 /* If my_wr_proc_pipe != NULL then it's a leftover handle from a previously
587 forked process. Close it now or suffer confusion with the parent of our
590 ForceCloseHandle1 (my_wr_proc_pipe
, wr_proc_pipe
);
592 /* Setup our write end of the process pipe. Clear the one in the structure.
593 The destructor should never be called for this but, it can't hurt to be
595 my_wr_proc_pipe
= wr_proc_pipe
;
596 rd_proc_pipe
= wr_proc_pipe
= NULL
;
597 /* Do the relocations here. These will actually likely be overwritten by the
598 below child_copy but we do them here in case there is a read-only section
599 which does not get copied by fork. */
600 _pei386_runtime_relocator (user_data
);
602 /* step 2 now that the dll has its heap filled in, we can fill in the
603 user's data and bss since user_data is now filled out. */
604 child_copy (parent
, false, silentfail (),
605 "data", user_data
->data_start
, user_data
->data_end
,
606 "bss", user_data
->bss_start
, user_data
->bss_end
,
609 if (fixup_mmaps_after_fork (parent
))
610 api_fatal ("recreate_mmaps_after_fork_failed");
612 /* We need to occupy the address space for dynamically loaded dlls
613 before we allocate any dynamic object, or we may end up with
614 error "address space needed by <dll> is already occupied"
615 for no good reason (seen with some relocated dll). */
616 dlls
.reserve_space ();
620 child_info_spawn::get_parent_handle ()
622 parent
= OpenProcess (PROCESS_VM_READ
, FALSE
, parent_winpid
);
627 child_info_spawn::handle_spawn ()
629 extern void fixup_lockf_after_exec (bool);
630 HANDLE h
= INVALID_HANDLE_VALUE
;
631 if (!dynamically_loaded
|| get_parent_handle ())
633 cygheap_fixup_in_child (true);
637 cygheap
->pid
= cygpid
;
639 /* Spawned process sets h to INVALID_HANDLE_VALUE to notify
640 pinfo::thisproc not to create another pid. */
641 if (!moreinfo
->myself_pinfo
||
642 !DuplicateHandle (GetCurrentProcess (), moreinfo
->myself_pinfo
,
643 GetCurrentProcess (), &h
, 0,
644 FALSE
, DUPLICATE_SAME_ACCESS
| DUPLICATE_CLOSE_SOURCE
))
645 h
= (type
== _CH_SPAWN
) ? INVALID_HANDLE_VALUE
: NULL
;
647 /* Setup our write end of the process pipe. Clear the one in the structure.
648 The destructor should never be called for this but, it can't hurt to be
650 my_wr_proc_pipe
= wr_proc_pipe
;
651 rd_proc_pipe
= wr_proc_pipe
= NULL
;
654 __argc
= moreinfo
->argc
;
655 __argv
= moreinfo
->argv
;
656 envp
= moreinfo
->envp
;
657 envc
= moreinfo
->envc
;
658 if (!dynamically_loaded
)
659 cygheap
->fdtab
.fixup_after_exec ();
661 cygheap
->fdtab
.move_fd (__stdin
, 0);
663 cygheap
->fdtab
.move_fd (__stdout
, 1);
664 cygheap
->user
.groups
.clear_supp ();
666 /* If we're execing we may have "inherited" a list of children forked by the
667 previous process executing under this pid. Reattach them here so that we
668 can wait for them. */
669 if (type
== _CH_EXEC
)
670 reattach_children ();
674 if (child_proc_info
->parent
)
676 /* We no longer need this handle so close it. Need to do
677 this after debug_fixup_after_fork_exec or DEBUGGING handling of
678 handles might get confused. */
679 CloseHandle (child_proc_info
->parent
);
680 child_proc_info
->parent
= NULL
;
683 signal_fixup_after_exec ();
684 fixup_lockf_after_exec (type
== _CH_EXEC
);
687 /* Retrieve and store system directory for later use. Note that the
688 directory is stored with a trailing backslash! */
690 init_windows_system_directory ()
692 if (!windows_system_directory_length
)
694 windows_system_directory_length
=
695 GetSystemDirectoryW (windows_system_directory
, MAX_PATH
);
696 if (windows_system_directory_length
== 0)
697 api_fatal ("can't find windows system directory");
698 windows_system_directory
[windows_system_directory_length
++] = L
'\\';
699 windows_system_directory
[windows_system_directory_length
] = L
'\0';
700 /* We need the Windows dir with NT prefix in path.cc. Note that we
701 don't append a backslash, because we need the dir without backslash
702 for the environment. */
703 wcpcpy (windows_directory_buf
, L
"\\??\\");
704 windows_directory_length
=
705 GetSystemWindowsDirectoryW (windows_directory
, MAX_PATH
- 4);
706 RtlInitCountedUnicodeString (&windows_directory_path
,
707 windows_directory_buf
,
708 (windows_directory_length
+ 4) * sizeof (WCHAR
));
716 GetModuleFileNameW (NULL
, global_progname
, NT_MAX_PATH
);
717 child_proc_info
= get_cygwin_startup_info ();
718 init_windows_system_directory ();
721 SetErrorMode (SEM_FAILCRITICALERRORS
| SEM_NOGPFAULTERRORBOX
);
723 lock_process::init ();
724 user_data
->impure_ptr
= _impure_ptr
;
725 user_data
->impure_ptr_ptr
= &_impure_ptr
;
727 DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
728 GetCurrentProcess (), &hMainThread
,
729 0, false, DUPLICATE_SAME_ACCESS
);
731 NtOpenProcessToken (NtCurrentProcess (), MAXIMUM_ALLOWED
, &hProcToken
);
732 set_cygwin_privileges (hProcToken
);
735 do_global_ctors (&__CTOR_LIST__
, 1);
738 if (!child_proc_info
)
745 cygwin_user_h
= child_proc_info
->user_h
;
746 switch (child_proc_info
->type
)
749 fork_info
->handle_fork ();
753 spawn_info
->handle_spawn ();
758 user_data
->threadinterface
->Init ();
760 _main_tls
= &_my_tls
;
762 /* Initialize signal processing here, early, in the hopes that the creation
763 of a thread early in the process will cause more predictability in memory
764 layout for the main thread. */
765 if (!dynamically_loaded
)
768 /* See comment preceeding myfault_altstack_handler in exception.cc. */
769 AddVectoredContinueHandler (0, myfault_altstack_handler
);
771 debug_printf ("finished dll_crt0_0 initialization");
777 __sinit (_impure_ptr
);
778 /* At this point, _impure_ptr == _GLOBAL_REENT is
779 initialized, but _REENT == _my_tls.local_clib doesn't know about it.
780 It has been copied over from _GLOBAL_REENT in _cygtls::init_thread
781 *before* the initialization took place.
783 As soon as the main thread calls a stdio function, this would be
784 rectified. But if another thread calls a stdio function on
785 stdin/out/err before the main thread does, all the required
786 initialization of stdin/out/err will be done, but _REENT->__cleanup
787 is *still* NULL. This in turn will result in a call to __sinit in the
788 wrong spot. The input or output buffer will be NULLed and nothing is
789 read or written in the first stdio function call in the main thread.
791 To fix this issue we set __cleanup to _cygtls::cleanup_early here. */
792 _REENT_CLEANUP(_REENT
) = _cygtls::cleanup_early
;
795 /* Take over from libc's crt0.o and start the application. Note the
796 various special cases when Cygwin DLL is being runtime loaded (as
797 opposed to being link-time loaded by Cygwin apps) from a non
798 cygwin app via LoadLibrary. */
802 extern void initial_setlocale ();
805 /* Inherit "parent" exec'ed process sigmask */
806 if (spawn_info
&& __in_forkee
!= FORKING
)
807 _my_tls
.sigmask
= spawn_info
->sigmask
;
809 if (dynamically_loaded
)
812 check_sanity_and_sync (user_data
);
814 /* Initialize malloc and then call user_shared_initialize since it relies
815 on a functioning malloc and it's possible that the user's program may
816 have overridden malloc. We only know about that at this stage,
819 user_shared
->initialize ();
823 const int n
= 2 * 1024 * 1024;
826 void *p
= cmalloc (HEAP_STR
, n
);
828 small_printf ("cmalloc returns %p\n", cmalloc (HEAP_STR
, n
));
831 small_printf ("total allocated %y\n", (i
- 1) * n
);
837 ProtectHandle (hMainThread
);
839 cygheap
->cwd
.init ();
841 /* Initialize pthread mainthread when not forked and it is safe to call new,
842 otherwise it is reinitalized in fixup_after_fork */
843 if (__in_forkee
!= FORKING
)
845 pthread::init_mainthread ();
846 _pei386_runtime_relocator (user_data
);
850 strace
.microseconds ();
853 cygbench ("pre-forkee");
854 if (__in_forkee
== FORKING
)
856 /* Make sure to restore the TEB's stack info. If guardsize is -1 the
857 stack has been provided by the application and must not be deallocated
858 automagically when the thread exits.
860 NOTE: Don't do anything that involves the stack until you've completed
862 PTEB teb
= NtCurrentTeb ();
863 teb
->Tib
.StackBase
= (PVOID
) fork_info
->stackbase
;
864 teb
->Tib
.StackLimit
= (PVOID
) fork_info
->stacklimit
;
865 teb
->DeallocationStack
= (fork_info
->guardsize
== (size_t) -1)
867 : (PVOID
) fork_info
->stackaddr
;
869 /* Not resetting _my_tls.incyg here because presumably fork will overwrite
870 it with the value of the forker and all will be good. */
871 longjmp (fork_info
->jmp
, true);
874 main_thread_sinit ();
878 extern void fork_init ();
882 pinfo_init (envp
, envc
);
885 /* Allocate cygheap->fdtab */
888 /* Set internal locale to the environment settings. */
889 initial_setlocale ();
891 uinfo_init (); /* initialize user info */
893 /* Connect to tty. */
894 tty::init_session ();
898 PWCHAR wline
= GetCommandLineW ();
899 size_t size
= sys_wcstombs_no_path (NULL
, 0, wline
) + 1;
900 char *line
= (char *) alloca (size
);
901 sys_wcstombs_no_path (line
, size
, wline
);
903 /* Scan the command line and build argv. Expand wildcards if not
904 called from another cygwin process. */
905 build_argv (line
, __argv
, __argc
,
906 NOTSTATE (myself
, PID_CYGPARENT
) && allow_glob
);
908 /* Convert argv[0] to posix rules if it's currently blatantly
910 if ((strchr (__argv
[0], ':')) || (strchr (__argv
[0], '\\')))
912 char *new_argv0
= (char *) malloc (NT_MAX_PATH
);
913 cygwin_conv_path (CCP_WIN_A_TO_POSIX
| CCP_RELATIVE
, __argv
[0],
914 new_argv0
, NT_MAX_PATH
);
915 __argv
[0] = (char *) realloc (new_argv0
, strlen (new_argv0
) + 1);
919 __argc_safe
= __argc
;
920 if (user_data
->premain
[0])
921 for (unsigned int i
= 0; i
< PREMAIN_LEN
/ 2; i
++)
922 user_data
->premain
[i
] (__argc
, __argv
, user_data
);
924 /* Set up standard fds in file descriptor table. */
925 cygheap
->fdtab
.stdio_init ();
927 /* Set up program_invocation_name and program_invocation_short_name.
928 __progname is an export alias for program_invocation_short_name. */
929 program_invocation_name
= __argv
[0];
930 if (__argv
[0] && (program_invocation_short_name
= strrchr (__argv
[0], '/')))
931 ++program_invocation_short_name
;
933 program_invocation_short_name
= __argv
[0];
934 if (program_invocation_short_name
)
936 char *cp
= strchr (program_invocation_short_name
, '\0') - 4;
937 if (cp
> program_invocation_short_name
&& ascii_strcasematch (cp
, ".exe"))
940 SetThreadName (GetCurrentThreadId (), program_invocation_short_name
);
942 (void) xdr_set_vprintf (&cygxdr_vwarnx
);
943 cygwin_finished_initializing
= true;
944 /* Call init of loaded dlls. */
947 /* Execute any specified "premain" functions */
948 if (user_data
->premain
[PREMAIN_LEN
/ 2])
949 for (unsigned int i
= PREMAIN_LEN
/ 2; i
< PREMAIN_LEN
; i
++)
950 user_data
->premain
[i
] (__argc
, __argv
, user_data
);
954 if (dynamically_loaded
)
956 _setlocale_r (_REENT
, LC_CTYPE
, "C");
960 /* Disable case-insensitive globbing */
961 ignore_case_with_glob
= false;
963 cygbench (__progname
);
966 /* Per POSIX set the default application locale back to "C". */
967 _setlocale_r (_REENT
, LC_CTYPE
, "C");
969 if (!user_data
->main
)
971 /* Handle any signals which may have arrived */
972 _my_tls
.call_signal_handler ();
973 _my_tls
.incyg
--; /* Not in Cygwin anymore */
977 /* Create a copy of Cygwin's version of __argv so that, if the user makes
978 a change to an element of argv[] it does not affect Cygwin's argv.
979 Changing the contents of what argv[n] points to will still affect
980 Cygwin. This is similar (but not exactly like) Linux.
982 We used to allocate newargv on the stack, but all the rest of the
983 argument and environment handling does not depend on the stack,
984 as it does on Linux. In fact, everything is stored by the parent
985 in the cygheap, so the only reason this may fail is if we're out
986 of resources in a big way. If this malloc fails, we could either
987 fail the entire process execution, or we could proceed with the
988 original argv and potentially affect output of /proc/self/cmdline.
989 We opt for the latter here because it's the lesser evil. */
990 char **newargv
= (char **) malloc ((__argc
+ 1) * sizeof (char *));
992 memcpy (newargv
, __argv
, (__argc
+ 1) * sizeof (char *));
995 /* Handle any signals which may have arrived */
996 sig_dispatch_pending (false);
997 _my_tls
.call_signal_handler ();
998 _my_tls
.incyg
--; /* Not in Cygwin anymore */
999 cygwin_exit (user_data
->main (__argc
, newargv
, environ
));
1002 .global _cygwin_exit_return \n\
1003 .global __cygwin_exit_return \n\
1004 _cygwin_exit_return: \n\
1005 __cygwin_exit_return: \n\
1013 /* Starting with Windows 10 rel 1511, the main stack of an application is
1014 not reproducible if a 64 bit process has been started from a 32 bit
1015 process. Given that we have enough virtual address space on 64 bit
1016 anyway, we now always move the main thread stack to the stack area
1017 reserved for pthread stacks. This allows a reproducible stack space
1018 under our own control and avoids collision with the OS. */
1019 if (!dynamically_loaded
)
1021 if (__in_forkee
!= FORKING
)
1023 /* Must be static since it's referenced after the stack and frame
1024 pointer registers have been changed. */
1025 static PVOID allocationbase
;
1026 PVOID stackaddr
= create_new_main_thread_stack (allocationbase
);
1030 /* Set stack pointer to new address. Set frame pointer to
1031 stack pointer and subtract 32 bytes for shadow space. */
1033 movq %[ADDR], %%rsp \n\
1034 movq %%rsp, %%rbp \n\
1036 : : [ADDR
] "r" (stackaddr
));
1038 #error unimplemented for this target
1040 /* We're on the new stack now. Free up space taken by the former
1041 main thread stack and set DeallocationStack correctly. */
1042 VirtualFree (NtCurrentTeb ()->DeallocationStack
, 0, MEM_RELEASE
);
1043 NtCurrentTeb ()->DeallocationStack
= allocationbase
;
1047 fork_info
->alloc_stack ();
1050 fesetenv (FE_DFL_ENV
);
1051 _main_tls
= &_my_tls
;
1052 _main_tls
->call ((DWORD (*) (void *, void *)) dll_crt0_1
, NULL
);
1056 dll_crt0 (per_process
*uptr
)
1058 /* Set the local copy of the pointer into the user space. */
1059 if (__in_forkee
!= FORKING
&& uptr
&& uptr
!= user_data
)
1061 memcpy (user_data
, uptr
, per_process_overwrite
);
1062 *(user_data
->impure_ptr_ptr
) = _GLOBAL_REENT
;
1067 /* This must be called by anyone who uses LoadLibrary to load cygwin1.dll.
1068 You must have __CYGTLS_PADSIZE__ bytes reserved at the bottom of the stack
1069 calling this function, and that storage must not be overwritten until you
1070 unload cygwin1.dll, as it is used for _my_tls. It is best to load
1071 cygwin1.dll before spawning any additional threads in your process.
1073 See winsup/testsuite/cygload for an example of how to use cygwin1.dll
1074 from MSVC and non-cygwin MinGW applications. */
1080 user_data
->magic_biscuit
= sizeof (per_process
);
1081 user_data
->fmode_ptr
= &_fmode
;
1088 /* Ordering is critical here. DLL ctors have already been
1089 run as they were being loaded, so we should stack the
1090 queued call to DLL dtors now. */
1091 atexit (dll_global_dtors
);
1092 do_global_ctors (user_data
->ctors
, false);
1093 /* Now we have run global ctors, register their dtors.
1095 At exit, global dtors will run first, so the app can still
1096 use shared library functions while terminating; then the
1097 DLLs will be destroyed; finally newlib will shut down stdio
1098 and terminate itself. */
1099 atexit (do_global_dtors
);
1100 sig_dispatch_pending (true);
1104 do_exit (int status
)
1106 syscall_printf ("do_exit (%d), exit_state %d", status
, exit_state
);
1108 lock_process
until_exit (true);
1110 if (exit_state
< ES_EVENTS_TERMINATE
)
1111 exit_state
= ES_EVENTS_TERMINATE
;
1113 if (exit_state
< ES_SIGNAL
)
1115 exit_state
= ES_SIGNAL
;
1116 signal (SIGCHLD
, SIG_IGN
);
1117 signal (SIGHUP
, SIG_IGN
);
1118 signal (SIGINT
, SIG_IGN
);
1119 signal (SIGQUIT
, SIG_IGN
);
1122 if (exit_state
< ES_CLOSEALL
)
1124 exit_state
= ES_CLOSEALL
;
1128 UINT n
= (UINT
) status
;
1129 if (exit_state
< ES_THREADTERM
)
1131 exit_state
= ES_THREADTERM
;
1132 cygthread::terminate ();
1135 myself
->stopsig
= 0;
1137 if (exit_state
< ES_HUP_PGRP
)
1139 exit_state
= ES_HUP_PGRP
;
1140 /* Kill orphaned children on group leader exit */
1141 if (myself
->has_pgid_children
&& myself
->pid
== myself
->pgid
)
1144 si
.si_signo
= -SIGHUP
;
1145 si
.si_code
= SI_KERNEL
;
1146 sigproc_printf ("%u == pgrp %u, send SIG{HUP,CONT} to stopped children",
1147 myself
->pid
, myself
->pgid
);
1148 kill_pgrp (myself
->pgid
, si
);
1152 if (exit_state
< ES_HUP_SID
)
1154 exit_state
= ES_HUP_SID
;
1155 /* Kill the foreground process group on session leader exit */
1156 if (getpgrp () > 0 && myself
->pid
== myself
->sid
&& real_tty_attached (myself
))
1158 tty
*tp
= cygwin_shared
->tty
[myself
->ctty
];
1159 sigproc_printf ("%u == sid %u, send SIGHUP to children",
1160 myself
->pid
, myself
->sid
);
1162 /* CGF FIXME: This can't be right. */
1163 if (tp
->getsid () == myself
->sid
)
1164 tp
->kill_pgrp (SIGHUP
);
1172 /* When introducing support for -fuse-cxa-atexit with Cygwin 1.7.32 and
1173 GCC 4.8.3-3, we defined __dso_value as &ImageBase. This supposedly allowed
1174 a reproducible value which could also be easily evaluated in cygwin_atexit.
1175 However, when building C++ applications with -fuse-cxa-atexit, G++ creates
1176 calls to __cxa_atexit using the *address* of __dso_handle as DSO handle.
1178 So what we do here is this: A call to __cxa_atexit from the application
1179 actually calls cygwin__cxa_atexit. From dso_handle (which is either
1180 &__dso_handle, or __dso_handle == ImageBase or NULL) we fetch the dll
1181 structure of the DLL. Then use dll::handle == ImageBase as the actual DSO
1182 handle value in calls to __cxa_atexit and __cxa_finalize.
1183 Thus, __cxa_atexit becomes entirely independent of the incoming value of
1184 dso_handle, as long as it's *some* pointer into the DSO's address space. */
1186 cygwin__cxa_atexit (void (*fn
)(void *), void *obj
, void *dso_handle
)
1188 dll
*d
= dso_handle
? dlls
.find (dso_handle
) : NULL
;
1189 return __cxa_atexit (fn
, obj
, d
? d
->handle
: NULL
);
1192 /* This function is only called for applications built with Cygwin versions
1193 up to API 0.279. Starting with API 0.280 (Cygwin 1.7.33/1.8.6-2), atexit
1194 is a statically linked function inside of libcygwin.a. The reason is that
1195 the old method to fetch the caller return address is unreliable given GCCs
1196 ability to perform tail call elimination. For the details, see the below
1197 comment. The atexit replacement is defined in libcygwin.a to allow reliable
1198 access to the correct DSO handle. */
1200 cygwin_atexit (void (*fn
) (void))
1204 dll
*d
= dlls
.find ((void *) _my_tls
.retaddr ());
1205 /* x86_64 DLLs created with GCC 4.8.3-3 register __gcc_deregister_frame
1206 as atexit function using a call to atexit, rather than __cxa_atexit.
1207 Due to GCC's tail call optimizing, cygwin_atexit doesn't get the correct
1208 return address on the stack. As a result it fails to get the HMODULE of
1209 the caller and thus calls atexit rather than __cxa_atexit. Then, if the
1210 module gets dlclosed, __cxa_finalize (called from dll_list::detach) can't
1211 remove __gcc_deregister_frame from the atexit function chain. So at
1212 process exit, __call_exitprocs calls __gcc_deregister_frame while the
1213 module is already unloaded and the __gcc_deregister_frame function not
1216 This also occurs for other functions.
1218 Workaround: If dlls.find fails, try to find the dll entry of the DLL
1219 containing fn. If that works, proceed by calling __cxa_atexit, otherwise
1222 This *should* be sufficiently safe. Ultimately, new applications will
1223 use the statically linked atexit function though, as outlined above. */
1225 d
= dlls
.find ((void *) fn
);
1226 res
= d
? __cxa_atexit ((void (*) (void *)) fn
, NULL
, d
->handle
) : atexit (fn
);
1233 exit_state
= ES_EXIT_STARTING
;
1240 do_exit (((DWORD
) n
& 0xff) << 8);
1243 extern "C" void cygwin_stackdump ();
1246 vapi_fatal (const char *fmt
, va_list ap
)
1249 int n
= __small_sprintf (buf
, "%P: *** fatal error %s- ",
1250 (__in_forkee
== FORKING
)
1251 ? "in forked process " : "");
1252 __small_vsprintf (buf
+ n
, fmt
, ap
);
1254 strace
.prntf (_STRACE_SYSTEM
, NULL
, "%s", buf
);
1256 myself
.exit (__api_fatal_exit_val
);
1260 api_fatal (const char *fmt
, ...)
1265 vapi_fatal (fmt
, ap
);
1269 multiple_cygwin_problem (const char *what
, uintptr_t magic_version
, uintptr_t version
)
1271 if (_cygwin_testing
&& (strstr (what
, "proc")))
1273 child_proc_info
->type
= _CH_WHOOPS
;
1277 if (GetEnvironmentVariableA ("CYGWIN_MISMATCH_OK", NULL
, 0))
1280 if (CYGWIN_VERSION_MAGIC_VERSION (magic_version
) == version
)
1281 system_printf ("%s magic number mismatch detected - %p/%ly", what
, magic_version
, version
);
1283 api_fatal ("%s mismatch detected - %ly/%ly.\n\
1284 This problem is probably due to using incompatible versions of the cygwin DLL.\n\
1285 Search for cygwin1.dll using the Windows Start->Find/Search facility\n\
1286 and delete all but the most recent version. The most recent version *should*\n\
1287 reside in x:\\cygwin\\bin, where 'x' is the drive on which you have\n\
1288 installed the cygwin distribution. Rebooting is also suggested if you\n\
1289 are unable to find another cygwin DLL.",
1290 what
, magic_version
, version
);
1295 cygbench (const char *s
)
1297 if (GetEnvironmentVariableA ("CYGWIN_BENCH", NULL
, 0))
1298 small_printf ("%05u ***** %s : %10d\n", GetCurrentProcessId (), s
, strace
.microseconds ());