3 Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003 Red Hat, Inc.
5 This file is part of Cygwin.
7 This software is a copyrighted work licensed under the terms of the
8 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
15 #include "exceptions.h"
20 #include "perthread.h"
21 #include "shared_info.h"
22 #include "perprocess.h"
25 #define CALL_HANDLER_RETRY 20
27 char debugger_command[2 * MAX_PATH + 20];
30 static int handle_exceptions (EXCEPTION_RECORD *, void *, CONTEXT *, void *);
31 extern void sigreturn ();
32 extern void sigdelayed ();
33 extern void sigdelayed0 ();
34 extern void siglast ();
35 extern DWORD __no_sig_start, __no_sig_end;
40 extern HANDLE hExeced;
41 extern DWORD dwExeced;
43 static BOOL WINAPI ctrl_c_handler (DWORD);
44 static void signal_exit (int) __attribute__ ((noreturn));
45 static char windows_system_directory[1024];
46 static size_t windows_system_directory_length;
48 /* This is set to indicate that we have already exited. */
50 static NO_COPY int exit_already = 0;
51 static NO_COPY muto *mask_sync = NULL;
53 HMODULE NO_COPY cygwin_hmodule;
62 { X (STATUS_ABANDONED_WAIT_0) },
63 { X (STATUS_ACCESS_VIOLATION) },
64 { X (STATUS_ARRAY_BOUNDS_EXCEEDED) },
65 { X (STATUS_BREAKPOINT) },
66 { X (STATUS_CONTROL_C_EXIT) },
67 { X (STATUS_DATATYPE_MISALIGNMENT) },
68 { X (STATUS_FLOAT_DENORMAL_OPERAND) },
69 { X (STATUS_FLOAT_DIVIDE_BY_ZERO) },
70 { X (STATUS_FLOAT_INEXACT_RESULT) },
71 { X (STATUS_FLOAT_INVALID_OPERATION) },
72 { X (STATUS_FLOAT_OVERFLOW) },
73 { X (STATUS_FLOAT_STACK_CHECK) },
74 { X (STATUS_FLOAT_UNDERFLOW) },
75 { X (STATUS_GUARD_PAGE_VIOLATION) },
76 { X (STATUS_ILLEGAL_INSTRUCTION) },
77 { X (STATUS_INTEGER_DIVIDE_BY_ZERO) },
78 { X (STATUS_INTEGER_OVERFLOW) },
79 { X (STATUS_INVALID_DISPOSITION) },
80 { X (STATUS_IN_PAGE_ERROR) },
81 { X (STATUS_NONCONTINUABLE_EXCEPTION) },
82 { X (STATUS_NO_MEMORY) },
83 { X (STATUS_PENDING) },
84 { X (STATUS_PRIVILEGED_INSTRUCTION) },
85 { X (STATUS_SINGLE_STEP) },
86 { X (STATUS_STACK_OVERFLOW) },
87 { X (STATUS_TIMEOUT) },
88 { X (STATUS_USER_APC) },
89 { X (STATUS_WAIT_0) },
94 /* Initialization code. */
98 // Set up the exception handler for the current thread. The PowerPC & Mips
99 // use compiler generated tables to set up the exception handlers for each
100 // region of code, and the kernel walks the call list until it finds a region
101 // of code that handles exceptions. The x86 on the other hand uses segment
102 // register fs, offset 0 to point to the current exception handler.
104 asm (".equ __except_list,0");
106 extern exception_list *_except_list asm ("%fs:__except_list");
109 init_exception_handler (exception_list *el)
111 el->handler = handle_exceptions;
112 el->prev = _except_list;
120 (void) SetConsoleCtrlHandler (ctrl_c_handler, FALSE);
121 if (!SetConsoleCtrlHandler (ctrl_c_handler, TRUE))
122 system_printf ("SetConsoleCtrlHandler failed, %E");
124 /* Initialize global security attribute stuff */
126 sec_none.nLength = sec_none_nih.nLength =
127 sec_all.nLength = sec_all_nih.nLength = sizeof (SECURITY_ATTRIBUTES);
128 sec_none.bInheritHandle = sec_all.bInheritHandle = TRUE;
129 sec_none_nih.bInheritHandle = sec_all_nih.bInheritHandle = FALSE;
130 sec_none.lpSecurityDescriptor = sec_none_nih.lpSecurityDescriptor = NULL;
131 sec_all.lpSecurityDescriptor = sec_all_nih.lpSecurityDescriptor =
136 init_exceptions (exception_list *el)
138 init_exception_handler (el);
142 error_start_init (const char *buf)
146 debugger_command[0] = '\0';
150 char pgm[MAX_PATH + 1];
151 if (!GetModuleFileName (NULL, pgm, MAX_PATH))
152 strcpy (pgm, "cygwin1.dll");
153 for (char *p = strchr (pgm, '\\'); p; p = strchr (p, '\\'))
156 __small_sprintf (debugger_command, "%s \"%s\"", buf, pgm);
160 open_stackdumpfile ()
162 if (myself->progname[0])
165 /* write to progname.stackdump if possible */
166 if (!myself->progname[0])
168 else if ((p = strrchr (myself->progname, '\\')))
171 p = myself->progname;
172 char corefile[strlen (p) + sizeof (".stackdump")];
173 __small_sprintf (corefile, "%s.stackdump", p);
174 HANDLE h = CreateFile (corefile, GENERIC_WRITE, 0, &sec_none_nih,
175 CREATE_ALWAYS, 0, 0);
176 if (h != INVALID_HANDLE_VALUE)
178 if (!myself->ppid_handle)
179 system_printf ("Dumping stack trace to %s", corefile);
181 debug_printf ("Dumping stack trace to %s", corefile);
182 SetStdHandle (STD_ERROR_HANDLE, h);
187 /* Utilities for dumping the stack, etc. */
190 exception (EXCEPTION_RECORD *e, CONTEXT *in)
192 const char *exception_name = NULL;
196 for (int i = 0; status_info[i].name; i++)
198 if (status_info[i].code == e->ExceptionCode)
200 exception_name = status_info[i].name;
209 small_printf ("Exception: %s at eip=%08x\r\n", exception_name, in->Eip);
211 small_printf ("Exception %d at eip=%08x\r\n", e->ExceptionCode, in->Eip);
212 small_printf ("eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\r\n",
213 in->Eax, in->Ebx, in->Ecx, in->Edx, in->Esi, in->Edi);
214 small_printf ("ebp=%08x esp=%08x program=%s\r\n",
215 in->Ebp, in->Esp, myself->progname);
216 small_printf ("cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x\r\n",
217 in->SegCs, in->SegDs, in->SegEs, in->SegFs, in->SegGs, in->SegSs);
221 system_printf ("Had an exception");
226 /* Print a stack backtrace. */
228 #define HAVE_STACK_TRACE
230 /* A class for manipulating the stack. */
233 int walk (); /* Uses the "old" method */
234 char *next_offset () {return *((char **) sf.AddrFrame.Offset);}
238 STACKFRAME sf; /* For storing the stack information */
239 void init (DWORD, bool, bool); /* Called the first time that stack info is needed */
241 /* Postfix ++ iterates over the stack, returning zero when nothing is left. */
242 int operator ++(int) { return walk (); }
245 /* The number of parameters used in STACKFRAME */
246 #define NPARAMS (sizeof (thestack.sf.Params) / sizeof (thestack.sf.Params[0]))
248 /* This is the main stack frame info for this process. */
249 static NO_COPY stack_info thestack;
250 static signal_dispatch sigsave;
252 /* Initialize everything needed to start iterating. */
254 stack_info::init (DWORD ebp, bool wantargs, bool goodframe)
256 # define debp ((DWORD *) ebp)
257 memset (&sf, 0, sizeof (sf));
259 sf.AddrFrame.Offset = ebp;
263 sf.AddrFrame.Offset = (DWORD) &dummy_frame;
265 sf.AddrReturn.Offset = debp[1];
266 sf.AddrFrame.Mode = AddrModeFlat;
271 /* Walk the stack by looking at successive stored 'bp' frames.
272 This is not foolproof. */
277 if ((ebp = (char **) next_offset ()) == NULL)
280 sf.AddrFrame.Offset = (DWORD) ebp;
281 sf.AddrPC.Offset = sf.AddrReturn.Offset;
283 if (!sf.AddrPC.Offset)
284 return 0; /* stack frames are exhausted */
286 /* The return address always follows the stack pointer */
287 sf.AddrReturn.Offset = (DWORD) *++ebp;
290 /* The arguments follow the return address */
291 for (unsigned i = 0; i < NPARAMS; i++)
292 sf.Params[i] = (DWORD) *++ebp;
298 stackdump (DWORD ebp, int open_file, bool isexception)
300 extern unsigned long rlim_core;
302 if (rlim_core == 0UL)
306 open_stackdumpfile ();
310 thestack.init (ebp, 1, !isexception); /* Initialize from the input CONTEXT */
311 small_printf ("Stack trace:\r\nFrame Function Args\r\n");
312 for (i = 0; i < 16 && thestack++; i++)
314 small_printf ("%08x %08x ", thestack.sf.AddrFrame.Offset,
315 thestack.sf.AddrPC.Offset);
316 for (unsigned j = 0; j < NPARAMS; j++)
317 small_printf ("%s%08x", j == 0 ? " (" : ", ", thestack.sf.Params[j]);
318 small_printf (")\r\n");
320 small_printf ("End of stack trace%s",
321 i == 16 ? " (more stack frames may be present)" : "");
324 /* Temporary (?) function for external callers to get a stack dump */
329 c.ContextFlags = CONTEXT_FULL;
330 GetThreadContext (GetCurrentThread (), &c);
331 stackdump (c.Ebp, 0, 0);
334 #define TIME_TO_WAIT_FOR_DEBUGGER 10000
337 try_to_debug (bool waitloop)
339 debug_printf ("debugger_command '%s'", debugger_command);
340 if (*debugger_command == '\0' || being_debugged ())
343 __small_sprintf (strchr (debugger_command, '\0'), " %u", GetCurrentProcessId ());
345 LONG prio = GetThreadPriority (GetCurrentThread ());
346 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_HIGHEST);
347 PROCESS_INFORMATION pi = {NULL, 0, 0, 0};
349 STARTUPINFO si = {0, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL};
350 si.lpReserved = NULL;
355 /* FIXME: need to know handles of all running threads to
356 suspend_all_threads_except (current_thread_id);
359 /* if any of these mutexes is owned, we will fail to start any cygwin app
360 until trapped app exits */
362 ReleaseMutex (title_mutex);
364 /* prevent recursive exception handling */
365 char* rawenv = GetEnvironmentStrings () ;
366 for (char* p = rawenv; *p != '\0'; p = strchr (p, '\0') + 1)
368 if (strncmp (p, "CYGWIN=", sizeof ("CYGWIN=") - 1) == 0)
370 char* q = strstr (p, "error_start") ;
371 /* replace 'error_start=...' with '_rror_start=...' */
373 SetEnvironmentVariable ("CYGWIN", p + sizeof ("CYGWIN=")) ;
379 dbg = CreateProcess (NULL,
384 CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
391 system_printf ("Failed to start debugger: %E");
396 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_IDLE);
397 while (!being_debugged ())
400 small_printf ("*** continuing from debugger call\n");
401 SetThreadPriority (GetCurrentThread (), prio);
404 /* FIXME: need to know handles of all running threads to
405 resume_all_threads_except (current_thread_id);
410 /* Main exception handler. */
413 handle_exceptions (EXCEPTION_RECORD *e, void *, CONTEXT *in, void *)
416 static int NO_COPY debugging = 0;
417 static int NO_COPY recursed = 0;
419 if (debugging && ++debugging < 500000)
421 SetThreadPriority (hMainThread, THREAD_PRIORITY_NORMAL);
425 /* If we've already exited, don't do anything here. Returning 1
426 tells Windows to keep looking for an exception handler. */
430 /* Coerce win32 value to posix value. */
431 switch (e->ExceptionCode)
433 case STATUS_FLOAT_DENORMAL_OPERAND:
434 case STATUS_FLOAT_DIVIDE_BY_ZERO:
435 case STATUS_FLOAT_INEXACT_RESULT:
436 case STATUS_FLOAT_INVALID_OPERATION:
437 case STATUS_FLOAT_OVERFLOW:
438 case STATUS_FLOAT_STACK_CHECK:
439 case STATUS_FLOAT_UNDERFLOW:
440 case STATUS_INTEGER_DIVIDE_BY_ZERO:
441 case STATUS_INTEGER_OVERFLOW:
445 case STATUS_ILLEGAL_INSTRUCTION:
446 case STATUS_PRIVILEGED_INSTRUCTION:
447 case STATUS_NONCONTINUABLE_EXCEPTION:
455 case STATUS_ACCESS_VIOLATION:
456 case STATUS_DATATYPE_MISALIGNMENT:
457 case STATUS_ARRAY_BOUNDS_EXCEEDED:
458 case STATUS_GUARD_PAGE_VIOLATION:
459 case STATUS_IN_PAGE_ERROR:
460 case STATUS_NO_MEMORY:
461 case STATUS_INVALID_DISPOSITION:
462 case STATUS_STACK_OVERFLOW:
466 case STATUS_CONTROL_C_EXIT:
470 case STATUS_INVALID_HANDLE:
471 /* CloseHandle will throw this exception if it is given an
472 invalid handle. We don't care about the exception; we just
473 want CloseHandle to return an error. This can be revisited
474 if gcc ever supports Windows style structured exception
479 /* If we don't recognize the exception, we have to assume that
480 we are doing structured exception handling, and we let
481 something else handle it. */
485 debug_printf ("In cygwin_except_handler exc %p at %p sp %p", e->ExceptionCode, in->Eip, in->Esp);
486 debug_printf ("In cygwin_except_handler sig = %d at %p", sig, in->Eip);
488 if (myself->getsig (sig).sa_mask & SIGTOMASK (sig))
489 syscall_printf ("signal %d, masked %p", sig, myself->getsig (sig).sa_mask);
491 debug_printf ("In cygwin_except_handler calling %p",
492 myself->getsig (sig).sa_handler);
494 DWORD *ebp = (DWORD *)in->Esp;
495 for (DWORD *bpend = (DWORD *) __builtin_frame_address (0); ebp > bpend; ebp--)
496 if (*ebp == in->SegCs && ebp[-1] == in->Eip)
502 if (!myself->progname[0]
503 || GetCurrentThreadId () == sigtid
504 || (void *) myself->getsig (sig).sa_handler == (void *) SIG_DFL
505 || (void *) myself->getsig (sig).sa_handler == (void *) SIG_IGN
506 || (void *) myself->getsig (sig).sa_handler == (void *) SIG_ERR)
508 /* Print the exception to the console */
511 for (int i = 0; status_info[i].name; i++)
513 if (status_info[i].code == e->ExceptionCode)
515 if (!myself->ppid_handle)
516 system_printf ("Exception: %s", status_info[i].name);
522 /* Another exception could happen while tracing or while exiting.
523 Only do this once. */
525 system_printf ("Error while dumping state (probably corrupted stack)");
528 if (try_to_debug (0))
534 open_stackdumpfile ();
536 stackdump ((DWORD) ebp, 0, 1);
539 signal_exit (0x80 | sig); // Flag signal + core dump
542 sig_send (NULL, sig, (DWORD) ebp, 1); // Signal myself
545 #endif /* __i386__ */
547 #ifndef HAVE_STACK_TRACE
551 system_printf ("Stack trace not yet supported on this machine.");
555 /* Utilities to call a user supplied exception handler. */
557 #define SIG_NONMASKABLE (SIGTOMASK (SIGKILL) | SIGTOMASK (SIGSTOP))
560 #define HAVE_CALL_HANDLER
562 /* Non-raceable sigsuspend
563 * Note: This implementation is based on the Single UNIX Specification
564 * man page. This indicates that sigsuspend always returns -1 and that
565 * attempts to block unblockable signals will be silently ignored.
566 * This is counter to what appears to be documented in some UNIX
567 * man pages, e.g. Linux.
570 handle_sigsuspend (sigset_t tempmask)
572 sig_dispatch_pending ();
573 sigframe thisframe (mainthread);
574 sigset_t oldmask = myself->getsigmask (); // Remember for restoration
576 set_process_mask (tempmask & ~SIG_NONMASKABLE);// Let signals we're
577 // interested in through.
578 sigproc_printf ("old mask %x, new mask %x", oldmask, tempmask);
580 pthread_testcancel ();
581 pthread::cancelable_wait (signal_arrived, INFINITE);
583 set_sig_errno (EINTR); // Per POSIX
585 /* A signal dispatch function will have been added to our stack and will
586 be hit eventually. Set the old mask to be restored when the signal
589 sigsave.oldmask = oldmask; // Will be restored by signal handler
593 extern DWORD exec_exit; // Possible exit value for exec
597 sig_handle_tty_stop (int sig)
599 /* Silently ignore attempts to suspend if there is no accomodating
600 cygwin parent to deal with this behavior. */
601 if (!myself->ppid_handle)
603 myself->process_state &= ~PID_STOPPED;
607 myself->stopsig = sig;
608 /* See if we have a living parent. If so, send it a special signal.
609 It will figure out exactly which pid has stopped by scanning
610 its list of subprocesses. */
611 if (my_parent_is_alive ())
613 pinfo parent (myself->ppid);
614 if (!(parent->getsig (SIGCHLD).sa_flags & SA_NOCLDSTOP))
615 sig_send (parent, SIGCHLD);
617 sigproc_printf ("process %d stopped by signal %d, myself->ppid_handle %p",
618 myself->pid, sig, myself->ppid_handle);
619 if (WaitForSingleObject (sigCONT, INFINITE) != WAIT_OBJECT_0)
620 api_fatal ("WaitSingleObject failed, %E");
621 (void) ResetEvent (sigCONT);
627 interruptible (DWORD pc, int testvalid = 0)
630 MEMORY_BASIC_INFORMATION m;
632 memset (&m, 0, sizeof m);
633 if (!VirtualQuery ((LPCVOID) pc, &m, sizeof m))
634 sigproc_printf ("couldn't get memory info, pc %p, %E", pc);
636 char *checkdir = (char *) alloca (windows_system_directory_length + 4);
637 memset (checkdir, 0, sizeof (checkdir));
639 # define h ((HMODULE) m.AllocationBase)
640 /* Apparently Windows 95 can sometimes return bogus addresses from
641 GetThreadContext. These resolve to a strange allocation base.
642 These should *never* be treated as interruptible. */
643 if (!h || m.State != MEM_COMMIT)
646 res = 1; /* All we wanted to know was if this was a valid module. */
647 else if (h == user_data->hmodule)
649 else if (h == cygwin_hmodule)
651 else if (!GetModuleFileName (h, checkdir, windows_system_directory_length + 2))
654 res = !strncasematch (windows_system_directory, checkdir,
655 windows_system_directory_length);
656 sigproc_printf ("pc %p, h %p, interruptible %d, testvalid %d", pc, h, res, testvalid);
662 sigthread::get_winapi_lock (int test)
665 return !InterlockedExchange (&winapi_lock, 1);
667 /* Need to do a busy loop because we can't block or a potential SuspendThread
669 while (InterlockedExchange (&winapi_lock, 1))
670 low_priority_sleep (0);
675 sigthread::release_winapi_lock ()
677 /* Assumes that we have the lock. */
678 InterlockedExchange (&winapi_lock, 0);
681 static void __stdcall interrupt_setup (int sig, void *handler, DWORD retaddr,
682 DWORD *retaddr_on_stack,
683 struct sigaction& siga)
684 __attribute__((regparm(3)));
685 static void __stdcall
686 interrupt_setup (int sig, void *handler, DWORD retaddr, DWORD *retaddr_on_stack,
687 struct sigaction& siga)
689 sigsave.retaddr = retaddr;
690 sigsave.retaddr_on_stack = retaddr_on_stack;
691 /* FIXME: Not multi-thread aware */
692 sigsave.oldmask = myself->getsigmask ();
693 sigsave.newmask = sigsave.oldmask | siga.sa_mask | SIGTOMASK (sig);
694 sigsave.sa_flags = siga.sa_flags;
695 sigsave.func = (void (*)(int)) handler;
696 sigsave.saved_errno = -1; // Flag: no errno to save
697 if (handler == sig_handle_tty_stop)
700 myself->process_state |= PID_STOPPED;
702 /* Clear any waiting threads prior to dispatching to handler function */
703 proc_subproc (PROC_CLEARWAIT, 1);
704 int res = SetEvent (signal_arrived); // For an EINTR case
705 sigsave.sig = sig; // Should ALWAYS be last thing set to avoid a race
706 sigproc_printf ("armed signal_arrived %p, res %d", signal_arrived, res);
709 static bool interrupt_now (CONTEXT *, int, void *, struct sigaction&) __attribute__((regparm(3)));
711 interrupt_now (CONTEXT *ctx, int sig, void *handler, struct sigaction& siga)
713 interrupt_setup (sig, handler, ctx->Eip, 0, siga);
714 ctx->Eip = (DWORD) sigdelayed;
715 SetThreadContext (myself->getthread2signal (), ctx); /* Restart the thread in a new location */
720 signal_fixup_after_fork ()
725 if (sigsave.retaddr_on_stack)
727 *sigsave.retaddr_on_stack = sigsave.retaddr;
728 set_process_mask (sigsave.oldmask);
735 signal_fixup_after_exec ()
737 /* Set up child's signal handlers */
738 for (int i = 0; i < NSIG; i++)
740 myself->getsig (i).sa_mask = 0;
741 if (myself->getsig (i).sa_handler != SIG_IGN)
742 myself->getsig (i).sa_handler = SIG_DFL;
746 static int interrupt_on_return (sigthread *, int, void *, struct sigaction&) __attribute__((regparm(3)));
748 interrupt_on_return (sigthread *th, int sig, void *handler, struct sigaction& siga)
751 DWORD ebp = th->frame;
756 thestack.init (ebp, 0, 1); /* Initialize from the input CONTEXT */
757 for (i = 0; i < 32 && thestack++ ; i++)
758 if (th->exception || interruptible (thestack.sf.AddrReturn.Offset))
760 DWORD *addr_retaddr = ((DWORD *)thestack.sf.AddrFrame.Offset) + 1;
761 if (*addr_retaddr == thestack.sf.AddrReturn.Offset)
763 interrupt_setup (sig, handler, *addr_retaddr, addr_retaddr, siga);
764 *addr_retaddr = (DWORD) sigdelayed;
769 sigproc_printf ("couldn't find a stack frame, i %d", i);
773 extern "C" void __stdcall
774 set_sig_errno (int e)
777 sigsave.saved_errno = e;
778 // sigproc_printf ("errno %d", e);
781 static int setup_handler (int, void *, struct sigaction&) __attribute__((regparm(3)));
783 setup_handler (int sig, void *handler, struct sigaction& siga)
786 bool interrupted = false;
787 sigthread *th = NULL; // Initialization needed to shut up gcc
793 for (int i = 0; i < CALL_HANDLER_RETRY; i++)
798 EnterCriticalSection (&mainthread.lock);
799 if (mainthread.frame)
806 LeaveCriticalSection (&mainthread.lock);
808 if (!mainthread.get_winapi_lock (1))
811 hth = myself->getthread2signal ();
814 /* Suspend the thread which will receive the signal. But first ensure that
815 this thread doesn't have any mutos. (FIXME: Someday we should just grab
816 all of the mutos rather than checking for them)
817 For Windows 95, we also have to ensure that the addresses returned by GetThreadContext
819 If one of these conditions is not true we loop for a fixed number of times
820 since we don't want to stall the signal handler. FIXME: Will this result in
822 If the thread is already suspended (which can occur when a program has called
823 SuspendThread on itself then just queue the signal. */
825 EnterCriticalSection (&mainthread.lock);
826 sigproc_printf ("suspending mainthread");
827 res = SuspendThread (hth);
828 /* Just release the lock now since we hav suspended the main thread and it
829 definitely can't be grabbing it now. This will have to change, of course,
830 if/when we can send signals to other than the main thread. */
831 LeaveCriticalSection (&mainthread.lock);
833 /* Just set pending if thread is already suspended */
836 mainthread.release_winapi_lock ();
837 (void) ResumeThread (hth);
841 mainthread.release_winapi_lock ();
842 if (mainthread.frame)
843 goto resume_thread; /* We just got the frame. What are the odds?
844 Just loop and we'll hopefully pick it up on
845 the next pass through. */
848 /* FIXME: Make multi-thread aware */
849 for (m = muto_start.next; m != NULL; m = m->next)
850 if (m->unstable () || m->owner () == mainthread.id)
852 sigproc_printf ("suspended thread owns a muto (%s)", m->name);
856 if (mainthread.frame)
860 cx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
861 if (!GetThreadContext (hth, &cx))
863 system_printf ("couldn't get context of main thread, %E");
869 if ((DWORD) prio != INFINITE)
871 /* Reset the priority so we can finish this off quickly. */
872 SetThreadPriority (GetCurrentThread (), WAIT_SIG_PRIORITY);
878 interrupted = interrupt_on_return (th, sig, handler, siga);
879 LeaveCriticalSection (&th->lock);
881 else if (interruptible (cx.Eip))
882 interrupted = interrupt_now (&cx, sig, handler, siga);
886 res = ResumeThread (hth);
891 if ((DWORD) prio != INFINITE && !mainthread.frame)
892 prio = low_priority_sleep (SLEEP_0_STAY_LOW);
893 sigproc_printf ("couldn't interrupt. trying again.");
899 if ((DWORD) prio != INFINITE)
900 SetThreadPriority (GetCurrentThread (), WAIT_SIG_PRIORITY);
901 sigproc_printf ("signal successfully delivered");
904 sigproc_printf ("returning %d", interrupted);
909 #ifndef HAVE_CALL_HANDLER
910 #error "Need to supply machine dependent setup_handler"
913 /* Keyboard interrupt handler. */
915 ctrl_c_handler (DWORD type)
917 static bool saw_close;
919 /* Return FALSE to prevent an "End task" dialog box from appearing
920 for each Cygwin process window that's open when the computer
921 is shut down or console window is closed. */
923 if (type == CTRL_SHUTDOWN_EVENT)
926 /* Don't send a signal. Only NT service applications and their child
927 processes will receive this event and the services typically already
928 handle the shutdown action when getting the SERVICE_CONTROL_SHUTDOWN
930 sig_send (NULL, SIGTERM);
935 if (myself->ctty != -1
936 && (type == CTRL_CLOSE_EVENT || (!saw_close && type == CTRL_LOGOFF_EVENT)))
938 if (type == CTRL_CLOSE_EVENT)
940 sig_send (NULL, SIGHUP);
944 /* If we are a stub and the new process has a pinfo structure, let it
945 handle this signal. */
946 if (dwExeced && pinfo (dwExeced))
949 /* We're only the process group leader when we have a valid pinfo structure.
950 If we don't have one, then the parent "stub" will handle the signal. */
951 if (!pinfo (cygwin_pid (GetCurrentProcessId ())))
954 tty_min *t = cygwin_shared->tty.get_tty (myself->ctty);
955 /* Ignore this if we're not the process group leader since it should be handled
956 *by* the process group leader. */
957 if (myself->ctty != -1 && t->getpgid () == myself->pid &&
958 (GetTickCount () - t->last_ctrl_c) >= MIN_CTRL_C_SLOP)
959 /* Otherwise we just send a SIGINT to the process group and return TRUE (to indicate
960 that we have handled the signal). At this point, type should be
961 a CTRL_C_EVENT or CTRL_BREAK_EVENT. */
963 t->last_ctrl_c = GetTickCount ();
964 kill (-myself->pid, SIGINT);
965 t->last_ctrl_c = GetTickCount ();
972 /* Set the signal mask for this process.
973 Note that some signals are unmaskable, as in UNIX. */
974 extern "C" void __stdcall
975 set_process_mask (sigset_t newmask)
977 sigframe thisframe (mainthread);
978 mask_sync->acquire (INFINITE);
979 sigset_t oldmask = myself->getsigmask ();
980 newmask &= ~SIG_NONMASKABLE;
981 sigproc_printf ("old mask = %x, new mask = %x", myself->getsigmask (), newmask);
982 myself->setsigmask (newmask); // Set a new mask
983 mask_sync->release ();
984 if (oldmask != newmask)
985 sig_dispatch_pending ();
987 sigproc_printf ("not calling sig_dispatch_pending. sigtid %p current %p",
988 sigtid, GetCurrentThreadId ());
997 sigproc_printf ("signal %d", sig);
999 struct sigaction thissig = myself->getsig (sig);
1000 void *handler = (void *) thissig.sa_handler;
1002 myself->rusage_self.ru_nsignals++;
1004 /* Clear pending SIGCONT on stop signals */
1005 if (sig == SIGSTOP || sig == SIGTSTP || sig == SIGTTIN || sig == SIGTTOU)
1006 sig_clear (SIGCONT);
1014 /* FIXME: Should we still do this if SIGCONT has a handler? */
1017 DWORD stopped = myself->process_state & PID_STOPPED;
1018 myself->stopsig = 0;
1019 myself->process_state &= ~PID_STOPPED;
1020 /* Clear pending stop signals */
1021 sig_clear (SIGSTOP);
1022 sig_clear (SIGTSTP);
1023 sig_clear (SIGTTIN);
1024 sig_clear (SIGTTOU);
1027 /* process pending signals */
1029 sig_dispatch_pending ();
1035 __small_sprintf (sigmsg, "cygwin: signal %d\n", sig);
1036 OutputDebugString (sigmsg);
1039 if (handler == (void *) SIG_DFL)
1041 if (sig == SIGCHLD || sig == SIGIO || sig == SIGCONT || sig == SIGWINCH
1042 || sig == SIGURG || (hExeced && sig == SIGINT))
1044 sigproc_printf ("default signal %d ignored", sig);
1048 if (sig == SIGTSTP || sig == SIGTTIN || sig == SIGTTOU)
1054 if (handler == (void *) SIG_IGN)
1056 sigproc_printf ("signal %d ignored", sig);
1060 if (handler == (void *) SIG_ERR)
1066 /* Eat multiple attempts to STOP */
1067 if (ISSTATE (myself, PID_STOPPED))
1069 handler = (void *) sig_handle_tty_stop;
1070 thissig = myself->getsig (SIGSTOP);
1073 /* Dispatch to the appropriate function. */
1074 sigproc_printf ("signal %d, about to call %p", sig, handler);
1075 rc = setup_handler (sig, handler, thissig);
1078 sigproc_printf ("returning %d", rc);
1082 if (sig == SIGQUIT || sig == SIGABRT)
1085 c.ContextFlags = CONTEXT_FULL;
1086 GetThreadContext (hMainThread, &c);
1087 if (!try_to_debug ())
1088 stackdump (c.Ebp, 1, 1);
1091 sigproc_printf ("signal %d, about to call do_exit", sig);
1096 CRITICAL_SECTION NO_COPY exit_lock;
1098 /* Cover function to `do_exit' to handle exiting even in presence of more
1099 exceptions. We used to call exit, but a SIGSEGV shouldn't cause atexit
1102 signal_exit (int rc)
1104 EnterCriticalSection (&exit_lock);
1105 rc = EXIT_SIGNAL | (rc << 8);
1109 /* We'd like to stop the main thread from executing but when we do that it
1110 causes random, inexplicable hangs. So, instead, we set up the priority
1111 of this thread really high so that it should do its thing and then exit. */
1112 (void) SetThreadPriority (hMainThread, THREAD_PRIORITY_IDLE);
1113 (void) SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL);
1115 /* Unlock any main thread mutos since we're executing with prejudice. */
1117 for (m = muto_start.next; m != NULL; m = m->next)
1118 if (m->unstable () || m->owner () == mainthread.id)
1121 user_data->resourcelocks->Delete ();
1122 user_data->resourcelocks->Init ();
1125 TerminateProcess (hExeced, rc);
1127 sigproc_printf ("about to call do_exit (%x)", rc);
1128 (void) SetEvent (signal_arrived);
1132 HANDLE NO_COPY title_mutex = NULL;
1138 char mutex_name[MAX_PATH];
1139 /* title_mutex protects modification of console title. It's necessary
1140 while finding console window handle */
1142 if (!(title_mutex = CreateMutex (&sec_all_nih, FALSE,
1143 name = shared_name (mutex_name,
1144 "title_mutex", 0))))
1145 api_fatal ("can't create title mutex '%s', %E", name);
1147 ProtectHandle (title_mutex);
1148 new_muto (mask_sync);
1149 windows_system_directory[0] = '\0';
1150 (void) GetSystemDirectory (windows_system_directory, sizeof (windows_system_directory) - 2);
1151 char *end = strchr (windows_system_directory, '\0');
1152 if (end == windows_system_directory)
1153 api_fatal ("can't find windows system directory");
1154 if (end[-1] != '\\')
1159 windows_system_directory_length = end - windows_system_directory;
1160 debug_printf ("windows_system_directory '%s', windows_system_directory_length %d",
1161 windows_system_directory, windows_system_directory_length);
1162 debug_printf ("cygwin_hmodule %p", cygwin_hmodule);
1163 InitializeCriticalSection (&exit_lock);
1167 events_terminate (void)
1173 static int __stdcall
1174 call_signal_handler_now ()
1178 sigproc_printf ("call_signal_handler_now called when no signal active");
1182 int sa_flags = sigsave.sa_flags;
1183 sigproc_printf ("sa_flags %p", sa_flags);
1184 *sigsave.retaddr_on_stack = sigsave.retaddr;
1186 return sa_flags & SA_RESTART;
1188 /* This kludge seems to keep a copy of call_signal_handler_now around
1189 even when compiling with -finline-functions. */
1190 static int __stdcall call_signal_handler_now_dummy ()
1191 __attribute__((alias ("call_signal_handler_now")));
1195 sigframe::call_signal_handler ()
1197 return unregister () ? call_signal_handler_now () : 0;
1200 #define pid_offset (unsigned)(((_pinfo *)NULL)->pid)
1203 reset_signal_arrived ()
1205 (void) ResetEvent (signal_arrived);
1206 sigproc_printf ("reset signal_arrived");
1210 #define errno ((DWORD volatile) _impure_ptr) + (((char *) &_impure_ptr->_errno) - ((char *) _impure_ptr))
1212 __attribute__((const, used, noinline)) static void
1213 unused_sig_wrapper ()
1215 /* Signal cleanup stuff. Cleans up stack (too bad that we didn't
1216 prototype signal handlers as __stdcall), calls _set_process_mask
1217 to restore any mask, restores any potentially clobbered registers
1218 and returns to original caller. */
1219 __asm__ volatile ("\n\
1222 addl $4,%%esp # Remove argument \n\
1223 call _set_process_mask@4 \n\
1225 cmpl $0,%4 # Did a signal come in? \n\
1226 jz 1f # No, if zero \n\
1228 movl %%esp,%%ebp \n\
1229 movl %%eax,36(%%ebp) # Restore return address \n\
1232 1: popl %%eax # saved errno \n\
1233 testl %%eax,%%eax # Is it < 0 \n\
1234 jl 2f # yup. ignore it \n\
1236 movl %%eax,(%%ebx) \n\
1249 pushl %2 # original return address \n\
1252 movl %%esp,%%ebp \n\
1260 pushl %6 # saved errno \n\
1261 3: pushl %3 # oldmask \n\
1262 pushl %4 # signal argument \n\
1263 pushl $_sigreturn \n\
1265 call _reset_signal_arrived@0 \n\
1266 pushl %5 # signal number \n\
1267 pushl %7 # newmask \n\
1269 call _set_process_mask@4 \n\
1270 movl $0,%0 # zero the signal number as a \n\
1271 # flag to the signal handler thread\n\
1272 # that it is ok to set up sigsave\n\
1276 " : "=m" (sigsave.sig): "X" ((char *) &_impure_ptr->_errno),
1277 "g" (sigsave.retaddr), "g" (sigsave.oldmask), "g" (sigsave.sig),
1278 "g" (sigsave.func), "g" (sigsave.saved_errno), "g" (sigsave.newmask)