Cygwin: strptime: add release note
[newlib-cygwin.git] / winsup / cygwin / dcrt0.cc
bloba40129c222328568a909a22ff5fe26def12a0746
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
7 details. */
9 #include "winsup.h"
10 #include "create_posix_thread.h"
11 #include <unistd.h>
12 #include <stdlib.h>
13 #include "glob.h"
14 #include <ctype.h>
15 #include <locale.h>
16 #include <sys/param.h>
17 #include "environ.h"
18 #include "sigproc.h"
19 #include "pinfo.h"
20 #include "cygerrno.h"
21 #define NEED_VFORK
22 #include "perprocess.h"
23 #include "path.h"
24 #include "fhandler.h"
25 #include "dtable.h"
26 #include "cygheap.h"
27 #include "child_info_magic.h"
28 #include "cygtls.h"
29 #include "shared_info.h"
30 #include "cygwin_version.h"
31 #include "dll_init.h"
32 #include "cygmalloc.h"
33 #include "heap.h"
34 #include "tls_pbuf.h"
35 #include "exception.h"
36 #include "cygxdr.h"
37 #include <fenv.h>
38 #include "ntdll.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;
52 static void
53 do_global_dtors ()
55 void (**pfunc) () = user_data->dtors;
56 if (pfunc)
58 user_data->dtors = NULL;
59 while (*++pfunc)
60 (*pfunc) ();
64 static void
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;
75 while (*++pfunc)
77 while (--pfunc > in_pfunc)
78 (*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.
87 static bool
88 insert_file (char *name, char *&cmd)
90 HANDLE f;
91 DWORD size;
92 tmp_pathbuf tp;
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);
107 return false;
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)
116 CloseHandle (f);
117 debug_printf ("couldn't get file size for '%s', %E", name);
118 return false;
121 int new_size = strlen (cmd) + size + 2;
122 char *tmp = (char *) malloc (new_size);
123 if (!tmp)
125 CloseHandle (f);
126 debug_printf ("malloc failed, %E");
127 return false;
130 /* realloc passed as it should */
131 DWORD rf_read;
132 BOOL rf_result;
133 rf_result = ReadFile (f, tmp, size, &rf_read, NULL);
134 CloseHandle (f);
135 if (!rf_result || (rf_read != size))
137 free (tmp);
138 debug_printf ("ReadFile failed, %E");
139 return false;
142 tmp[size++] = ' ';
143 strcpy (tmp + size, cmd);
144 cmd = tmp;
145 return true;
148 static inline int
149 isquote (char c)
151 char ch = c;
152 return ch == '"' || ch == '\'';
155 /* Step over a run of characters delimited by quotes */
156 static /*__inline*/ char *
157 quoted (char *cmd, int winshell)
159 char *p;
160 char quote = *cmd;
162 if (!winshell)
164 char *p;
165 strcpy (cmd, cmd + 1);
166 if (*(p = strchrnul (cmd, quote)))
167 strcpy (p, p + 1);
168 return p;
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
178 break;
180 else if (*p == '\\')
181 cmd = ++p;
182 else if (quote == '"' && p[1] == '"')
184 *p = '\\';
185 cmd = ++p; // a quoted quote
187 else
189 cmd = p + 1; // point to after end
190 break;
192 return cmd;
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) \
201 || ((s)[0] == '\\' \
202 && (s)[1] == '\\' \
203 && isalpha ((s)[2]) \
204 && strchr ((s) + 3, '\\')))
206 static int
207 globify (char *word, char **&argv, int &argc, int &argvlen)
209 if (*word != '~' && strpbrk (word, "?*[\"\'(){}") == NULL)
210 return 0;
212 int n = 0;
213 char *p, *s;
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, "'\""))
222 n = strlen (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++)
228 if (!isquote (*s))
230 if (dos_spec && *s == '\\')
231 *p++ = '\\';
232 *p = *s;
234 else
236 char quote = *s;
237 while (*++s && *s != quote)
239 if (dos_spec || *s != '\\')
240 /* nothing */;
241 else if (s[1] == quote || s[1] == '\\')
242 s++;
243 *p++ = '\\';
244 size_t cnt = isascii (*s) ? 1 : mbtowc (NULL, s, MB_CUR_MAX);
245 if (cnt <= 1 || cnt == (size_t)-1)
246 *p++ = *s;
247 else
249 --s;
250 while (cnt-- > 0)
251 *p++ = *++s;
254 if (*s == quote)
255 p--;
256 if (*s == '\0')
257 break;
260 *p = '\0';
262 glob_t gl;
263 gl.gl_offs = 0;
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)
267 return 0;
269 /* Allocate enough space in argv for the matched filenames. */
270 n = argc;
271 if ((argc += gl.gl_pathc) > argvlen)
273 argvlen = argc + 10;
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;
280 while (*gv)
282 debug_printf ("argv[%d] = '%s'", n++, *gv);
283 *av++ = *gv++;
286 /* Clean up after glob. */
287 free (gl.gl_pathv);
288 return 1;
291 /* Build argv, argc from string passed from Windows. */
293 static void
294 build_argv (char *cmd, char **&argv, int &argc, int winshell)
296 int argvlen = 0;
297 int nesting = 0; // monitor "nesting" from insert_file
299 argc = 0;
300 argvlen = 0;
301 argv = NULL;
303 /* Scan command line until there is nothing left. */
304 while (*cmd)
306 /* Ignore spaces */
307 if (issep (*cmd))
309 cmd++;
310 continue;
313 /* Found the beginning of an argument. */
314 char *word = cmd;
315 char *sawquote = NULL;
316 while (*cmd)
318 if (*cmd != '"' && (!winshell || *cmd != '\''))
319 cmd++; // Skip over this character
320 else
321 /* Skip over characters until the closing quote */
323 sawquote = cmd;
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
331 break;
333 if (*cmd)
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 */
347 if (argc >= argvlen)
349 argvlen = argc + 10;
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);
357 argv[argc++] = word;
361 if (argv)
362 argv[argc] = NULL;
364 debug_printf ("argc %d", argc);
367 /* sanity and sync check */
368 void
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. */
391 void
392 child_info_fork::alloc_stack ()
394 PTEB teb = NtCurrentTeb ();
395 if (teb->Tib.StackBase != stackbase)
397 void *stack_ptr;
398 size_t stacksize;
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)
403 return;
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,
411 teb->Tib.StackBase);
413 /* Commit the area commited in parent. */
414 stacksize = (PBYTE) stackbase - (PBYTE) stacklimit;
415 stack_ptr = VirtualAlloc (stacklimit, stacksize, MEM_COMMIT,
416 PAGE_READWRITE);
417 if (!stack_ptr)
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",
430 stack_ptr);
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);
440 else
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",
456 guardpage);
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;
467 extern "C" void
468 break_here ()
470 static int NO_COPY sent_break;
471 if (!sent_break++)
472 DebugBreak ();
473 debug_printf ("break here");
476 static void
477 initial_env ()
479 if (GetEnvironmentVariableA ("CYGWIN_TESTING", NULL, 0))
480 _cygwin_testing = 1;
482 #ifdef DEBUGGING
483 char buf[PATH_MAX];
484 if (GetEnvironmentVariableA ("CYGWIN_DEBUG", buf, sizeof (buf) - 1))
486 char buf1[PATH_MAX];
487 GetModuleFileName (NULL, buf1, PATH_MAX);
488 char *p = strpbrk (buf, ":=");
489 if (!p)
490 p = (char *) "gdb.exe -nw";
491 else
492 *p++ = '\0';
493 if (strcasestr (buf1, buf))
495 extern PWCHAR debugger_command;
497 debugger_command = (PWCHAR) HeapAlloc (GetProcessHeap (), 0,
498 (2 * NT_MAX_PATH + 20)
499 * sizeof (WCHAR));
500 if (!debugger_command)
501 return;
502 error_start_init (p);
503 jit_debug = true;
504 try_to_debug ();
505 console_printf ("*** Sending Break. gdb may issue spurious SIGTRAP message.\n");
506 break_here ();
509 #endif
512 child_info *
513 get_cygwin_startup_info ()
515 STARTUPINFO si;
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);
524 res = NULL;
526 else
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;
532 switch (res->type)
534 case _CH_FORK:
535 __in_forkee = FORKING;
536 should_be_cb = sizeof (child_info_fork);
537 fallthrough;
538 case _CH_SPAWN:
539 case _CH_EXEC:
540 if (!should_be_cb)
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 ())
550 yield ();
551 strace.activate (res->type == _CH_FORK);
553 break;
554 default:
555 system_printf ("unknown exec type %u", res->type);
556 fallthrough;
557 case _CH_WHOOPS:
558 res = NULL;
559 break;
563 return res;
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__
571 void
572 child_info_fork::handle_fork ()
574 cygheap_fixup_in_child (false);
575 memory_init ();
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,
584 NULL);
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
588 parent. */
589 if (my_wr_proc_pipe)
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
594 safe. */
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,
607 NULL);
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 ();
619 bool
620 child_info_spawn::get_parent_handle ()
622 parent = OpenProcess (PROCESS_VM_READ, FALSE, parent_winpid);
623 return !!parent;
626 void
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);
634 memory_init ();
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
649 safe. */
650 my_wr_proc_pipe = wr_proc_pipe;
651 rd_proc_pipe = wr_proc_pipe = NULL;
653 myself.thisproc (h);
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 ();
660 if (__stdin >= 0)
661 cygheap->fdtab.move_fd (__stdin, 0);
662 if (__stdout >= 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 ();
672 ready (true);
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! */
689 static void
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));
712 void
713 dll_crt0_0 ()
715 wincap.init ();
716 GetModuleFileNameW (NULL, global_progname, NT_MAX_PATH);
717 child_proc_info = get_cygwin_startup_info ();
718 init_windows_system_directory ();
719 initial_env ();
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);
734 device::init ();
735 do_global_ctors (&__CTOR_LIST__, 1);
736 cygthread::init ();
738 if (!child_proc_info)
740 setup_cygheap ();
741 memory_init ();
743 else
745 cygwin_user_h = child_proc_info->user_h;
746 switch (child_proc_info->type)
748 case _CH_FORK:
749 fork_info->handle_fork ();
750 break;
751 case _CH_SPAWN:
752 case _CH_EXEC:
753 spawn_info->handle_spawn ();
754 break;
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)
766 sigproc_init ();
768 /* See comment preceeding myfault_altstack_handler in exception.cc. */
769 AddVectoredContinueHandler (0, myfault_altstack_handler);
771 debug_printf ("finished dll_crt0_0 initialization");
774 static inline void
775 main_thread_sinit ()
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. */
799 void
800 dll_crt0_1 (void *)
802 extern void initial_setlocale ();
804 _my_tls.incyg++;
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)
810 sigproc_init ();
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,
817 unfortunately. */
818 malloc_init ();
819 user_shared->initialize ();
821 #ifdef CYGHEAP_DEBUG
822 int i = 0;
823 const int n = 2 * 1024 * 1024;
824 while (i--)
826 void *p = cmalloc (HEAP_STR, n);
827 if (p)
828 small_printf ("cmalloc returns %p\n", cmalloc (HEAP_STR, n));
829 else
831 small_printf ("total allocated %y\n", (i - 1) * n);
832 break;
835 #endif
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);
849 #ifdef DEBUGGING
850 strace.microseconds ();
851 #endif
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
861 this step. */
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)
866 ? NULL
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 ();
876 #ifdef DEBUGGING
878 extern void fork_init ();
879 fork_init ();
881 #endif
882 pinfo_init (envp, envc);
883 strace.dll_info ();
885 /* Allocate cygheap->fdtab */
886 dtable_init ();
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 ();
896 if (!__argc)
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
909 win32 style. */
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;
932 else
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"))
938 *cp = '\0';
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. */
945 dlls.init ();
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);
952 set_errno (0);
954 if (dynamically_loaded)
956 _setlocale_r (_REENT, LC_CTYPE, "C");
957 return;
960 /* Disable case-insensitive globbing */
961 ignore_case_with_glob = false;
963 cygbench (__progname);
965 ld_preload ();
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 */
975 else
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 *));
991 if (newargv)
992 memcpy (newargv, __argv, (__argc + 1) * sizeof (char *));
993 else
994 newargv = __argv;
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));
1001 __asm__ (" \n\
1002 .global _cygwin_exit_return \n\
1003 .global __cygwin_exit_return \n\
1004 _cygwin_exit_return: \n\
1005 __cygwin_exit_return: \n\
1006 nop \n\
1010 extern "C" void
1011 _dll_crt0 ()
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);
1027 if (stackaddr)
1029 #ifdef __x86_64__
1030 /* Set stack pointer to new address. Set frame pointer to
1031 stack pointer and subtract 32 bytes for shadow space. */
1032 __asm__ ("\n\
1033 movq %[ADDR], %%rsp \n\
1034 movq %%rsp, %%rbp \n\
1035 subq $32,%%rsp \n"
1036 : : [ADDR] "r" (stackaddr));
1037 #else
1038 #error unimplemented for this target
1039 #endif
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;
1046 else
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);
1055 void
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;
1064 _dll_crt0 ();
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. */
1075 extern "C" void
1076 cygwin_dll_init ()
1078 static int _fmode;
1080 user_data->magic_biscuit = sizeof (per_process);
1081 user_data->fmode_ptr = &_fmode;
1082 _dll_crt0 ();
1085 extern "C" void
1086 __main (void)
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);
1103 void
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;
1125 close_all_files ();
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)
1143 siginfo_t si = {0};
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);
1169 myself.exit (n);
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. */
1185 extern "C" int
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. */
1199 extern "C" int
1200 cygwin_atexit (void (*fn) (void))
1202 int res;
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
1214 available ==> SEGV.
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
1220 call atexit.
1222 This *should* be sufficiently safe. Ultimately, new applications will
1223 use the statically linked atexit function though, as outlined above. */
1224 if (!d)
1225 d = dlls.find ((void *) fn);
1226 res = d ? __cxa_atexit ((void (*) (void *)) fn, NULL, d->handle) : atexit (fn);
1227 return res;
1230 extern "C" void
1231 cygwin_exit (int n)
1233 exit_state = ES_EXIT_STARTING;
1234 exit (n);
1237 extern "C" void
1238 _exit (int n)
1240 do_exit (((DWORD) n & 0xff) << 8);
1243 extern "C" void cygwin_stackdump ();
1245 extern "C" void
1246 vapi_fatal (const char *fmt, va_list ap)
1248 char buf[4096];
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);
1253 va_end (ap);
1254 strace.prntf (_STRACE_SYSTEM, NULL, "%s", buf);
1255 api_fatal_debug();
1256 myself.exit (__api_fatal_exit_val);
1259 extern "C" void
1260 api_fatal (const char *fmt, ...)
1262 va_list ap;
1264 va_start (ap, fmt);
1265 vapi_fatal (fmt, ap);
1268 void
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;
1274 return;
1277 if (GetEnvironmentVariableA ("CYGWIN_MISMATCH_OK", NULL, 0))
1278 return;
1280 if (CYGWIN_VERSION_MAGIC_VERSION (magic_version) == version)
1281 system_printf ("%s magic number mismatch detected - %p/%ly", what, magic_version, version);
1282 else
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);
1293 #ifdef DEBUGGING
1294 void
1295 cygbench (const char *s)
1297 if (GetEnvironmentVariableA ("CYGWIN_BENCH", NULL, 0))
1298 small_printf ("%05u ***** %s : %10d\n", GetCurrentProcessId (), s, strace.microseconds ());
1300 #endif