features.h: support POSIX.1-2024
[newlib-cygwin.git] / winsup / cygwin / dcrt0.cc
blobf4c09befd62c2af5e84842d219b55a087730e6be
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 mbstate_t mbs = { 0 };
240 if (dos_spec || *s != '\\')
241 /* nothing */;
242 else if (s[1] == quote || s[1] == '\\')
243 s++;
244 *p++ = '\\';
245 size_t cnt = isascii (*s) ? 1 : mbrtowi (NULL, s, MB_CUR_MAX, &mbs);
246 if (cnt <= 1 || cnt == (size_t)-1)
247 *p++ = *s;
248 else
250 --s;
251 while (cnt-- > 0)
252 *p++ = *++s;
255 if (*s == quote)
256 p--;
257 if (*s == '\0')
258 break;
261 *p = '\0';
263 glob_t gl;
264 gl.gl_offs = 0;
266 /* Attempt to match the argument. Return just word (minus quoting) if no match. */
267 if (glob (pattern, GLOB_TILDE | GLOB_NOCHECK | GLOB_BRACE | GLOB_QUOTE, NULL, &gl) || !gl.gl_pathc)
268 return 0;
270 /* Allocate enough space in argv for the matched filenames. */
271 n = argc;
272 if ((argc += gl.gl_pathc) > argvlen)
274 argvlen = argc + 10;
275 argv = (char **) realloc (argv, (1 + argvlen) * sizeof (argv[0]));
278 /* Copy the matched filenames to argv. */
279 char **gv = gl.gl_pathv;
280 char **av = argv + n;
281 while (*gv)
283 debug_printf ("argv[%d] = '%s'", n++, *gv);
284 *av++ = *gv++;
287 /* Clean up after glob. */
288 free (gl.gl_pathv);
289 return 1;
292 /* Build argv, argc from string passed from Windows. */
294 static void
295 build_argv (char *cmd, char **&argv, int &argc, int winshell)
297 int argvlen = 0;
298 int nesting = 0; // monitor "nesting" from insert_file
300 argc = 0;
301 argvlen = 0;
302 argv = NULL;
304 /* Scan command line until there is nothing left. */
305 while (*cmd)
307 /* Ignore spaces */
308 if (issep (*cmd))
310 cmd++;
311 continue;
314 /* Found the beginning of an argument. */
315 char *word = cmd;
316 char *sawquote = NULL;
317 while (*cmd)
319 if (*cmd != '"' && (!winshell || *cmd != '\''))
320 cmd++; // Skip over this character
321 else
322 /* Skip over characters until the closing quote */
324 sawquote = cmd;
325 /* Handle quoting. Only strip off quotes if the parent is
326 a Cygwin process, or if the word starts with a '@'.
327 In this case, the insert_file function needs an unquoted
328 DOS filename and globbing isn't performed anyway. */
329 cmd = quoted (cmd, winshell && argc > 0 && *word != '@');
331 if (issep (*cmd)) // End of argument if space
332 break;
334 if (*cmd)
335 *cmd++ = '\0'; // Terminate `word'
337 /* Possibly look for @file construction assuming that this isn't
338 the very first argument and the @ wasn't quoted */
339 if (argc && sawquote != word && *word == '@')
341 if (++nesting > MAX_AT_FILE_LEVEL)
342 api_fatal ("Too many levels of nesting for %s", word);
343 if (insert_file (word, cmd))
344 continue; // There's new stuff in cmd now
347 /* See if we need to allocate more space for argv */
348 if (argc >= argvlen)
350 argvlen = argc + 10;
351 argv = (char **) realloc (argv, (1 + argvlen) * sizeof (argv[0]));
354 /* Add word to argv file after (optional) wildcard expansion. */
355 if (!winshell || !argc || !globify (word, argv, argc, argvlen))
357 debug_printf ("argv[%d] = '%s'", argc, word);
358 argv[argc++] = word;
362 if (argv)
363 argv[argc] = NULL;
365 debug_printf ("argc %d", argc);
368 /* sanity and sync check */
369 void
370 check_sanity_and_sync (per_process *p)
372 /* Sanity check to make sure developers didn't change the per_process */
373 /* struct without updating SIZEOF_PER_PROCESS [it makes them think twice */
374 /* about changing it]. */
375 if (sizeof (per_process) != SIZEOF_PER_PROCESS)
376 api_fatal ("per_process sanity check failed");
378 /* magic_biscuit must be SIZEOF_PER_PROCESS. */
379 if (p->magic_biscuit != SIZEOF_PER_PROCESS)
380 api_fatal ("Incompatible cygwin .dll -- incompatible per_process info %u != %u",
381 p->magic_biscuit, SIZEOF_PER_PROCESS);
383 /* Complain if incompatible API changes made */
384 if (p->api_major > cygwin_version.api_major)
385 api_fatal ("cygwin DLL and APP are out of sync -- API version mismatch %u > %u",
386 p->api_major, cygwin_version.api_major);
389 child_info NO_COPY *child_proc_info;
391 /* Extend the stack prior to fork longjmp. */
392 void
393 child_info_fork::alloc_stack ()
395 PTEB teb = NtCurrentTeb ();
396 if (teb->Tib.StackBase != stackbase)
398 void *stack_ptr;
399 size_t stacksize;
401 /* If guardsize is -1, we have been started from a pthread with an
402 application-provided stack, and the stack has just to be used as is. */
403 if (guardsize == (size_t) -1)
404 return;
405 /* Reserve entire stack. */
406 stacksize = (PBYTE) stackbase - (PBYTE) stackaddr;
407 if (!VirtualAlloc (stackaddr, stacksize, MEM_RESERVE, PAGE_NOACCESS))
409 api_fatal ("fork: can't reserve memory for parent stack "
410 "%p - %p, (child has %p - %p), %E",
411 stackaddr, stackbase, teb->DeallocationStack,
412 teb->Tib.StackBase);
414 /* Commit the area commited in parent. */
415 stacksize = (PBYTE) stackbase - (PBYTE) stacklimit;
416 stack_ptr = VirtualAlloc (stacklimit, stacksize, MEM_COMMIT,
417 PAGE_READWRITE);
418 if (!stack_ptr)
419 api_fatal ("can't commit memory for stack %p(%ly), %E",
420 stacklimit, stacksize);
421 /* Set up guardpages. */
422 ULONG real_guardsize = guardsize
423 ? roundup2 (guardsize, wincap.page_size ())
424 : wincap.def_guard_page_size ();
425 if (stack_ptr > stackaddr)
427 stack_ptr = (void *) ((PBYTE) stack_ptr - real_guardsize);
428 if (!VirtualAlloc (stack_ptr, real_guardsize, MEM_COMMIT,
429 PAGE_READWRITE | PAGE_GUARD))
430 api_fatal ("fork: couldn't allocate new stack guard page %p, %E",
431 stack_ptr);
433 /* Set thread stack guarantee matching the guardsize.
434 Note that the guardsize is one page bigger than the guarantee. */
435 if (real_guardsize > wincap.def_guard_page_size ())
437 real_guardsize -= wincap.page_size ();
438 SetThreadStackGuarantee (&real_guardsize);
441 else
443 /* Fork has been called from main thread. Simply commit the region
444 of the stack commited in the parent but not yet commited in the
445 child and create new guardpages. */
446 if (NtCurrentTeb ()->Tib.StackLimit > stacklimit)
448 SIZE_T commitsize = (PBYTE) NtCurrentTeb ()->Tib.StackLimit
449 - (PBYTE) stacklimit;
450 if (!VirtualAlloc (stacklimit, commitsize, MEM_COMMIT, PAGE_READWRITE))
451 api_fatal ("can't commit child memory for stack %p(%ly), %E",
452 stacklimit, commitsize);
453 PVOID guardpage = (PBYTE) stacklimit - wincap.def_guard_page_size ();
454 if (!VirtualAlloc (guardpage, wincap.def_guard_page_size (),
455 MEM_COMMIT, PAGE_READWRITE | PAGE_GUARD))
456 api_fatal ("fork: couldn't allocate new stack guard page %p, %E",
457 guardpage);
458 NtCurrentTeb ()->Tib.StackLimit = stacklimit;
460 /* This only affects forked children of a process started from a native
461 64 bit process, but it doesn't hurt to do it unconditionally. Fix
462 StackBase in the child to be the same as in the parent, so that the
463 computation of _my_tls is correct. */
464 teb->Tib.StackBase = (PVOID) stackbase;
468 extern "C" void
469 break_here ()
471 static int NO_COPY sent_break;
472 if (!sent_break++)
473 DebugBreak ();
474 debug_printf ("break here");
477 static void
478 initial_env ()
480 if (GetEnvironmentVariableA ("CYGWIN_TESTING", NULL, 0))
481 _cygwin_testing = 1;
483 #ifdef DEBUGGING
484 char buf[PATH_MAX];
485 if (GetEnvironmentVariableA ("CYGWIN_DEBUG", buf, sizeof (buf) - 1))
487 char buf1[PATH_MAX];
488 GetModuleFileName (NULL, buf1, PATH_MAX);
489 char *p = strpbrk (buf, ":=");
490 if (!p)
491 p = (char *) "gdb.exe -nw";
492 else
493 *p++ = '\0';
494 if (strcasestr (buf1, buf))
496 extern PWCHAR debugger_command;
498 debugger_command = (PWCHAR) HeapAlloc (GetProcessHeap (), 0,
499 (2 * NT_MAX_PATH + 20)
500 * sizeof (WCHAR));
501 if (!debugger_command)
502 return;
503 error_start_init (p);
504 jit_debug = true;
505 try_to_debug ();
506 console_printf ("*** Sending Break. gdb may issue spurious SIGTRAP message.\n");
507 break_here ();
510 #endif
513 child_info *
514 get_cygwin_startup_info ()
516 STARTUPINFO si;
518 GetStartupInfo (&si);
519 child_info *res = (child_info *) si.lpReserved2;
521 if (si.cbReserved2 < EXEC_MAGIC_SIZE || !res
522 || res->intro != PROC_MAGIC_GENERIC || res->magic != CHILD_INFO_MAGIC)
524 strace.activate (false);
525 res = NULL;
527 else
529 if ((res->intro & OPROC_MAGIC_MASK) == OPROC_MAGIC_GENERIC)
530 multiple_cygwin_problem ("proc intro", res->intro, 0);
532 unsigned should_be_cb = 0;
533 switch (res->type)
535 case _CH_FORK:
536 __in_forkee = FORKING;
537 should_be_cb = sizeof (child_info_fork);
538 fallthrough;
539 case _CH_SPAWN:
540 case _CH_EXEC:
541 if (!should_be_cb)
542 should_be_cb = sizeof (child_info_spawn);
543 if (should_be_cb != res->cb)
544 multiple_cygwin_problem ("proc size", res->cb, should_be_cb);
545 else if (sizeof (fhandler_union) != res->fhandler_union_cb)
546 multiple_cygwin_problem ("fhandler size", res->fhandler_union_cb,
547 sizeof (fhandler_union));
548 if (res->isstraced ())
550 while (!being_debugged ())
551 yield ();
552 strace.activate (res->type == _CH_FORK);
554 break;
555 default:
556 system_printf ("unknown exec type %u", res->type);
557 fallthrough;
558 case _CH_WHOOPS:
559 res = NULL;
560 break;
564 return res;
567 #define dll_data_start &__data_start__
568 #define dll_data_end &__data_end__
569 #define dll_bss_start &__bss_start__
570 #define dll_bss_end &__bss_end__
572 void
573 child_info_fork::handle_fork ()
575 cygheap_fixup_in_child (false);
576 memory_init ();
577 myself.thisproc (NULL);
578 myself->uid = cygheap->user.real_uid;
579 myself->gid = cygheap->user.real_gid;
581 child_copy (parent, false, silentfail (),
582 "dll data", dll_data_start, dll_data_end,
583 "dll bss", dll_bss_start, dll_bss_end,
584 "user heap", cygheap->user_heap.base, cygheap->user_heap.ptr,
585 NULL);
587 /* If my_wr_proc_pipe != NULL then it's a leftover handle from a previously
588 forked process. Close it now or suffer confusion with the parent of our
589 parent. */
590 if (my_wr_proc_pipe)
591 ForceCloseHandle1 (my_wr_proc_pipe, wr_proc_pipe);
593 /* Setup our write end of the process pipe. Clear the one in the structure.
594 The destructor should never be called for this but, it can't hurt to be
595 safe. */
596 my_wr_proc_pipe = wr_proc_pipe;
597 rd_proc_pipe = wr_proc_pipe = NULL;
598 /* Do the relocations here. These will actually likely be overwritten by the
599 below child_copy but we do them here in case there is a read-only section
600 which does not get copied by fork. */
601 _pei386_runtime_relocator (user_data);
603 /* step 2 now that the dll has its heap filled in, we can fill in the
604 user's data and bss since user_data is now filled out. */
605 child_copy (parent, false, silentfail (),
606 "data", user_data->data_start, user_data->data_end,
607 "bss", user_data->bss_start, user_data->bss_end,
608 NULL);
610 if (fixup_mmaps_after_fork (parent))
611 api_fatal ("recreate_mmaps_after_fork_failed");
613 /* We need to occupy the address space for dynamically loaded dlls
614 before we allocate any dynamic object, or we may end up with
615 error "address space needed by <dll> is already occupied"
616 for no good reason (seen with some relocated dll). */
617 dlls.reserve_space ();
620 bool
621 child_info_spawn::get_parent_handle ()
623 parent = OpenProcess (PROCESS_VM_READ, FALSE, parent_winpid);
624 return !!parent;
627 void
628 child_info_spawn::handle_spawn ()
630 extern void fixup_lockf_after_exec (bool);
631 HANDLE h = INVALID_HANDLE_VALUE;
632 if (!dynamically_loaded || get_parent_handle ())
634 cygheap_fixup_in_child (true);
635 memory_init ();
638 cygheap->pid = cygpid;
640 /* Spawned process sets h to INVALID_HANDLE_VALUE to notify
641 pinfo::thisproc not to create another pid. */
642 if (!moreinfo->myself_pinfo ||
643 !DuplicateHandle (GetCurrentProcess (), moreinfo->myself_pinfo,
644 GetCurrentProcess (), &h, 0,
645 FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE))
646 h = (type == _CH_SPAWN) ? INVALID_HANDLE_VALUE : NULL;
648 /* Setup our write end of the process pipe. Clear the one in the structure.
649 The destructor should never be called for this but, it can't hurt to be
650 safe. */
651 my_wr_proc_pipe = wr_proc_pipe;
652 rd_proc_pipe = wr_proc_pipe = NULL;
654 myself.thisproc (h);
655 __argc = moreinfo->argc;
656 __argv = moreinfo->argv;
657 envp = moreinfo->envp;
658 envc = moreinfo->envc;
659 if (!dynamically_loaded)
660 cygheap->fdtab.fixup_after_exec ();
661 if (__stdin >= 0)
662 cygheap->fdtab.move_fd (__stdin, 0);
663 if (__stdout >= 0)
664 cygheap->fdtab.move_fd (__stdout, 1);
665 cygheap->user.groups.clear_supp ();
667 /* If we're execing we may have "inherited" a list of children forked by the
668 previous process executing under this pid. Reattach them here so that we
669 can wait for them. */
670 if (type == _CH_EXEC)
671 reattach_children ();
673 ready (true);
675 if (child_proc_info->parent)
677 /* We no longer need this handle so close it. Need to do
678 this after debug_fixup_after_fork_exec or DEBUGGING handling of
679 handles might get confused. */
680 CloseHandle (child_proc_info->parent);
681 child_proc_info->parent = NULL;
684 signal_fixup_after_exec ();
685 fixup_lockf_after_exec (type == _CH_EXEC);
688 /* Retrieve and store system directory for later use. Note that the
689 directory is stored with a trailing backslash! */
690 static void
691 init_windows_system_directory ()
693 if (!windows_system_directory_length)
695 windows_system_directory_length =
696 GetSystemDirectoryW (windows_system_directory, MAX_PATH);
697 if (windows_system_directory_length == 0)
698 api_fatal ("can't find windows system directory");
699 windows_system_directory[windows_system_directory_length++] = L'\\';
700 windows_system_directory[windows_system_directory_length] = L'\0';
701 /* We need the Windows dir with NT prefix in path.cc. Note that we
702 don't append a backslash, because we need the dir without backslash
703 for the environment. */
704 wcpcpy (windows_directory_buf, L"\\??\\");
705 windows_directory_length =
706 GetSystemWindowsDirectoryW (windows_directory, MAX_PATH - 4);
707 RtlInitCountedUnicodeString (&windows_directory_path,
708 windows_directory_buf,
709 (windows_directory_length + 4) * sizeof (WCHAR));
713 void
714 dll_crt0_0 ()
716 wincap.init ();
717 GetModuleFileNameW (NULL, global_progname, NT_MAX_PATH);
718 child_proc_info = get_cygwin_startup_info ();
719 init_windows_system_directory ();
720 initial_env ();
722 SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
724 lock_process::init ();
725 user_data->impure_ptr = _impure_ptr;
726 user_data->impure_ptr_ptr = &_impure_ptr;
728 DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
729 GetCurrentProcess (), &hMainThread,
730 0, false, DUPLICATE_SAME_ACCESS);
732 NtOpenProcessToken (NtCurrentProcess (), MAXIMUM_ALLOWED, &hProcToken);
733 set_cygwin_privileges (hProcToken);
735 device::init ();
736 do_global_ctors (&__CTOR_LIST__, 1);
737 cygthread::init ();
739 if (!child_proc_info)
741 setup_cygheap ();
742 memory_init ();
744 else
746 cygwin_user_h = child_proc_info->user_h;
747 switch (child_proc_info->type)
749 case _CH_FORK:
750 fork_info->handle_fork ();
751 break;
752 case _CH_SPAWN:
753 case _CH_EXEC:
754 spawn_info->handle_spawn ();
755 break;
759 user_data->threadinterface->Init ();
761 _main_tls = &_my_tls;
763 /* Initialize signal processing here, early, in the hopes that the creation
764 of a thread early in the process will cause more predictability in memory
765 layout for the main thread. */
766 if (!dynamically_loaded)
767 sigproc_init ();
769 /* See comment preceeding myfault_altstack_handler in exception.cc. */
770 AddVectoredContinueHandler (0, myfault_altstack_handler);
772 debug_printf ("finished dll_crt0_0 initialization");
775 static inline void
776 main_thread_sinit ()
778 __sinit (_impure_ptr);
779 /* At this point, _impure_ptr == _GLOBAL_REENT is
780 initialized, but _REENT == _my_tls.local_clib doesn't know about it.
781 It has been copied over from _GLOBAL_REENT in _cygtls::init_thread
782 *before* the initialization took place.
784 As soon as the main thread calls a stdio function, this would be
785 rectified. But if another thread calls a stdio function on
786 stdin/out/err before the main thread does, all the required
787 initialization of stdin/out/err will be done, but _REENT->__cleanup
788 is *still* NULL. This in turn will result in a call to __sinit in the
789 wrong spot. The input or output buffer will be NULLed and nothing is
790 read or written in the first stdio function call in the main thread.
792 To fix this issue we set __cleanup to _cygtls::cleanup_early here. */
793 _REENT_CLEANUP(_REENT) = _cygtls::cleanup_early;
796 /* Take over from libc's crt0.o and start the application. Note the
797 various special cases when Cygwin DLL is being runtime loaded (as
798 opposed to being link-time loaded by Cygwin apps) from a non
799 cygwin app via LoadLibrary. */
800 void
801 dll_crt0_1 (void *)
803 extern void initial_setlocale ();
805 _my_tls.incyg++;
806 /* Inherit "parent" exec'ed process sigmask */
807 if (spawn_info && __in_forkee != FORKING)
808 _my_tls.sigmask = spawn_info->sigmask;
810 if (dynamically_loaded)
811 sigproc_init ();
813 /* Call this before accessing any files. */
814 RtlSetProcessPlaceholderCompatibilityMode (PHCM_EXPOSE_PLACEHOLDERS);
816 check_sanity_and_sync (user_data);
818 /* Initialize malloc and then call user_shared_initialize since it relies
819 on a functioning malloc and it's possible that the user's program may
820 have overridden malloc. We only know about that at this stage,
821 unfortunately. */
822 malloc_init ();
823 user_shared->initialize ();
825 #ifdef CYGHEAP_DEBUG
826 int i = 0;
827 const int n = 2 * 1024 * 1024;
828 while (i--)
830 void *p = cmalloc (HEAP_STR, n);
831 if (p)
832 small_printf ("cmalloc returns %p\n", cmalloc (HEAP_STR, n));
833 else
835 small_printf ("total allocated %y\n", (i - 1) * n);
836 break;
839 #endif
841 ProtectHandle (hMainThread);
843 cygheap->cwd.init ();
845 /* Initialize pthread mainthread when not forked and it is safe to call new,
846 otherwise it is reinitalized in fixup_after_fork */
847 if (__in_forkee != FORKING)
849 pthread::init_mainthread ();
850 _pei386_runtime_relocator (user_data);
853 #ifdef DEBUGGING
854 strace.microseconds ();
855 #endif
857 cygbench ("pre-forkee");
858 if (__in_forkee == FORKING)
860 /* Make sure to restore the TEB's stack info. If guardsize is -1 the
861 stack has been provided by the application and must not be deallocated
862 automagically when the thread exits.
864 NOTE: Don't do anything that involves the stack until you've completed
865 this step. */
866 PTEB teb = NtCurrentTeb ();
867 teb->Tib.StackBase = (PVOID) fork_info->stackbase;
868 teb->Tib.StackLimit = (PVOID) fork_info->stacklimit;
869 teb->DeallocationStack = (fork_info->guardsize == (size_t) -1)
870 ? NULL
871 : (PVOID) fork_info->stackaddr;
873 /* Not resetting _my_tls.incyg here because presumably fork will overwrite
874 it with the value of the forker and all will be good. */
875 longjmp (fork_info->jmp, true);
878 main_thread_sinit ();
880 #ifdef DEBUGGING
882 extern void fork_init ();
883 fork_init ();
885 #endif
886 pinfo_init (envp, envc);
887 strace.dll_info ();
889 /* Allocate cygheap->fdtab */
890 dtable_init ();
892 /* Set internal locale to the environment settings. */
893 initial_setlocale ();
895 uinfo_init (); /* initialize user info */
897 /* Connect to tty. */
898 tty::init_session ();
900 if (!__argc)
902 PWCHAR wline = GetCommandLineW ();
903 size_t size = sys_wcstombs_no_path (NULL, 0, wline) + 1;
904 char *line = (char *) alloca (size);
905 sys_wcstombs_no_path (line, size, wline);
907 /* Scan the command line and build argv. Expand wildcards if not
908 called from another cygwin process. */
909 build_argv (line, __argv, __argc,
910 NOTSTATE (myself, PID_CYGPARENT) && allow_glob);
912 /* Convert argv[0] to posix rules if it's currently blatantly
913 win32 style. */
914 if ((strchr (__argv[0], ':')) || (strchr (__argv[0], '\\')))
916 char *new_argv0 = (char *) malloc (NT_MAX_PATH);
917 cygwin_conv_path (CCP_WIN_A_TO_POSIX | CCP_RELATIVE, __argv[0],
918 new_argv0, NT_MAX_PATH);
919 __argv[0] = (char *) realloc (new_argv0, strlen (new_argv0) + 1);
923 __argc_safe = __argc;
924 if (user_data->premain[0])
925 for (unsigned int i = 0; i < PREMAIN_LEN / 2; i++)
926 user_data->premain[i] (__argc, __argv, user_data);
928 /* Set up standard fds in file descriptor table. */
929 cygheap->fdtab.stdio_init ();
931 /* Set up program_invocation_name and program_invocation_short_name.
932 __progname is an export alias for program_invocation_short_name. */
933 program_invocation_name = __argv[0];
934 if (__argv[0] && (program_invocation_short_name = strrchr (__argv[0], '/')))
935 ++program_invocation_short_name;
936 else
937 program_invocation_short_name = __argv[0];
938 if (program_invocation_short_name)
940 char *cp = strchr (program_invocation_short_name, '\0') - 4;
941 if (cp > program_invocation_short_name && ascii_strcasematch (cp, ".exe"))
942 *cp = '\0';
944 SetThreadName (GetCurrentThreadId (), program_invocation_short_name);
946 (void) xdr_set_vprintf (&cygxdr_vwarnx);
947 cygwin_finished_initializing = true;
948 /* Call init of loaded dlls. */
949 dlls.init ();
951 /* Execute any specified "premain" functions */
952 if (user_data->premain[PREMAIN_LEN / 2])
953 for (unsigned int i = PREMAIN_LEN / 2; i < PREMAIN_LEN; i++)
954 user_data->premain[i] (__argc, __argv, user_data);
956 set_errno (0);
958 if (dynamically_loaded)
960 _setlocale_r (_REENT, LC_CTYPE, "C");
961 return;
964 /* Disable case-insensitive globbing */
965 ignore_case_with_glob = false;
967 cygbench (__progname);
969 ld_preload ();
970 /* Per POSIX set the default application locale back to "C". */
971 _setlocale_r (_REENT, LC_CTYPE, "C");
973 if (!user_data->main)
975 /* Handle any signals which may have arrived */
976 _my_tls.call_signal_handler ();
977 _my_tls.incyg--; /* Not in Cygwin anymore */
979 else
981 /* Create a copy of Cygwin's version of __argv so that, if the user makes
982 a change to an element of argv[] it does not affect Cygwin's argv.
983 Changing the contents of what argv[n] points to will still affect
984 Cygwin. This is similar (but not exactly like) Linux.
986 We used to allocate newargv on the stack, but all the rest of the
987 argument and environment handling does not depend on the stack,
988 as it does on Linux. In fact, everything is stored by the parent
989 in the cygheap, so the only reason this may fail is if we're out
990 of resources in a big way. If this malloc fails, we could either
991 fail the entire process execution, or we could proceed with the
992 original argv and potentially affect output of /proc/self/cmdline.
993 We opt for the latter here because it's the lesser evil. */
994 char **newargv = (char **) malloc ((__argc + 1) * sizeof (char *));
995 if (newargv)
996 memcpy (newargv, __argv, (__argc + 1) * sizeof (char *));
997 else
998 newargv = __argv;
999 /* Handle any signals which may have arrived */
1000 sig_dispatch_pending (false);
1001 _my_tls.call_signal_handler ();
1002 _my_tls.incyg--; /* Not in Cygwin anymore */
1003 cygwin_exit (user_data->main (__argc, newargv, environ));
1005 __asm__ (" \n\
1006 .global _cygwin_exit_return \n\
1007 .global __cygwin_exit_return \n\
1008 _cygwin_exit_return: \n\
1009 __cygwin_exit_return: \n\
1010 nop \n\
1014 extern "C" void
1015 _dll_crt0 ()
1017 /* Starting with Windows 10 rel 1511, the main stack of an application is
1018 not reproducible if a 64 bit process has been started from a 32 bit
1019 process. Given that we have enough virtual address space on 64 bit
1020 anyway, we now always move the main thread stack to the stack area
1021 reserved for pthread stacks. This allows a reproducible stack space
1022 under our own control and avoids collision with the OS. */
1023 if (!dynamically_loaded)
1025 if (__in_forkee != FORKING)
1027 /* Must be static since it's referenced after the stack and frame
1028 pointer registers have been changed. */
1029 static PVOID allocationbase;
1030 PVOID stackaddr = create_new_main_thread_stack (allocationbase);
1031 if (stackaddr)
1033 #ifdef __x86_64__
1034 /* Set stack pointer to new address. Set frame pointer to
1035 stack pointer and subtract 32 bytes for shadow space. */
1036 __asm__ ("\n\
1037 movq %[ADDR], %%rsp \n\
1038 movq %%rsp, %%rbp \n\
1039 subq $32,%%rsp \n"
1040 : : [ADDR] "r" (stackaddr));
1041 #else
1042 #error unimplemented for this target
1043 #endif
1044 /* We're on the new stack now. Free up space taken by the former
1045 main thread stack and set DeallocationStack correctly. */
1046 VirtualFree (NtCurrentTeb ()->DeallocationStack, 0, MEM_RELEASE);
1047 NtCurrentTeb ()->DeallocationStack = allocationbase;
1050 else
1051 fork_info->alloc_stack ();
1054 fesetenv (FE_DFL_ENV);
1055 _main_tls = &_my_tls;
1056 _main_tls->call ((DWORD (*) (void *, void *)) dll_crt0_1, NULL);
1059 void
1060 dll_crt0 (per_process *uptr)
1062 /* Set the local copy of the pointer into the user space. */
1063 if (__in_forkee != FORKING && uptr && uptr != user_data)
1065 memcpy (user_data, uptr, per_process_overwrite);
1066 *(user_data->impure_ptr_ptr) = _GLOBAL_REENT;
1068 _dll_crt0 ();
1071 /* This must be called by anyone who uses LoadLibrary to load cygwin1.dll.
1072 You must have __CYGTLS_PADSIZE__ bytes reserved at the bottom of the stack
1073 calling this function, and that storage must not be overwritten until you
1074 unload cygwin1.dll, as it is used for _my_tls. It is best to load
1075 cygwin1.dll before spawning any additional threads in your process.
1077 See winsup/testsuite/cygload for an example of how to use cygwin1.dll
1078 from MSVC and non-cygwin MinGW applications. */
1079 extern "C" void
1080 cygwin_dll_init ()
1082 static int _fmode;
1084 user_data->magic_biscuit = sizeof (per_process);
1085 user_data->fmode_ptr = &_fmode;
1086 _dll_crt0 ();
1089 extern "C" void
1090 __main (void)
1092 /* Ordering is critical here. DLL ctors have already been
1093 run as they were being loaded, so we should stack the
1094 queued call to DLL dtors now. */
1095 atexit (dll_global_dtors);
1096 do_global_ctors (user_data->ctors, false);
1097 /* Now we have run global ctors, register their dtors.
1099 At exit, global dtors will run first, so the app can still
1100 use shared library functions while terminating; then the
1101 DLLs will be destroyed; finally newlib will shut down stdio
1102 and terminate itself. */
1103 atexit (do_global_dtors);
1104 sig_dispatch_pending (true);
1107 void
1108 do_exit (int status)
1110 syscall_printf ("do_exit (%d), exit_state %d", status, exit_state);
1112 lock_process until_exit (true);
1114 if (exit_state < ES_EVENTS_TERMINATE)
1115 exit_state = ES_EVENTS_TERMINATE;
1117 if (exit_state < ES_SIGNAL)
1119 exit_state = ES_SIGNAL;
1120 signal (SIGCHLD, SIG_IGN);
1121 signal (SIGHUP, SIG_IGN);
1122 signal (SIGINT, SIG_IGN);
1123 signal (SIGQUIT, SIG_IGN);
1126 if (exit_state < ES_CLOSEALL)
1128 exit_state = ES_CLOSEALL;
1129 close_all_files ();
1132 UINT n = (UINT) status;
1133 if (exit_state < ES_THREADTERM)
1135 exit_state = ES_THREADTERM;
1136 cygthread::terminate ();
1139 myself->stopsig = 0;
1141 if (exit_state < ES_HUP_PGRP)
1143 exit_state = ES_HUP_PGRP;
1144 /* Kill orphaned children on group leader exit */
1145 if (myself->has_pgid_children && myself->pid == myself->pgid)
1147 siginfo_t si = {0};
1148 si.si_signo = -SIGHUP;
1149 si.si_code = SI_KERNEL;
1150 sigproc_printf ("%u == pgrp %u, send SIG{HUP,CONT} to stopped children",
1151 myself->pid, myself->pgid);
1152 kill_pgrp (myself->pgid, si);
1156 if (exit_state < ES_HUP_SID)
1158 exit_state = ES_HUP_SID;
1159 /* Kill the foreground process group on session leader exit */
1160 if (getpgrp () > 0 && myself->pid == myself->sid && real_tty_attached (myself))
1162 tty *tp = cygwin_shared->tty[myself->ctty];
1163 sigproc_printf ("%u == sid %u, send SIGHUP to children",
1164 myself->pid, myself->sid);
1166 /* CGF FIXME: This can't be right. */
1167 if (tp->getsid () == myself->sid)
1168 tp->kill_pgrp (SIGHUP);
1173 myself.exit (n);
1176 /* When introducing support for -fuse-cxa-atexit with Cygwin 1.7.32 and
1177 GCC 4.8.3-3, we defined __dso_value as &ImageBase. This supposedly allowed
1178 a reproducible value which could also be easily evaluated in cygwin_atexit.
1179 However, when building C++ applications with -fuse-cxa-atexit, G++ creates
1180 calls to __cxa_atexit using the *address* of __dso_handle as DSO handle.
1182 So what we do here is this: A call to __cxa_atexit from the application
1183 actually calls cygwin__cxa_atexit. From dso_handle (which is either
1184 &__dso_handle, or __dso_handle == ImageBase or NULL) we fetch the dll
1185 structure of the DLL. Then use dll::handle == ImageBase as the actual DSO
1186 handle value in calls to __cxa_atexit and __cxa_finalize.
1187 Thus, __cxa_atexit becomes entirely independent of the incoming value of
1188 dso_handle, as long as it's *some* pointer into the DSO's address space. */
1189 extern "C" int
1190 cygwin__cxa_atexit (void (*fn)(void *), void *obj, void *dso_handle)
1192 dll *d = dso_handle ? dlls.find (dso_handle) : NULL;
1193 return __cxa_atexit (fn, obj, d ? d->handle : NULL);
1196 /* This function is only called for applications built with Cygwin versions
1197 up to API 0.279. Starting with API 0.280 (Cygwin 1.7.33/1.8.6-2), atexit
1198 is a statically linked function inside of libcygwin.a. The reason is that
1199 the old method to fetch the caller return address is unreliable given GCCs
1200 ability to perform tail call elimination. For the details, see the below
1201 comment. The atexit replacement is defined in libcygwin.a to allow reliable
1202 access to the correct DSO handle. */
1203 extern "C" int
1204 cygwin_atexit (void (*fn) (void))
1206 int res;
1208 dll *d = dlls.find ((void *) _my_tls.retaddr ());
1209 /* x86_64 DLLs created with GCC 4.8.3-3 register __gcc_deregister_frame
1210 as atexit function using a call to atexit, rather than __cxa_atexit.
1211 Due to GCC's tail call optimizing, cygwin_atexit doesn't get the correct
1212 return address on the stack. As a result it fails to get the HMODULE of
1213 the caller and thus calls atexit rather than __cxa_atexit. Then, if the
1214 module gets dlclosed, __cxa_finalize (called from dll_list::detach) can't
1215 remove __gcc_deregister_frame from the atexit function chain. So at
1216 process exit, __call_exitprocs calls __gcc_deregister_frame while the
1217 module is already unloaded and the __gcc_deregister_frame function not
1218 available ==> SEGV.
1220 This also occurs for other functions.
1222 Workaround: If dlls.find fails, try to find the dll entry of the DLL
1223 containing fn. If that works, proceed by calling __cxa_atexit, otherwise
1224 call atexit.
1226 This *should* be sufficiently safe. Ultimately, new applications will
1227 use the statically linked atexit function though, as outlined above. */
1228 if (!d)
1229 d = dlls.find ((void *) fn);
1230 res = d ? __cxa_atexit ((void (*) (void *)) fn, NULL, d->handle) : atexit (fn);
1231 return res;
1234 extern "C" void
1235 cygwin_exit (int n)
1237 exit_state = ES_EXIT_STARTING;
1238 exit (n);
1241 extern "C" void
1242 _exit (int n)
1244 do_exit (((DWORD) n & 0xff) << 8);
1247 extern "C" void cygwin_stackdump ();
1249 extern "C" void
1250 vapi_fatal (const char *fmt, va_list ap)
1252 char buf[4096];
1253 int n = __small_sprintf (buf, "%P: *** fatal error %s- ",
1254 (__in_forkee == FORKING)
1255 ? "in forked process " : "");
1256 __small_vsprintf (buf + n, fmt, ap);
1257 va_end (ap);
1258 strace.prntf (_STRACE_SYSTEM, NULL, "%s", buf);
1259 api_fatal_debug();
1260 myself.exit (__api_fatal_exit_val);
1263 extern "C" void
1264 api_fatal (const char *fmt, ...)
1266 va_list ap;
1268 va_start (ap, fmt);
1269 vapi_fatal (fmt, ap);
1272 void
1273 multiple_cygwin_problem (const char *what, uintptr_t magic_version, uintptr_t version)
1275 if (_cygwin_testing && (strstr (what, "proc")))
1277 child_proc_info->type = _CH_WHOOPS;
1278 return;
1281 if (GetEnvironmentVariableA ("CYGWIN_MISMATCH_OK", NULL, 0))
1282 return;
1284 if (CYGWIN_VERSION_MAGIC_VERSION (magic_version) == version)
1285 system_printf ("%s magic number mismatch detected - %p/%ly", what, magic_version, version);
1286 else
1287 api_fatal ("%s mismatch detected - %ly/%ly.\n\
1288 This problem is probably due to using incompatible versions of the cygwin DLL.\n\
1289 Search for cygwin1.dll using the Windows Start->Find/Search facility\n\
1290 and delete all but the most recent version. The most recent version *should*\n\
1291 reside in x:\\cygwin\\bin, where 'x' is the drive on which you have\n\
1292 installed the cygwin distribution. Rebooting is also suggested if you\n\
1293 are unable to find another cygwin DLL.",
1294 what, magic_version, version);
1297 #ifdef DEBUGGING
1298 void
1299 cygbench (const char *s)
1301 if (GetEnvironmentVariableA ("CYGWIN_BENCH", NULL, 0))
1302 small_printf ("%05u ***** %s : %10d\n", GetCurrentProcessId (), s, strace.microseconds ());
1304 #endif