Cygwin: (mostly) drop NT4 and Samba < 3.0 support
[newlib-cygwin.git] / winsup / cygwin / dcrt0.cc
blob7229377eb3fe47f0b030a2489d61b0d6d9d00684
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 /* Call this before accessing any files. */
813 RtlSetProcessPlaceholderCompatibilityMode (PHCM_EXPOSE_PLACEHOLDERS);
815 check_sanity_and_sync (user_data);
817 /* Initialize malloc and then call user_shared_initialize since it relies
818 on a functioning malloc and it's possible that the user's program may
819 have overridden malloc. We only know about that at this stage,
820 unfortunately. */
821 malloc_init ();
822 user_shared->initialize ();
824 #ifdef CYGHEAP_DEBUG
825 int i = 0;
826 const int n = 2 * 1024 * 1024;
827 while (i--)
829 void *p = cmalloc (HEAP_STR, n);
830 if (p)
831 small_printf ("cmalloc returns %p\n", cmalloc (HEAP_STR, n));
832 else
834 small_printf ("total allocated %y\n", (i - 1) * n);
835 break;
838 #endif
840 ProtectHandle (hMainThread);
842 cygheap->cwd.init ();
844 /* Initialize pthread mainthread when not forked and it is safe to call new,
845 otherwise it is reinitalized in fixup_after_fork */
846 if (__in_forkee != FORKING)
848 pthread::init_mainthread ();
849 _pei386_runtime_relocator (user_data);
852 #ifdef DEBUGGING
853 strace.microseconds ();
854 #endif
856 cygbench ("pre-forkee");
857 if (__in_forkee == FORKING)
859 /* Make sure to restore the TEB's stack info. If guardsize is -1 the
860 stack has been provided by the application and must not be deallocated
861 automagically when the thread exits.
863 NOTE: Don't do anything that involves the stack until you've completed
864 this step. */
865 PTEB teb = NtCurrentTeb ();
866 teb->Tib.StackBase = (PVOID) fork_info->stackbase;
867 teb->Tib.StackLimit = (PVOID) fork_info->stacklimit;
868 teb->DeallocationStack = (fork_info->guardsize == (size_t) -1)
869 ? NULL
870 : (PVOID) fork_info->stackaddr;
872 /* Not resetting _my_tls.incyg here because presumably fork will overwrite
873 it with the value of the forker and all will be good. */
874 longjmp (fork_info->jmp, true);
877 main_thread_sinit ();
879 #ifdef DEBUGGING
881 extern void fork_init ();
882 fork_init ();
884 #endif
885 pinfo_init (envp, envc);
886 strace.dll_info ();
888 /* Allocate cygheap->fdtab */
889 dtable_init ();
891 /* Set internal locale to the environment settings. */
892 initial_setlocale ();
894 uinfo_init (); /* initialize user info */
896 /* Connect to tty. */
897 tty::init_session ();
899 if (!__argc)
901 PWCHAR wline = GetCommandLineW ();
902 size_t size = sys_wcstombs_no_path (NULL, 0, wline) + 1;
903 char *line = (char *) alloca (size);
904 sys_wcstombs_no_path (line, size, wline);
906 /* Scan the command line and build argv. Expand wildcards if not
907 called from another cygwin process. */
908 build_argv (line, __argv, __argc,
909 NOTSTATE (myself, PID_CYGPARENT) && allow_glob);
911 /* Convert argv[0] to posix rules if it's currently blatantly
912 win32 style. */
913 if ((strchr (__argv[0], ':')) || (strchr (__argv[0], '\\')))
915 char *new_argv0 = (char *) malloc (NT_MAX_PATH);
916 cygwin_conv_path (CCP_WIN_A_TO_POSIX | CCP_RELATIVE, __argv[0],
917 new_argv0, NT_MAX_PATH);
918 __argv[0] = (char *) realloc (new_argv0, strlen (new_argv0) + 1);
922 __argc_safe = __argc;
923 if (user_data->premain[0])
924 for (unsigned int i = 0; i < PREMAIN_LEN / 2; i++)
925 user_data->premain[i] (__argc, __argv, user_data);
927 /* Set up standard fds in file descriptor table. */
928 cygheap->fdtab.stdio_init ();
930 /* Set up program_invocation_name and program_invocation_short_name.
931 __progname is an export alias for program_invocation_short_name. */
932 program_invocation_name = __argv[0];
933 if (__argv[0] && (program_invocation_short_name = strrchr (__argv[0], '/')))
934 ++program_invocation_short_name;
935 else
936 program_invocation_short_name = __argv[0];
937 if (program_invocation_short_name)
939 char *cp = strchr (program_invocation_short_name, '\0') - 4;
940 if (cp > program_invocation_short_name && ascii_strcasematch (cp, ".exe"))
941 *cp = '\0';
943 SetThreadName (GetCurrentThreadId (), program_invocation_short_name);
945 (void) xdr_set_vprintf (&cygxdr_vwarnx);
946 cygwin_finished_initializing = true;
947 /* Call init of loaded dlls. */
948 dlls.init ();
950 /* Execute any specified "premain" functions */
951 if (user_data->premain[PREMAIN_LEN / 2])
952 for (unsigned int i = PREMAIN_LEN / 2; i < PREMAIN_LEN; i++)
953 user_data->premain[i] (__argc, __argv, user_data);
955 set_errno (0);
957 if (dynamically_loaded)
959 _setlocale_r (_REENT, LC_CTYPE, "C");
960 return;
963 /* Disable case-insensitive globbing */
964 ignore_case_with_glob = false;
966 cygbench (__progname);
968 ld_preload ();
969 /* Per POSIX set the default application locale back to "C". */
970 _setlocale_r (_REENT, LC_CTYPE, "C");
972 if (!user_data->main)
974 /* Handle any signals which may have arrived */
975 _my_tls.call_signal_handler ();
976 _my_tls.incyg--; /* Not in Cygwin anymore */
978 else
980 /* Create a copy of Cygwin's version of __argv so that, if the user makes
981 a change to an element of argv[] it does not affect Cygwin's argv.
982 Changing the contents of what argv[n] points to will still affect
983 Cygwin. This is similar (but not exactly like) Linux.
985 We used to allocate newargv on the stack, but all the rest of the
986 argument and environment handling does not depend on the stack,
987 as it does on Linux. In fact, everything is stored by the parent
988 in the cygheap, so the only reason this may fail is if we're out
989 of resources in a big way. If this malloc fails, we could either
990 fail the entire process execution, or we could proceed with the
991 original argv and potentially affect output of /proc/self/cmdline.
992 We opt for the latter here because it's the lesser evil. */
993 char **newargv = (char **) malloc ((__argc + 1) * sizeof (char *));
994 if (newargv)
995 memcpy (newargv, __argv, (__argc + 1) * sizeof (char *));
996 else
997 newargv = __argv;
998 /* Handle any signals which may have arrived */
999 sig_dispatch_pending (false);
1000 _my_tls.call_signal_handler ();
1001 _my_tls.incyg--; /* Not in Cygwin anymore */
1002 cygwin_exit (user_data->main (__argc, newargv, environ));
1004 __asm__ (" \n\
1005 .global _cygwin_exit_return \n\
1006 .global __cygwin_exit_return \n\
1007 _cygwin_exit_return: \n\
1008 __cygwin_exit_return: \n\
1009 nop \n\
1013 extern "C" void
1014 _dll_crt0 ()
1016 /* Starting with Windows 10 rel 1511, the main stack of an application is
1017 not reproducible if a 64 bit process has been started from a 32 bit
1018 process. Given that we have enough virtual address space on 64 bit
1019 anyway, we now always move the main thread stack to the stack area
1020 reserved for pthread stacks. This allows a reproducible stack space
1021 under our own control and avoids collision with the OS. */
1022 if (!dynamically_loaded)
1024 if (__in_forkee != FORKING)
1026 /* Must be static since it's referenced after the stack and frame
1027 pointer registers have been changed. */
1028 static PVOID allocationbase;
1029 PVOID stackaddr = create_new_main_thread_stack (allocationbase);
1030 if (stackaddr)
1032 #ifdef __x86_64__
1033 /* Set stack pointer to new address. Set frame pointer to
1034 stack pointer and subtract 32 bytes for shadow space. */
1035 __asm__ ("\n\
1036 movq %[ADDR], %%rsp \n\
1037 movq %%rsp, %%rbp \n\
1038 subq $32,%%rsp \n"
1039 : : [ADDR] "r" (stackaddr));
1040 #else
1041 #error unimplemented for this target
1042 #endif
1043 /* We're on the new stack now. Free up space taken by the former
1044 main thread stack and set DeallocationStack correctly. */
1045 VirtualFree (NtCurrentTeb ()->DeallocationStack, 0, MEM_RELEASE);
1046 NtCurrentTeb ()->DeallocationStack = allocationbase;
1049 else
1050 fork_info->alloc_stack ();
1053 fesetenv (FE_DFL_ENV);
1054 _main_tls = &_my_tls;
1055 _main_tls->call ((DWORD (*) (void *, void *)) dll_crt0_1, NULL);
1058 void
1059 dll_crt0 (per_process *uptr)
1061 /* Set the local copy of the pointer into the user space. */
1062 if (__in_forkee != FORKING && uptr && uptr != user_data)
1064 memcpy (user_data, uptr, per_process_overwrite);
1065 *(user_data->impure_ptr_ptr) = _GLOBAL_REENT;
1067 _dll_crt0 ();
1070 /* This must be called by anyone who uses LoadLibrary to load cygwin1.dll.
1071 You must have __CYGTLS_PADSIZE__ bytes reserved at the bottom of the stack
1072 calling this function, and that storage must not be overwritten until you
1073 unload cygwin1.dll, as it is used for _my_tls. It is best to load
1074 cygwin1.dll before spawning any additional threads in your process.
1076 See winsup/testsuite/cygload for an example of how to use cygwin1.dll
1077 from MSVC and non-cygwin MinGW applications. */
1078 extern "C" void
1079 cygwin_dll_init ()
1081 static int _fmode;
1083 user_data->magic_biscuit = sizeof (per_process);
1084 user_data->fmode_ptr = &_fmode;
1085 _dll_crt0 ();
1088 extern "C" void
1089 __main (void)
1091 /* Ordering is critical here. DLL ctors have already been
1092 run as they were being loaded, so we should stack the
1093 queued call to DLL dtors now. */
1094 atexit (dll_global_dtors);
1095 do_global_ctors (user_data->ctors, false);
1096 /* Now we have run global ctors, register their dtors.
1098 At exit, global dtors will run first, so the app can still
1099 use shared library functions while terminating; then the
1100 DLLs will be destroyed; finally newlib will shut down stdio
1101 and terminate itself. */
1102 atexit (do_global_dtors);
1103 sig_dispatch_pending (true);
1106 void
1107 do_exit (int status)
1109 syscall_printf ("do_exit (%d), exit_state %d", status, exit_state);
1111 lock_process until_exit (true);
1113 if (exit_state < ES_EVENTS_TERMINATE)
1114 exit_state = ES_EVENTS_TERMINATE;
1116 if (exit_state < ES_SIGNAL)
1118 exit_state = ES_SIGNAL;
1119 signal (SIGCHLD, SIG_IGN);
1120 signal (SIGHUP, SIG_IGN);
1121 signal (SIGINT, SIG_IGN);
1122 signal (SIGQUIT, SIG_IGN);
1125 if (exit_state < ES_CLOSEALL)
1127 exit_state = ES_CLOSEALL;
1128 close_all_files ();
1131 UINT n = (UINT) status;
1132 if (exit_state < ES_THREADTERM)
1134 exit_state = ES_THREADTERM;
1135 cygthread::terminate ();
1138 myself->stopsig = 0;
1140 if (exit_state < ES_HUP_PGRP)
1142 exit_state = ES_HUP_PGRP;
1143 /* Kill orphaned children on group leader exit */
1144 if (myself->has_pgid_children && myself->pid == myself->pgid)
1146 siginfo_t si = {0};
1147 si.si_signo = -SIGHUP;
1148 si.si_code = SI_KERNEL;
1149 sigproc_printf ("%u == pgrp %u, send SIG{HUP,CONT} to stopped children",
1150 myself->pid, myself->pgid);
1151 kill_pgrp (myself->pgid, si);
1155 if (exit_state < ES_HUP_SID)
1157 exit_state = ES_HUP_SID;
1158 /* Kill the foreground process group on session leader exit */
1159 if (getpgrp () > 0 && myself->pid == myself->sid && real_tty_attached (myself))
1161 tty *tp = cygwin_shared->tty[myself->ctty];
1162 sigproc_printf ("%u == sid %u, send SIGHUP to children",
1163 myself->pid, myself->sid);
1165 /* CGF FIXME: This can't be right. */
1166 if (tp->getsid () == myself->sid)
1167 tp->kill_pgrp (SIGHUP);
1172 myself.exit (n);
1175 /* When introducing support for -fuse-cxa-atexit with Cygwin 1.7.32 and
1176 GCC 4.8.3-3, we defined __dso_value as &ImageBase. This supposedly allowed
1177 a reproducible value which could also be easily evaluated in cygwin_atexit.
1178 However, when building C++ applications with -fuse-cxa-atexit, G++ creates
1179 calls to __cxa_atexit using the *address* of __dso_handle as DSO handle.
1181 So what we do here is this: A call to __cxa_atexit from the application
1182 actually calls cygwin__cxa_atexit. From dso_handle (which is either
1183 &__dso_handle, or __dso_handle == ImageBase or NULL) we fetch the dll
1184 structure of the DLL. Then use dll::handle == ImageBase as the actual DSO
1185 handle value in calls to __cxa_atexit and __cxa_finalize.
1186 Thus, __cxa_atexit becomes entirely independent of the incoming value of
1187 dso_handle, as long as it's *some* pointer into the DSO's address space. */
1188 extern "C" int
1189 cygwin__cxa_atexit (void (*fn)(void *), void *obj, void *dso_handle)
1191 dll *d = dso_handle ? dlls.find (dso_handle) : NULL;
1192 return __cxa_atexit (fn, obj, d ? d->handle : NULL);
1195 /* This function is only called for applications built with Cygwin versions
1196 up to API 0.279. Starting with API 0.280 (Cygwin 1.7.33/1.8.6-2), atexit
1197 is a statically linked function inside of libcygwin.a. The reason is that
1198 the old method to fetch the caller return address is unreliable given GCCs
1199 ability to perform tail call elimination. For the details, see the below
1200 comment. The atexit replacement is defined in libcygwin.a to allow reliable
1201 access to the correct DSO handle. */
1202 extern "C" int
1203 cygwin_atexit (void (*fn) (void))
1205 int res;
1207 dll *d = dlls.find ((void *) _my_tls.retaddr ());
1208 /* x86_64 DLLs created with GCC 4.8.3-3 register __gcc_deregister_frame
1209 as atexit function using a call to atexit, rather than __cxa_atexit.
1210 Due to GCC's tail call optimizing, cygwin_atexit doesn't get the correct
1211 return address on the stack. As a result it fails to get the HMODULE of
1212 the caller and thus calls atexit rather than __cxa_atexit. Then, if the
1213 module gets dlclosed, __cxa_finalize (called from dll_list::detach) can't
1214 remove __gcc_deregister_frame from the atexit function chain. So at
1215 process exit, __call_exitprocs calls __gcc_deregister_frame while the
1216 module is already unloaded and the __gcc_deregister_frame function not
1217 available ==> SEGV.
1219 This also occurs for other functions.
1221 Workaround: If dlls.find fails, try to find the dll entry of the DLL
1222 containing fn. If that works, proceed by calling __cxa_atexit, otherwise
1223 call atexit.
1225 This *should* be sufficiently safe. Ultimately, new applications will
1226 use the statically linked atexit function though, as outlined above. */
1227 if (!d)
1228 d = dlls.find ((void *) fn);
1229 res = d ? __cxa_atexit ((void (*) (void *)) fn, NULL, d->handle) : atexit (fn);
1230 return res;
1233 extern "C" void
1234 cygwin_exit (int n)
1236 exit_state = ES_EXIT_STARTING;
1237 exit (n);
1240 extern "C" void
1241 _exit (int n)
1243 do_exit (((DWORD) n & 0xff) << 8);
1246 extern "C" void cygwin_stackdump ();
1248 extern "C" void
1249 vapi_fatal (const char *fmt, va_list ap)
1251 char buf[4096];
1252 int n = __small_sprintf (buf, "%P: *** fatal error %s- ",
1253 (__in_forkee == FORKING)
1254 ? "in forked process " : "");
1255 __small_vsprintf (buf + n, fmt, ap);
1256 va_end (ap);
1257 strace.prntf (_STRACE_SYSTEM, NULL, "%s", buf);
1258 api_fatal_debug();
1259 myself.exit (__api_fatal_exit_val);
1262 extern "C" void
1263 api_fatal (const char *fmt, ...)
1265 va_list ap;
1267 va_start (ap, fmt);
1268 vapi_fatal (fmt, ap);
1271 void
1272 multiple_cygwin_problem (const char *what, uintptr_t magic_version, uintptr_t version)
1274 if (_cygwin_testing && (strstr (what, "proc")))
1276 child_proc_info->type = _CH_WHOOPS;
1277 return;
1280 if (GetEnvironmentVariableA ("CYGWIN_MISMATCH_OK", NULL, 0))
1281 return;
1283 if (CYGWIN_VERSION_MAGIC_VERSION (magic_version) == version)
1284 system_printf ("%s magic number mismatch detected - %p/%ly", what, magic_version, version);
1285 else
1286 api_fatal ("%s mismatch detected - %ly/%ly.\n\
1287 This problem is probably due to using incompatible versions of the cygwin DLL.\n\
1288 Search for cygwin1.dll using the Windows Start->Find/Search facility\n\
1289 and delete all but the most recent version. The most recent version *should*\n\
1290 reside in x:\\cygwin\\bin, where 'x' is the drive on which you have\n\
1291 installed the cygwin distribution. Rebooting is also suggested if you\n\
1292 are unable to find another cygwin DLL.",
1293 what, magic_version, version);
1296 #ifdef DEBUGGING
1297 void
1298 cygbench (const char *s)
1300 if (GetEnvironmentVariableA ("CYGWIN_BENCH", NULL, 0))
1301 small_printf ("%05u ***** %s : %10d\n", GetCurrentProcessId (), s, strace.microseconds ());
1303 #endif