newlib-cygwin/winsup/cygwin/exceptions.cc

1271 lines
34 KiB
C++
Raw Normal View History

2000-02-18 03:38:33 +08:00
/* exceptions.cc
2002-01-14 04:03:03 +08:00
Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
2000-02-18 03:38:33 +08:00
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#include "winsup.h"
#include <imagehlp.h>
2000-02-18 03:38:33 +08:00
#include <errno.h>
#include <stdlib.h>
2000-02-18 03:38:33 +08:00
#include "exceptions.h"
#include "sync.h"
#include "sigproc.h"
#include "pinfo.h"
#include "cygerrno.h"
#include "perthread.h"
#include "shared_info.h"
#include "perprocess.h"
#include "security.h"
2000-02-18 03:38:33 +08:00
#define CALL_HANDLER_RETRY 20
char debugger_command[2 * MAX_PATH + 20];
2000-02-18 03:38:33 +08:00
extern "C" {
static int handle_exceptions (EXCEPTION_RECORD *, void *, CONTEXT *, void *);
extern void sigreturn ();
extern void sigdelayed ();
extern void sigdelayed0 ();
2000-02-18 03:38:33 +08:00
extern void siglast ();
extern DWORD __no_sig_start, __no_sig_end;
2000-02-18 03:38:33 +08:00
};
extern DWORD sigtid;
extern HANDLE hExeced;
extern DWORD dwExeced;
2000-02-18 03:38:33 +08:00
static BOOL WINAPI ctrl_c_handler (DWORD);
2000-07-27 04:36:19 +08:00
static void signal_exit (int) __attribute__ ((noreturn));
static char windows_system_directory[1024];
static size_t windows_system_directory_length;
2000-02-18 03:38:33 +08:00
/* This is set to indicate that we have already exited. */
static NO_COPY int exit_already = 0;
static NO_COPY muto *mask_sync = NULL;
HMODULE NO_COPY cygwin_hmodule;
2000-02-18 03:38:33 +08:00
NO_COPY static struct
2000-02-18 03:38:33 +08:00
{
unsigned int code;
const char *name;
} status_info[] =
2000-02-18 03:38:33 +08:00
{
#define X(s) s, #s
{ X (STATUS_ABANDONED_WAIT_0) },
{ X (STATUS_ACCESS_VIOLATION) },
{ X (STATUS_ARRAY_BOUNDS_EXCEEDED) },
{ X (STATUS_BREAKPOINT) },
{ X (STATUS_CONTROL_C_EXIT) },
{ X (STATUS_DATATYPE_MISALIGNMENT) },
{ X (STATUS_FLOAT_DENORMAL_OPERAND) },
{ X (STATUS_FLOAT_DIVIDE_BY_ZERO) },
{ X (STATUS_FLOAT_INEXACT_RESULT) },
{ X (STATUS_FLOAT_INVALID_OPERATION) },
{ X (STATUS_FLOAT_OVERFLOW) },
{ X (STATUS_FLOAT_STACK_CHECK) },
{ X (STATUS_FLOAT_UNDERFLOW) },
{ X (STATUS_GUARD_PAGE_VIOLATION) },
{ X (STATUS_ILLEGAL_INSTRUCTION) },
{ X (STATUS_INTEGER_DIVIDE_BY_ZERO) },
{ X (STATUS_INTEGER_OVERFLOW) },
{ X (STATUS_INVALID_DISPOSITION) },
{ X (STATUS_IN_PAGE_ERROR) },
{ X (STATUS_NONCONTINUABLE_EXCEPTION) },
{ X (STATUS_NO_MEMORY) },
{ X (STATUS_PENDING) },
{ X (STATUS_PRIVILEGED_INSTRUCTION) },
{ X (STATUS_SINGLE_STEP) },
{ X (STATUS_STACK_OVERFLOW) },
{ X (STATUS_TIMEOUT) },
{ X (STATUS_USER_APC) },
{ X (STATUS_WAIT_0) },
{ 0, 0 }
#undef X
};
/* Initialization code. */
#ifdef __i386__
// Set up the exception handler for the current thread. The PowerPC & Mips
// use compiler generated tables to set up the exception handlers for each
// region of code, and the kernel walks the call list until it finds a region
// of code that handles exceptions. The x86 on the other hand uses segment
// register fs, offset 0 to point to the current exception handler.
asm (".equ __except_list,0");
extern exception_list *_except_list asm ("%fs:__except_list");
static void
init_exception_handler (exception_list *el)
{
el->handler = handle_exceptions;
el->prev = _except_list;
_except_list = el;
}
#endif
void
early_stuff_init ()
2000-02-18 03:38:33 +08:00
{
(void) SetConsoleCtrlHandler (ctrl_c_handler, FALSE);
if (!SetConsoleCtrlHandler (ctrl_c_handler, TRUE))
system_printf ("SetConsoleCtrlHandler failed, %E");
2000-02-18 03:38:33 +08:00
/* Initialize global security attribute stuff */
sec_none.nLength = sec_none_nih.nLength =
sec_all.nLength = sec_all_nih.nLength = sizeof (SECURITY_ATTRIBUTES);
sec_none.bInheritHandle = sec_all.bInheritHandle = TRUE;
sec_none_nih.bInheritHandle = sec_all_nih.bInheritHandle = FALSE;
sec_none.lpSecurityDescriptor = sec_none_nih.lpSecurityDescriptor = NULL;
sec_all.lpSecurityDescriptor = sec_all_nih.lpSecurityDescriptor =
get_null_sd ();
}
extern "C" void
init_exceptions (exception_list *el)
{
init_exception_handler (el);
2000-02-18 03:38:33 +08:00
}
extern "C" void
error_start_init (const char *buf)
{
if (!buf || !*buf)
{
debugger_command[0] = '\0';
return;
}
char pgm[MAX_PATH + 1];
if (!GetModuleFileName (NULL, pgm, MAX_PATH))
strcpy (pgm, "cygwin1.dll");
for (char *p = strchr (pgm, '\\'); p; p = strchr (p, '\\'))
*p = '/';
2000-02-18 03:38:33 +08:00
__small_sprintf (debugger_command, "%s %s", buf, pgm);
2000-02-18 03:38:33 +08:00
}
static void
open_stackdumpfile ()
{
if (myself->progname[0])
{
const char *p;
/* write to progname.stackdump if possible */
if (!myself->progname[0])
p = "unknown";
else if ((p = strrchr (myself->progname, '\\')))
p++;
else
p = myself->progname;
char corefile[strlen (p) + sizeof (".stackdump")];
__small_sprintf (corefile, "%s.stackdump", p);
HANDLE h = CreateFile (corefile, GENERIC_WRITE, 0, &sec_none_nih,
CREATE_ALWAYS, 0, 0);
if (h != INVALID_HANDLE_VALUE)
{
if (!myself->ppid_handle)
system_printf ("Dumping stack trace to %s", corefile);
else
debug_printf ("Dumping stack trace to %s", corefile);
SetStdHandle (STD_ERROR_HANDLE, h);
}
}
}
2000-02-18 03:38:33 +08:00
/* Utilities for dumping the stack, etc. */
static void
exception (EXCEPTION_RECORD *e, CONTEXT *in)
{
const char *exception_name = NULL;
2000-02-18 03:38:33 +08:00
if (e)
{
for (int i = 0; status_info[i].name; i++)
{
if (status_info[i].code == e->ExceptionCode)
{
exception_name = status_info[i].name;
break;
}
}
}
#ifdef __i386__
#define HAVE_STATUS
if (exception_name)
small_printf ("Exception: %s at eip=%08x\r\n", exception_name, in->Eip);
else
small_printf ("Exception %d at eip=%08x\r\n", e->ExceptionCode, in->Eip);
small_printf ("eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\r\n",
in->Eax, in->Ebx, in->Ecx, in->Edx, in->Esi, in->Edi);
small_printf ("ebp=%08x esp=%08x program=%s\r\n",
in->Ebp, in->Esp, myself->progname);
small_printf ("cs=%04x ds=%04x es=%04x fs=%04x gs=%04x ss=%04x\r\n",
in->SegCs, in->SegDs, in->SegEs, in->SegFs, in->SegGs, in->SegSs);
#endif
#ifndef HAVE_STATUS
system_printf ("Had an exception");
#endif
}
#ifdef __i386__
/* Print a stack backtrace. */
#define HAVE_STACK_TRACE
/* A class for manipulating the stack. */
class stack_info
{
int walk (); /* Uses the "old" method */
char *next_offset () {return *((char **) sf.AddrFrame.Offset);}
bool needargs;
DWORD dummy_frame;
2000-02-18 03:38:33 +08:00
public:
STACKFRAME sf; /* For storing the stack information */
void init (DWORD, bool, bool); /* Called the first time that stack info is needed */
2000-02-18 03:38:33 +08:00
/* Postfix ++ iterates over the stack, returning zero when nothing is left. */
int operator ++(int) { return this->walk (); }
2000-02-18 03:38:33 +08:00
};
/* The number of parameters used in STACKFRAME */
#define NPARAMS (sizeof (thestack.sf.Params) / sizeof (thestack.sf.Params[0]))
2000-02-18 03:38:33 +08:00
/* This is the main stack frame info for this process. */
static NO_COPY stack_info thestack;
static signal_dispatch sigsave;
2000-02-18 03:38:33 +08:00
/* Initialize everything needed to start iterating. */
void
stack_info::init (DWORD ebp, bool wantargs, bool goodframe)
2000-02-18 03:38:33 +08:00
{
# define debp ((DWORD *) ebp)
memset (&sf, 0, sizeof (sf));
if (!goodframe)
sf.AddrFrame.Offset = ebp;
else
{
dummy_frame = ebp;
sf.AddrFrame.Offset = (DWORD) &dummy_frame;
}
sf.AddrReturn.Offset = debp[1];
2000-02-18 03:38:33 +08:00
sf.AddrFrame.Mode = AddrModeFlat;
needargs = wantargs;
# undef debp
2000-02-18 03:38:33 +08:00
}
/* Walk the stack by looking at successive stored 'bp' frames.
This is not foolproof. */
int
stack_info::walk ()
2000-02-18 03:38:33 +08:00
{
char **ebp;
if ((ebp = (char **) next_offset ()) == NULL)
2000-02-18 03:38:33 +08:00
return 0;
sf.AddrFrame.Offset = (DWORD) ebp;
sf.AddrPC.Offset = sf.AddrReturn.Offset;
2000-02-18 03:38:33 +08:00
if (!sf.AddrPC.Offset)
return 0; /* stack frames are exhausted */
/* The return address always follows the stack pointer */
sf.AddrReturn.Offset = (DWORD) *++ebp;
if (needargs)
/* The arguments follow the return address */
for (unsigned i = 0; i < NPARAMS; i++)
sf.Params[i] = (DWORD) *++ebp;
2000-02-18 03:38:33 +08:00
return 1;
}
static void
stackdump (DWORD ebp, int open_file, bool isexception)
2000-02-18 03:38:33 +08:00
{
extern unsigned long rlim_core;
if (rlim_core == 0UL)
return;
if (open_file)
open_stackdumpfile ();
2000-02-18 03:38:33 +08:00
int i;
thestack.init (ebp, 1, !isexception); /* Initialize from the input CONTEXT */
2000-02-18 03:38:33 +08:00
small_printf ("Stack trace:\r\nFrame Function Args\r\n");
for (i = 0; i < 16 && thestack++; i++)
2000-02-18 03:38:33 +08:00
{
small_printf ("%08x %08x ", thestack.sf.AddrFrame.Offset,
thestack.sf.AddrPC.Offset);
2000-02-18 03:38:33 +08:00
for (unsigned j = 0; j < NPARAMS; j++)
small_printf ("%s%08x", j == 0 ? " (" : ", ", thestack.sf.Params[j]);
2000-02-18 03:38:33 +08:00
small_printf (")\r\n");
}
small_printf ("End of stack trace%s",
i == 16 ? " (more stack frames may be present)" : "");
}
/* Temporary (?) function for external callers to get a stack dump */
extern "C" void
cygwin_stackdump ()
2000-02-18 03:38:33 +08:00
{
CONTEXT c;
c.ContextFlags = CONTEXT_FULL;
GetThreadContext (GetCurrentThread (), &c);
stackdump (c.Ebp, 0, 0);
2000-02-18 03:38:33 +08:00
}
#define TIME_TO_WAIT_FOR_DEBUGGER 10000
2000-02-18 03:38:33 +08:00
extern "C" int
try_to_debug (bool waitloop)
2000-02-18 03:38:33 +08:00
{
Throughout, change 'cygwin_shared.mount' to 'mount_table'. * child_info.h (child_info): Move shared_h, console_h to cygheap. Add mount_h. * cygheap.h (init_cygheap): Add shared_h, console_h. * cygheap.cc (init_cheap): Initialize heap at a fixed location after the shared memory regions. Initialize cygheap->user name here. * dcrt0.cc (dll_crt0_1): Call getpagesize () to initialize constants. Remove cygheap_init since it is done in shared_init now. (_dll_crt0): Initialize mount_h, remove shared_h and console_h initialization. * fhandler_console.cc (console_shared_h): Eliminate. (get_tty_stuff): Use cygheap->console_h rather than console_shared_h. * heap.cc (heap_init): Use page size constant calculated earlier in initialization. * shared.cc: Eliminate cygwin_shared_h. Add cygwin_mount_h. (mount_table_init): New function for initializing a user mount table. (open_shared_file_map): Use constant for shared memory region. Initialize cygheap and mount table here. (open_shared): Improve debugging output. (shared_info::initialize): Eliminate call to mount.init. (shared_terminate): Use cygheap->shared_h. Close cygwin_mount_h. (open_shared_file_map): Eliminate. * shared_info.h (mount_info): Add a version field. (shared_align_past): New macro for calculating location for shared memory regions. * sigproc.cc (init_child_info): Eliminate shared_h, console_h. * spawn.cc (spawn_guts): Pass on cygwin_mount_h iff not a different user. * syscalls.cc (system_info): New global holding system memory defaults. (getpagesize): Use system_info. * uinfo.cc (internal_getlogin): Only fill in user name if nonexistent. * winsup.h: Declare system_info. * passwd.cc (read_etc_passwd): Use cygheap->user.name () rather than retrieving the name again.
2001-01-28 13:51:15 +08:00
debug_printf ("debugger_command '%s'", debugger_command);
if (*debugger_command == '\0' || being_debugged ())
2000-02-18 03:38:33 +08:00
return 0;
__small_sprintf (strchr (debugger_command, '\0'), " %u", GetCurrentProcessId ());
SetThreadPriority (hMainThread, THREAD_PRIORITY_HIGHEST);
PROCESS_INFORMATION pi = {NULL, 0, 0, 0};
2000-02-18 03:38:33 +08:00
STARTUPINFO si = {0, NULL, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL};
2000-02-18 03:38:33 +08:00
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.dwFlags = 0;
si.cb = sizeof (si);
/* FIXME: need to know handles of all running threads to
suspend_all_threads_except (current_thread_id);
*/
/* if any of these mutexes is owned, we will fail to start any cygwin app
until trapped app exits */
ReleaseMutex (title_mutex);
/* prevent recursive exception handling */
char* rawenv = GetEnvironmentStrings () ;
for (char* p = rawenv; *p != '\0'; p = strchr (p, '\0') + 1)
{
if (strncmp (p, "CYGWIN=", sizeof ("CYGWIN=") - 1) == 0)
{
char* q = strstr (p, "error_start") ;
/* replace 'error_start=...' with '_rror_start=...' */
if (q) *q = '_' ;
SetEnvironmentVariable ("CYGWIN", p + sizeof ("CYGWIN=")) ;
break ;
}
}
BOOL dbg;
2000-02-18 03:38:33 +08:00
dbg = CreateProcess (NULL,
debugger_command,
NULL,
NULL,
FALSE,
CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
NULL,
NULL,
&si,
&pi);
if (!dbg)
system_printf ("Failed to start debugger: %E");
else
2000-02-18 03:38:33 +08:00
{
SetThreadPriority (hMainThread, THREAD_PRIORITY_IDLE);
if (!waitloop)
return 1;
while (!being_debugged ())
/* spin */;
Sleep (4000);
small_printf ("*** continuing from debugger call\n");
2000-02-18 03:38:33 +08:00
}
/* FIXME: need to know handles of all running threads to
resume_all_threads_except (current_thread_id);
*/
return 0;
2000-02-18 03:38:33 +08:00
}
/* Main exception handler. */
static int
handle_exceptions (EXCEPTION_RECORD *e, void *, CONTEXT *in, void *)
2000-02-18 03:38:33 +08:00
{
int sig;
static int NO_COPY debugging = 0;
static int NO_COPY recursed = 0;
if (debugging && ++debugging < 500000)
{
SetThreadPriority (hMainThread, THREAD_PRIORITY_NORMAL);
return 0;
}
2000-02-18 03:38:33 +08:00
/* If we've already exited, don't do anything here. Returning 1
tells Windows to keep looking for an exception handler. */
if (exit_already)
return 1;
/* Coerce win32 value to posix value. */
switch (e->ExceptionCode)
{
case STATUS_FLOAT_DENORMAL_OPERAND:
case STATUS_FLOAT_DIVIDE_BY_ZERO:
case STATUS_FLOAT_INEXACT_RESULT:
case STATUS_FLOAT_INVALID_OPERATION:
case STATUS_FLOAT_OVERFLOW:
case STATUS_FLOAT_STACK_CHECK:
case STATUS_FLOAT_UNDERFLOW:
case STATUS_INTEGER_DIVIDE_BY_ZERO:
case STATUS_INTEGER_OVERFLOW:
sig = SIGFPE;
break;
case STATUS_ILLEGAL_INSTRUCTION:
case STATUS_PRIVILEGED_INSTRUCTION:
case STATUS_NONCONTINUABLE_EXCEPTION:
sig = SIGILL;
break;
case STATUS_TIMEOUT:
sig = SIGALRM;
break;
case STATUS_ACCESS_VIOLATION:
case STATUS_DATATYPE_MISALIGNMENT:
case STATUS_ARRAY_BOUNDS_EXCEEDED:
case STATUS_GUARD_PAGE_VIOLATION:
case STATUS_IN_PAGE_ERROR:
case STATUS_NO_MEMORY:
case STATUS_INVALID_DISPOSITION:
case STATUS_STACK_OVERFLOW:
sig = SIGSEGV;
break;
case STATUS_CONTROL_C_EXIT:
sig = SIGINT;
break;
case STATUS_INVALID_HANDLE:
/* CloseHandle will throw this exception if it is given an
invalid handle. We don't care about the exception; we just
want CloseHandle to return an error. This can be revisited
if gcc ever supports Windows style structured exception
handling. */
return 0;
default:
/* If we don't recognize the exception, we have to assume that
we are doing structured exception handling, and we let
something else handle it. */
return 1;
}
debug_printf ("In cygwin_except_handler exc %p at %p sp %p", e->ExceptionCode, in->Eip, in->Esp);
debug_printf ("In cygwin_except_handler sig = %d at %p", sig, in->Eip);
if (myself->getsig (sig).sa_mask & SIGTOMASK (sig))
syscall_printf ("signal %d, masked %p", sig, myself->getsig (sig).sa_mask);
2000-02-18 03:38:33 +08:00
debug_printf ("In cygwin_except_handler calling %p",
myself->getsig (sig).sa_handler);
DWORD *ebp = (DWORD *)in->Esp;
for (DWORD *bpend = (DWORD *) __builtin_frame_address (0); ebp > bpend; ebp--)
if (*ebp == in->SegCs && ebp[-1] == in->Eip)
{
ebp -= 2;
break;
}
2000-02-18 03:38:33 +08:00
if (!myself->progname[0]
|| GetCurrentThreadId () == sigtid
|| (void *) myself->getsig (sig).sa_handler == (void *) SIG_DFL
|| (void *) myself->getsig (sig).sa_handler == (void *) SIG_IGN
|| (void *) myself->getsig (sig).sa_handler == (void *) SIG_ERR)
2000-02-18 03:38:33 +08:00
{
/* Print the exception to the console */
if (e)
{
for (int i = 0; status_info[i].name; i++)
{
if (status_info[i].code == e->ExceptionCode)
{
if (!myself->ppid_handle)
system_printf ("Exception: %s", status_info[i].name);
2000-02-18 03:38:33 +08:00
break;
}
}
}
/* Another exception could happen while tracing or while exiting.
Only do this once. */
if (recursed++)
system_printf ("Error while dumping state (probably corrupted stack)");
2000-02-18 03:38:33 +08:00
else
{
if (try_to_debug (0))
{
debugging = 1;
return 0;
}
open_stackdumpfile ();
exception (e, in);
stackdump ((DWORD) ebp, 0, 1);
2000-02-18 03:38:33 +08:00
}
signal_exit (0x80 | sig); // Flag signal + core dump
2000-02-18 03:38:33 +08:00
}
sig_send (NULL, sig, (DWORD) ebp, 1); // Signal myself
2000-02-18 03:38:33 +08:00
return 0;
}
#endif /* __i386__ */
#ifndef HAVE_STACK_TRACE
void
stack (void)
{
system_printf ("Stack trace not yet supported on this machine.");
}
#endif
/* Utilities to call a user supplied exception handler. */
#define SIG_NONMASKABLE (SIGTOMASK (SIGKILL) | SIGTOMASK (SIGSTOP))
2000-02-18 03:38:33 +08:00
#ifdef __i386__
#define HAVE_CALL_HANDLER
/* Non-raceable sigsuspend
* Note: This implementation is based on the Single UNIX Specification
* man page. This indicates that sigsuspend always returns -1 and that
* attempts to block unblockable signals will be silently ignored.
* This is counter to what appears to be documented in some UNIX
* man pages, e.g. Linux.
*/
int __stdcall
handle_sigsuspend (sigset_t tempmask)
{
sig_dispatch_pending (0);
sigframe thisframe (mainthread);
2000-02-18 03:38:33 +08:00
sigset_t oldmask = myself->getsigmask (); // Remember for restoration
set_process_mask (tempmask & ~SIG_NONMASKABLE);// Let signals we're
// interested in through.
sigproc_printf ("old mask %x, new mask %x", oldmask, tempmask);
WaitForSingleObject (signal_arrived, INFINITE);
set_sig_errno (EINTR); // Per POSIX
/* A signal dispatch function will have been added to our stack and will
be hit eventually. Set the old mask to be restored when the signal
handler returns. */
sigsave.oldmask = oldmask; // Will be restored by signal handler
return -1;
}
extern DWORD exec_exit; // Possible exit value for exec
extern int pending_signals;
extern "C" {
static void
sig_handle_tty_stop (int sig)
{
/* Silently ignore attempts to suspend if there is no accomodating
cygwin parent to deal with this behavior. */
if (!myself->ppid_handle)
{
myself->process_state &= ~PID_STOPPED;
return;
}
myself->stopsig = sig;
/* See if we have a living parent. If so, send it a special signal.
* It will figure out exactly which pid has stopped by scanning
* its list of subprocesses.
*/
if (my_parent_is_alive ())
{
pinfo parent (myself->ppid);
if (!(parent->getsig (SIGCHLD).sa_flags & SA_NOCLDSTOP))
sig_send (parent, SIGCHLD);
}
sigproc_printf ("process %d stopped by signal %d, myself->ppid_handle %p",
myself->pid, sig, myself->ppid_handle);
if (WaitForSingleObject (sigCONT, INFINITE) != WAIT_OBJECT_0)
api_fatal ("WaitSingleObject failed, %E");
(void) ResetEvent (sigCONT);
return;
}
}
int
interruptible (DWORD pc, int testvalid = 0)
2000-02-18 03:38:33 +08:00
{
int res;
MEMORY_BASIC_INFORMATION m;
memset (&m, 0, sizeof m);
if (!VirtualQuery ((LPCVOID) pc, &m, sizeof m))
sigproc_printf ("couldn't get memory info, pc %p, %E", pc);
char *checkdir = (char *) alloca (windows_system_directory_length + 4);
memset (checkdir, 0, sizeof (checkdir));
# define h ((HMODULE) m.AllocationBase)
/* Apparently Windows 95 can sometimes return bogus addresses from
GetThreadContext. These resolve to a strange allocation base.
These should *never* be treated as interruptible. */
if (!h || m.State != MEM_COMMIT)
res = 0;
else if (testvalid)
res = 1; /* All we wanted to know was if this was a valid module. */
else if (h == user_data->hmodule)
res = 1;
else if (h == cygwin_hmodule)
res = 0;
else if (!GetModuleFileName (h, checkdir, windows_system_directory_length + 2))
res = 0;
else
res = !strncasematch (windows_system_directory, checkdir,
windows_system_directory_length);
sigproc_printf ("pc %p, h %p, interruptible %d, testvalid %d", pc, h, res, testvalid);
# undef h
return res;
2000-02-18 03:38:33 +08:00
}
bool
sigthread::get_winapi_lock (int test)
{
if (test)
return !InterlockedExchange (&winapi_lock, 1);
/* Need to do a busy loop because we can't block or a potential SuspendThread
will hang. */
while (InterlockedExchange (&winapi_lock, 1))
low_priority_sleep (0);
return 1;
}
void
sigthread::release_winapi_lock ()
{
/* Assumes that we have the lock. */
InterlockedExchange (&winapi_lock, 0);
}
static void __stdcall interrupt_setup (int sig, void *handler, DWORD retaddr,
DWORD *retaddr_on_stack,
struct sigaction& siga)
__attribute__((regparm(3)));
static void __stdcall
interrupt_setup (int sig, void *handler, DWORD retaddr, DWORD *retaddr_on_stack,
struct sigaction& siga)
2000-02-18 03:38:33 +08:00
{
sigsave.retaddr = retaddr;
sigsave.retaddr_on_stack = retaddr_on_stack;
/* FIXME: Not multi-thread aware */
sigsave.oldmask = myself->getsigmask ();
sigsave.newmask = sigsave.oldmask | siga.sa_mask | SIGTOMASK (sig);
sigsave.sa_flags = siga.sa_flags;
sigsave.func = (void (*)(int)) handler;
sigsave.sig = sig;
sigsave.saved_errno = -1; // Flag: no errno to save
if (handler == sig_handle_tty_stop)
{
myself->stopsig = 0;
myself->process_state |= PID_STOPPED;
}
/* Clear any waiting threads prior to dispatching to handler function */
proc_subproc (PROC_CLEARWAIT, 1);
int res = SetEvent (signal_arrived); // For an EINTR case
sigproc_printf ("armed signal_arrived %p, res %d", signal_arrived, res);
}
2000-02-18 03:38:33 +08:00
static bool interrupt_now (CONTEXT *, int, void *, struct sigaction&) __attribute__((regparm(3)));
static bool
interrupt_now (CONTEXT *ctx, int sig, void *handler, struct sigaction& siga)
{
interrupt_setup (sig, handler, ctx->Eip, 0, siga);
ctx->Eip = (DWORD) sigdelayed;
SetThreadContext (myself->getthread2signal (), ctx); /* Restart the thread in a new location */
return 1;
2000-02-18 03:38:33 +08:00
}
* Makefile.in: Remove some obsolete stuff. * dcrt0.cc (dll_crt0_1): Call signal_fixup_after_exec where appropriate. Set myself->uid from parent version. Just use ThreadItem Init method. Close or store hexec_proc as appropriate. (_dll_crt0): Store user_data->forkee here so that proper tests can be made subsequently. (do_exit): Remove hExeced stuff. * environ.cc (environ_init): Accept environ count as well as environ pointer. * environ.h: Reflect above change. * pinfo.cc (pinfo_init): Ditto. Accept environ count. (fixup_in_spawned_child): Remove. * spawn.cc (spawn_guts): Move signal code to dll_crt0_1. Don't suspend execing process since it is no longer necessary. Store envc. * exceptions.cc (signal_fixup_after_exec): New function. (call_handler): Remove hExeced test. * child_info.h (cygheap_exec_info): Store envc as well as envp. (child_info_spawn): Store hexec_proc so that it can be closed in child. * path.cc (normalize_posix_path): Avoid intermediate use of temporary cwd buf. (normalize_win32_path): Ditto. (cwdstuff::get_initial): Always set lock. * sigproc.h: Remove hExeced. * strace.cc (strace::vsprntf): Modify to accomodate for lack of hExeced. * thread.cc (MTinterface::Init): Merge Init1 and ClearReent into this method. (MTinterface::Init1): Eliminate. (MTinterface::ClearReent): Eliminate. * thread.h: Reflect above changes. * include/sys/strace.h (strace): Make microseconds() public. Make various functions 'regparm', throughout. * pinfo.h (_pinfo): Inline simple signal manipulation functions. Requires inclusion of thread.h which was removed from .cc files, where appropriate. throughout. * pinfo.cc: Eliminate signal manipulation functions. (_pinfo::exit): Calculate total rusage for exiting process here. * cygheap.cc (size2bucket): Eliminate. (init_buckets): Ditto. (_cmalloc): Calculate size and bits in a loop rather than going through a function call. (_crealloc): Use stored array index to calculate allocated size. * spawn.cc (spawn_guts): Use _pinfo exit method to exit, calculating cpu usage.
2000-10-17 07:55:58 +08:00
void __stdcall
signal_fixup_after_fork ()
{
if (sigsave.sig)
{
sigsave.sig = 0;
if (sigsave.retaddr_on_stack)
{
*sigsave.retaddr_on_stack = sigsave.retaddr;
set_process_mask (sigsave.oldmask);
}
}
sigproc_init ();
}
* Makefile.in: Remove some obsolete stuff. * dcrt0.cc (dll_crt0_1): Call signal_fixup_after_exec where appropriate. Set myself->uid from parent version. Just use ThreadItem Init method. Close or store hexec_proc as appropriate. (_dll_crt0): Store user_data->forkee here so that proper tests can be made subsequently. (do_exit): Remove hExeced stuff. * environ.cc (environ_init): Accept environ count as well as environ pointer. * environ.h: Reflect above change. * pinfo.cc (pinfo_init): Ditto. Accept environ count. (fixup_in_spawned_child): Remove. * spawn.cc (spawn_guts): Move signal code to dll_crt0_1. Don't suspend execing process since it is no longer necessary. Store envc. * exceptions.cc (signal_fixup_after_exec): New function. (call_handler): Remove hExeced test. * child_info.h (cygheap_exec_info): Store envc as well as envp. (child_info_spawn): Store hexec_proc so that it can be closed in child. * path.cc (normalize_posix_path): Avoid intermediate use of temporary cwd buf. (normalize_win32_path): Ditto. (cwdstuff::get_initial): Always set lock. * sigproc.h: Remove hExeced. * strace.cc (strace::vsprntf): Modify to accomodate for lack of hExeced. * thread.cc (MTinterface::Init): Merge Init1 and ClearReent into this method. (MTinterface::Init1): Eliminate. (MTinterface::ClearReent): Eliminate. * thread.h: Reflect above changes. * include/sys/strace.h (strace): Make microseconds() public. Make various functions 'regparm', throughout. * pinfo.h (_pinfo): Inline simple signal manipulation functions. Requires inclusion of thread.h which was removed from .cc files, where appropriate. throughout. * pinfo.cc: Eliminate signal manipulation functions. (_pinfo::exit): Calculate total rusage for exiting process here. * cygheap.cc (size2bucket): Eliminate. (init_buckets): Ditto. (_cmalloc): Calculate size and bits in a loop rather than going through a function call. (_crealloc): Use stored array index to calculate allocated size. * spawn.cc (spawn_guts): Use _pinfo exit method to exit, calculating cpu usage.
2000-10-17 07:55:58 +08:00
void __stdcall
signal_fixup_after_exec (bool isspawn)
{
/* Set up child's signal handlers */
for (int i = 0; i < NSIG; i++)
{
myself->getsig (i).sa_mask = 0;
if (myself->getsig (i).sa_handler != SIG_IGN || isspawn)
myself->getsig (i).sa_handler = SIG_DFL;
* Makefile.in: Remove some obsolete stuff. * dcrt0.cc (dll_crt0_1): Call signal_fixup_after_exec where appropriate. Set myself->uid from parent version. Just use ThreadItem Init method. Close or store hexec_proc as appropriate. (_dll_crt0): Store user_data->forkee here so that proper tests can be made subsequently. (do_exit): Remove hExeced stuff. * environ.cc (environ_init): Accept environ count as well as environ pointer. * environ.h: Reflect above change. * pinfo.cc (pinfo_init): Ditto. Accept environ count. (fixup_in_spawned_child): Remove. * spawn.cc (spawn_guts): Move signal code to dll_crt0_1. Don't suspend execing process since it is no longer necessary. Store envc. * exceptions.cc (signal_fixup_after_exec): New function. (call_handler): Remove hExeced test. * child_info.h (cygheap_exec_info): Store envc as well as envp. (child_info_spawn): Store hexec_proc so that it can be closed in child. * path.cc (normalize_posix_path): Avoid intermediate use of temporary cwd buf. (normalize_win32_path): Ditto. (cwdstuff::get_initial): Always set lock. * sigproc.h: Remove hExeced. * strace.cc (strace::vsprntf): Modify to accomodate for lack of hExeced. * thread.cc (MTinterface::Init): Merge Init1 and ClearReent into this method. (MTinterface::Init1): Eliminate. (MTinterface::ClearReent): Eliminate. * thread.h: Reflect above changes. * include/sys/strace.h (strace): Make microseconds() public. Make various functions 'regparm', throughout. * pinfo.h (_pinfo): Inline simple signal manipulation functions. Requires inclusion of thread.h which was removed from .cc files, where appropriate. throughout. * pinfo.cc: Eliminate signal manipulation functions. (_pinfo::exit): Calculate total rusage for exiting process here. * cygheap.cc (size2bucket): Eliminate. (init_buckets): Ditto. (_cmalloc): Calculate size and bits in a loop rather than going through a function call. (_crealloc): Use stored array index to calculate allocated size. * spawn.cc (spawn_guts): Use _pinfo exit method to exit, calculating cpu usage.
2000-10-17 07:55:58 +08:00
}
}
static int interrupt_on_return (sigthread *, int, void *, struct sigaction&) __attribute__((regparm(3)));
static int
interrupt_on_return (sigthread *th, int sig, void *handler, struct sigaction& siga)
2000-02-18 03:38:33 +08:00
{
int i;
DWORD ebp = th->frame;
2000-02-18 03:38:33 +08:00
if (!ebp)
return 0;
2000-02-18 03:38:33 +08:00
thestack.init (ebp, 0, 1); /* Initialize from the input CONTEXT */
for (i = 0; i < 32 && thestack++ ; i++)
if (th->exception || interruptible (thestack.sf.AddrReturn.Offset))
2000-02-18 03:38:33 +08:00
{
DWORD *addr_retaddr = ((DWORD *)thestack.sf.AddrFrame.Offset) + 1;
if (*addr_retaddr == thestack.sf.AddrReturn.Offset)
{
interrupt_setup (sig, handler, *addr_retaddr, addr_retaddr, siga);
*addr_retaddr = (DWORD) sigdelayed;
}
return 1;
2000-02-18 03:38:33 +08:00
}
sigproc_printf ("couldn't find a stack frame, i %d", i);
return 0;
2000-02-18 03:38:33 +08:00
}
extern "C" void __stdcall
set_sig_errno (int e)
{
set_errno (e);
sigsave.saved_errno = e;
// sigproc_printf ("errno %d", e);
2000-02-18 03:38:33 +08:00
}
static int setup_handler (int, void *, struct sigaction&) __attribute__((regparm(3)));
2000-02-18 03:38:33 +08:00
static int
setup_handler (int sig, void *handler, struct sigaction& siga)
2000-02-18 03:38:33 +08:00
{
CONTEXT cx;
bool interrupted = false;
sigthread *th = NULL; // Initialization needed to shut up gcc
int prio = INFINITE;
if (sigsave.sig)
goto set_pending;
for (int i = 0; i < CALL_HANDLER_RETRY; i++)
{
DWORD res;
HANDLE hth;
EnterCriticalSection (&mainthread.lock);
if (mainthread.frame)
{
hth = NULL;
th = &mainthread;
}
else
{
LeaveCriticalSection (&mainthread.lock);
if (!mainthread.get_winapi_lock (1))
continue;
hth = myself->getthread2signal ();
th = NULL;
/* Suspend the thread which will receive the signal. But first ensure that
this thread doesn't have any mutos. (FIXME: Someday we should just grab
all of the mutos rather than checking for them)
For Windows 95, we also have to ensure that the addresses returned by GetThreadContext
are valid.
If one of these conditions is not true we loop for a fixed number of times
since we don't want to stall the signal handler. FIXME: Will this result in
noticeable delays?
If the thread is already suspended (which can occur when a program has called
SuspendThread on itself then just queue the signal. */
EnterCriticalSection (&mainthread.lock);
sigproc_printf ("suspending mainthread");
res = SuspendThread (hth);
/* Just release the lock now since we hav suspended the main thread and it
definitely can't be grabbing it now. This will have to change, of course,
if/when we can send signals to other than the main thread. */
LeaveCriticalSection (&mainthread.lock);
/* Just set pending if thread is already suspended */
if (res)
{
(void) ResumeThread (hth);
break;
}
mainthread.release_winapi_lock ();
if (mainthread.frame)
goto resume_thread; /* We just got the frame. What are the odds?
Just loop and we'll hopefully pick it up on
the next pass through. */
muto *m;
/* FIXME: Make multi-thread aware */
for (m = muto_start.next; m != NULL; m = m->next)
if (m->unstable () || m->owner () == mainthread.id)
{
sigproc_printf ("suspended thread owns a muto (%s)", m->name);
goto resume_thread;
}
if (mainthread.frame)
th = &mainthread;
else
{
cx.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;
if (!GetThreadContext (hth, &cx))
{
system_printf ("couldn't get context of main thread, %E");
goto resume_thread;
}
}
}
if ((DWORD) prio != INFINITE)
{
/* Reset the priority so we can finish this off quickly. */
SetThreadPriority (GetCurrentThread (), WAIT_SIG_PRIORITY);
prio = INFINITE;
}
if (th)
{
interrupted = interrupt_on_return (th, sig, handler, siga);
LeaveCriticalSection (&th->lock);
}
else if (interruptible (cx.Eip))
interrupted = interrupt_now (&cx, sig, handler, siga);
resume_thread:
if (hth)
res = ResumeThread (hth);
if (interrupted)
break;
if ((DWORD) prio != INFINITE && !mainthread.frame)
prio = low_priority_sleep (SLEEP_0_STAY_LOW);
sigproc_printf ("couldn't interrupt. trying again.");
2000-02-18 03:38:33 +08:00
}
set_pending:
if (interrupted)
{
if ((DWORD) prio != INFINITE)
SetThreadPriority (GetCurrentThread (), WAIT_SIG_PRIORITY);
sigproc_printf ("signal successfully delivered");
}
else
2000-02-18 03:38:33 +08:00
{
pending_signals = 1; /* FIXME: Probably need to be more tricky here */
sig_set_pending (sig);
sig_dispatch_pending (1);
low_priority_sleep (SLEEP_0_STAY_LOW); /* Hopefully, other process will be waking up soon. */
sigproc_printf ("couldn't send signal %d", sig);
2000-02-18 03:38:33 +08:00
}
sigproc_printf ("returning %d", interrupted);
return interrupted;
2000-02-18 03:38:33 +08:00
}
#endif /* i386 */
#ifndef HAVE_CALL_HANDLER
#error "Need to supply machine dependent setup_handler"
2000-02-18 03:38:33 +08:00
#endif
/* Keyboard interrupt handler. */
2000-02-18 03:38:33 +08:00
static BOOL WINAPI
ctrl_c_handler (DWORD type)
{
if (type == CTRL_LOGOFF_EVENT)
return TRUE;
/* Return FALSE to prevent an "End task" dialog box from appearing
for each Cygwin process window that's open when the computer
is shut down or console window is closed. */
if (type == CTRL_SHUTDOWN_EVENT)
{
sig_send (NULL, SIGTERM);
return FALSE;
}
if (type == CTRL_CLOSE_EVENT)
2000-02-18 03:38:33 +08:00
{
sig_send (NULL, SIGHUP);
return FALSE;
}
/* If we are a stub and the new process has a pinfo structure, let it
handle this signal. */
if (dwExeced && pinfo (dwExeced))
return TRUE;
/* We're only the process group leader when we have a valid pinfo structure.
If we don't have one, then the parent "stub" will handle the signal. */
if (!pinfo (cygwin_pid (GetCurrentProcessId ())))
return TRUE;
tty_min *t = cygwin_shared->tty.get_tty (myself->ctty);
/* Ignore this if we're not the process group leader since it should be handled
2000-02-18 03:38:33 +08:00
*by* the process group leader. */
if (myself->ctty != -1 && t->getpgid () == myself->pid &&
(GetTickCount () - t->last_ctrl_c) >= MIN_CTRL_C_SLOP)
2000-02-18 03:38:33 +08:00
/* Otherwise we just send a SIGINT to the process group and return TRUE (to indicate
that we have handled the signal). At this point, type should be
a CTRL_C_EVENT or CTRL_BREAK_EVENT. */
{
t->last_ctrl_c = GetTickCount ();
kill (-myself->pid, SIGINT);
t->last_ctrl_c = GetTickCount ();
return TRUE;
}
return TRUE;
2000-02-18 03:38:33 +08:00
}
/* Set the signal mask for this process.
Note that some signals are unmaskable, as in UNIX. */
2000-02-18 03:38:33 +08:00
extern "C" void __stdcall
set_process_mask (sigset_t newmask)
{
sigframe thisframe (mainthread);
2000-02-18 03:38:33 +08:00
mask_sync->acquire (INFINITE);
sigset_t oldmask = myself->getsigmask ();
2000-02-18 03:38:33 +08:00
newmask &= ~SIG_NONMASKABLE;
sigproc_printf ("old mask = %x, new mask = %x", myself->getsigmask (), newmask);
myself->setsigmask (newmask); // Set a new mask
mask_sync->release ();
if (oldmask != newmask && GetCurrentThreadId () != sigtid)
sig_dispatch_pending ();
else
sigproc_printf ("not calling sig_dispatch_pending. sigtid %p current %p",
sigtid, GetCurrentThreadId ());
2000-02-18 03:38:33 +08:00
return;
}
int __stdcall
sig_handle (int sig, bool thisproc)
2000-02-18 03:38:33 +08:00
{
int rc = 0;
sigproc_printf ("signal %d", sig);
struct sigaction thissig = myself->getsig (sig);
2000-02-18 03:38:33 +08:00
void *handler = (void *) thissig.sa_handler;
myself->rusage_self.ru_nsignals++;
/* Clear pending SIGCONT on stop signals */
if (sig == SIGSTOP || sig == SIGTSTP || sig == SIGTTIN || sig == SIGTTOU)
sig_clear (SIGCONT);
if (sig == SIGKILL)
goto exit_sig;
if (sig == SIGSTOP)
goto stop;
/* FIXME: Should we still do this if SIGCONT has a handler? */
if (sig == SIGCONT)
{
DWORD stopped = myself->process_state & PID_STOPPED;
2000-02-18 03:38:33 +08:00
myself->stopsig = 0;
myself->process_state &= ~PID_STOPPED;
/* Clear pending stop signals */
sig_clear (SIGSTOP);
sig_clear (SIGTSTP);
sig_clear (SIGTTIN);
sig_clear (SIGTTOU);
if (stopped)
SetEvent (sigCONT);
2000-02-18 03:38:33 +08:00
/* process pending signals */
sig_dispatch_pending (1);
2000-02-18 03:38:33 +08:00
}
#if 0
char sigmsg[24];
__small_sprintf (sigmsg, "cygwin: signal %d\n", sig);
OutputDebugString (sigmsg);
#endif
if (handler == (void *) SIG_DFL)
{
if (sig == SIGCHLD || sig == SIGIO || sig == SIGCONT || sig == SIGWINCH
* autoload.cc (LoadFuncEx): Define via new LoadFuncEx2 macro. (LoadFuncEx2): Adapted from LoadFuncEx. Provides control of return value for nonexistent function. (NtQueryObject): Declare. (IsDebuggerPresent): Declare via LoadFuncEx2 and always return true if not available. * debug.h (being_debugged): Just rely on IsDebuggerPresent return value. * dtable.cc (handle_to_fn): New function. (dtable::init_std_file_from_handle): Attempt to derive std handle's name via handle_to_fn. (dtable::build_fhandler_from_name): Fill in what we can in path_conv structure when given a handle and path doesn't exist. * fhandler.cc (fhandler_base::open): Don't set the file pointer here. Use pc->exists () to determine if file exists rather than calling GetFileAttributes again. * fhandler.h (fhandler_base::exec_state_isknown): New method. (fhandler_base::fstat_helper): Add extra arguments to declaration. (fhandler_base::fstat_by_handle): Declare new method. (fhandler_base::fstat_by_name): Declare new method. * fhandler_disk_file (num_entries): Make __stdcall. (fhandler_base::fstat_by_handle): Define new method. (fhandler_base::fstat_by_name): Define new method. (fhandler_base:fstat): Call fstat_by_{handle,name} as appropriate. (fhandler_disk_file::fstat_helper): Accept extra arguments for filling out stat structure. Move handle or name specific stuff to new methods above. (fhandler_disk_file::open): Use real_path->exists rather than calling GetFileAttributes again. * ntdll.h (FILE_NAME_INFORMATION): Define new structure. (OBJECT_INFORMATION_CLASS): Partially define new enum. (OBJECT_NAME_INFORMATION): Define new structure. (NtQueryInformationFile): New declaration. (NtQueryObject): New declaration. * path.cc (path_conv::fillin): Define new method. * path.h (path_conv::fillin): Declare new method. (path_conv::drive_thpe): Rename from 'get_drive_type'. (path_conv::volser): Declare new method. (path_conv::volname): Declare new method. (path_conv::root_dir): Declare new method. * syscalls.cc (fstat64): Send real path_conv to fstat as second argument.
2002-05-28 09:55:40 +08:00
|| sig == SIGURG || (thisproc && hExeced && sig == SIGINT))
2000-02-18 03:38:33 +08:00
{
sigproc_printf ("default signal %d ignored", sig);
goto done;
}
if (sig == SIGTSTP || sig == SIGTTIN || sig == SIGTTOU)
goto stop;
goto exit_sig;
}
if (handler == (void *) SIG_IGN)
{
sigproc_printf ("signal %d ignored", sig);
goto done;
}
if (handler == (void *) SIG_ERR)
goto exit_sig;
goto dosig;
stop:
/* Eat multiple attempts to STOP */
if (ISSTATE (myself, PID_STOPPED))
goto done;
2000-02-18 03:38:33 +08:00
handler = (void *) sig_handle_tty_stop;
thissig = myself->getsig (SIGSTOP);
2000-02-18 03:38:33 +08:00
dosig:
2000-02-18 03:38:33 +08:00
/* Dispatch to the appropriate function. */
sigproc_printf ("signal %d, about to call %p", sig, handler);
rc = setup_handler (sig, handler, thissig);
2000-02-18 03:38:33 +08:00
done:
2000-02-18 03:38:33 +08:00
sigproc_printf ("returning %d", rc);
return rc;
exit_sig:
2000-02-18 03:38:33 +08:00
if (sig == SIGQUIT || sig == SIGABRT)
{
CONTEXT c;
c.ContextFlags = CONTEXT_FULL;
GetThreadContext (hMainThread, &c);
if (!try_to_debug ())
stackdump (c.Ebp, 1, 1);
sig |= 0x80;
2000-02-18 03:38:33 +08:00
}
sigproc_printf ("signal %d, about to call do_exit", sig);
signal_exit (sig);
2000-02-18 03:38:33 +08:00
/* Never returns */
}
/* Cover function to `do_exit' to handle exiting even in presence of more
exceptions. We used to call exit, but a SIGSEGV shouldn't cause atexit
2000-02-18 03:38:33 +08:00
routines to run. */
static void
signal_exit (int rc)
2000-02-18 03:38:33 +08:00
{
rc = EXIT_SIGNAL | (rc << 8);
2000-02-18 03:38:33 +08:00
if (exit_already++)
* exceptions.cc (set_console_handler): Don't allocate console_handler_thread_waiter. It is obsolete. (ctrl_c_handler): Don't use console_handler_thread_waiter. * path.cc (hash_path_name): Fix handling of relative names. Make case insensitive. * path.h (suffix_info): Use initializers. * pinfo.h (_pinfo): Avoid initializers for null case. * resource.cc (fill_rusage): Zero rest of rusage structure. * security.cc (set_process_privileges): Don't reopen parent process. Just use hMainProc. * signal.cc (signal): Track when a signal handler has been used. (sigaction): Ditto. * sigproc.cc (pchildren): Use default initializer. (zombies): Ditto. (sigproc_terminate): Avoid closing handles that will be closed on exit anyway. (wait_sig): Send signal to "parent" on EXECing, not FORKing. (wait_subproc): Send SIGCHLD here rather than in proc_wait to avoid potential muto conflicts. * sigproc.h (sigthread): Don't initialize to zero. It's the default. * spawn.cc (spawn_guts): Fill in resources from exec parent prior to termination. * sync.h (muto): Don't initialize to zero. * syscalls.cc (close_all_files): Use one lock around entire loop and call fhandler close/release stuff directly. (_read): Don't use ready_for_read if there are not signal handlers active. * dcrt0.cc (dll_crt0_1): Fix display of "title". (do_exit): Use pinfo exit method to exit. (__api_fatal): Ditto. * exceptions.cc (signal_exit): Ditto. * fork.cc (fork_child): Remove debugging stuff. Use pinfo_fixup_after fork in place of exec_fixup_after_fork. * pinfo.cc (pinfo_fixup_after_fork): New method. (pinfo_fixup_in_spawned_child): Ditto. (_pinfo::exit): New method. (_pinfo::init): Remove recursion. Detect pathological case where pinfo structure already exists for new pid. * pinfo.h (_pinfo): Reorganize slightly. Add new method and new function declarations. * sigproc.cc (proc_exists): Previous simplification was a little to simple. Try harder to detect if a process exists. (proc_terminate): Use PID_EXITED setting to determine if process is still around. (WFSO): Remove debugging statement. (WFMO): Ditto. * spawn.cc (exec_fixup_after_fork): Eliminate. (spawn_guts): Always set old_title to NULL. Is it really needed? Move hexec_proc to pinfo.cc. Call pinfo_fixup_in_spawned_child to eliminate handle link after a spawn. * include/sys/cygwin.h: Remove PID_NOT_IN_USE. Add PID_EXITED.
2000-10-15 09:37:07 +08:00
myself->exit (rc);
2000-02-18 03:38:33 +08:00
/* We'd like to stop the main thread from executing but when we do that it
causes random, inexplicable hangs. So, instead, we set up the priority
of this thread really high so that it should do its thing and then exit. */
(void) SetThreadPriority (hMainThread, THREAD_PRIORITY_IDLE);
(void) SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL);
/* Unlock any main thread mutos since we're executing with prejudice. */
muto *m;
for (m = muto_start.next; m != NULL; m = m->next)
if (m->unstable () || m->owner () == mainthread.id)
m->reset ();
user_data->resourcelocks->Delete ();
user_data->resourcelocks->Init ();
if (hExeced)
TerminateProcess (hExeced, rc);
sigproc_printf ("about to call do_exit (%x)", rc);
(void) SetEvent (signal_arrived);
2000-02-18 03:38:33 +08:00
do_exit (rc);
}
HANDLE NO_COPY title_mutex = NULL;
void
events_init (void)
{
/* title_mutex protects modification of console title. It's neccessary
while finding console window handle */
if (!(title_mutex = CreateMutex (&sec_all_nih, FALSE,
shared_name ("title_mutex", 0))))
api_fatal ("can't create title mutex, %E");
ProtectHandle (title_mutex);
* sync.h (new_muto): Just accept an argument which denotes the name of the muto. Use this argument to construct static storage. * cygheap.cc (cygheap_init): Reflect above change. * exceptions.cc (events_init): Ditto. * malloc.cc (malloc_init): Ditto. * path.cc (cwdstuff::init): Ditto. * cygheap.h (cwdstuff): Change name of lock element to make it less generic. * path.cc (cwdstuff::get_hash): Ditto. (cwdstuff::get_initial): Ditto. (cwdstuff::set): Ditto. (cwdstuff::get): Ditto. * sigproc.cc (proc_subproc): Ditto. * debug.cc (lock_debug): Change to method. Use method rather than macro throughout. * tty.h (tty_min::kill_pgrp): Declare new method. * fhandler_termios.cc (tty_min::kill_pgrp): New method. (fhandler_termios::line_edit): Use new method for killing process. * dcrt0.cc (do_exit): Ditto. * dtable.cc (dtable::get_debugger_info): New method for inheriting dtable info from a debugger. * tty.cc (tty_init): Attempt to grab file handle info from parent debugger, if appropriate. # dtable.cc (dtable::stdio_init): Make this a method. (dtable::init_std_file_from_handle): Don't set fd unless it's not open. (dtable::build_fhandler_from_name): Move name setting to dtable::build_fhandler. (dtable::build_fhandler): Add win32 name parameter. * dcrt0.cc (dll_crt0_1): Change to use dtable stdio_init. * dtable.h (dtable): Reflect build_fhandler parameter change. * mmap.cc (mmap_record::alloc_fh): Don't set name parameter in build_fhandler. * net.cc (fdsock): Remove set_name call since it is now handled by build_fhandler. * sigproc.cc (proc_subproc): Release muto as early as possible.
2002-02-23 03:33:41 +08:00
new_muto (mask_sync);
windows_system_directory[0] = '\0';
(void) GetSystemDirectory (windows_system_directory, sizeof (windows_system_directory) - 2);
char *end = strchr (windows_system_directory, '\0');
if (end == windows_system_directory)
api_fatal ("can't find windows system directory");
if (end[-1] != '\\')
{
*end++ = '\\';
*end = '\0';
}
windows_system_directory_length = end - windows_system_directory;
debug_printf ("windows_system_directory '%s', windows_system_directory_length %d",
windows_system_directory, windows_system_directory_length);
debug_printf ("cygwin_hmodule %p", cygwin_hmodule);
2000-02-18 03:38:33 +08:00
}
void
events_terminate (void)
{
exit_already = 1;
}
extern "C" {
static int __stdcall
call_signal_handler_now ()
{
if (!sigsave.sig)
{
sigproc_printf ("call_signal_handler_now called when no signal active");
return 0;
}
int sa_flags = sigsave.sa_flags;
sigproc_printf ("sa_flags %p", sa_flags);
*sigsave.retaddr_on_stack = sigsave.retaddr;
sigdelayed0 ();
return sa_flags & SA_RESTART;
}
/* This kludge seems to keep a copy of call_signal_handler_now around
even when compiling with -finline-functions. */
static int __stdcall call_signal_handler_now_dummy ()
__attribute__((alias ("call_signal_handler_now")));
};
int
sigframe::call_signal_handler ()
{
return unregister () ? call_signal_handler_now () : 0;
}
* include/cygwin/version.h: Bump DLL minor version number to 5 due to all of the changes below. Redefine process structure to avoid a fixed size table. Redefine pinfo/_pinfo classes. Use these throughout. * dcrt0.cc (dll_crt0_1): Accomodate set_myself argument change. (__api_fatal): Accomodate _pinfo::record_death argument change. * exceptions.cc (really_exit): Ditto. (sig_handle_tty_stop): Use pinfo constructor to access process info. (events_init): Don't create pinfo_mutex since it is no longer required. * external.cc (fillout_pinfo): Use winpids class to iterate over all system pids. (cygwin_internal): lock_pinfo_for_update and unlock_pinfo are now noops. * fhandler_termios.cc (fhandler_termios::set_ctty): Use pinfo constructor to access process info. * fork.cc (fork): Reorganize to initialize child info after the child has started since that is when we know the child's winpid, which is necessary to allocate the pinfo shared memory. * mmap.cc (recreate_mmaps_after_fork): Change arg type to _pinfo. * pinfo.cc: Rename pinfo methods to _pinfo throughout. Eliminate pinfo_list stuff. (set_myself): Accept a pid argument now. Call pinfo initializer to initialize myself. Detect when this is an "execed" process and create an "indirect" pid block. (pinfo_init): Accomodate set_myself arg change. (procinfo): Remove. (pinfo::lock_pinfo): Remove. (pinfo::unlock_pinfo): Remove. (pinfo::init): New method. Allocates shared memory space for process pinfo structure. (pinfo::record_death): Don't call locking functions. (cygwin_winpid_to_pid): Simplify by using new pinfo constructor. (EnumProcessesW95): New function for iterating over processes on Windows 95. (winpids::winpids): New constructor for winpids class. Sets up a list of process ids. (enum_init): Initialize w95/wnt pid enumerators. * shared.cc (shared-info::initialize): Remove pid initialization. * shared.h: Move pinfo stuff into pinfo.h. (class shared_info): Remove pinfo_list element. * signal.cc (kill_worker): Use pinfo constructor to access process info. (kill_pgrp): Ditto. Use winpids methods to access list of processes. * sigproc.cc: Throughout, modify to use _pinfo where appropriate. (proc_exists (pid_t)): New function. Determines if a process exists based on the pid. (proc_exists (_pinfo *p): Use new proc_exists function above. (proc_subproc): Copy pinfo stuff around rather than _pinfo pointers. Try to be careful about releasing shared memory when we don't need it anymore. Remove pinfo locks. (remove_zombies): Remove pinfo memory when zombie is going away. * sigproc.h: Reflect _pinfo/pinfo changes in sigproc.cc. * spawn.cc (spawn_guts): Eliminate pinfo *child argument. Reorganize to only initialize child pinfo after process has been started and we know the windows pid. (_spawnve): Reflect spawn_guts changes. * syscalls.cc (setpgid): Use pinfo constructor to access process info. (getpgid): Ditto. (internal_getlogin): Use _pinfo. * winsup.h: Eliminate pinfo_mutex. Eliminate spawn_guts declaration since it is static now. Reflect set_myself argument change. * include/sys/cygwin.h: Add some PID_* enums to accomodate new pinfo stuff. * include/cygwin/version.h: Update minor version for cygdrive changes below.
2000-07-30 00:24:59 +08:00
#define pid_offset (unsigned)(((_pinfo *)NULL)->pid)
2000-02-18 03:38:33 +08:00
extern "C" {
void __stdcall
reset_signal_arrived ()
{
(void) ResetEvent (signal_arrived);
sigproc_printf ("reset signal_arrived");
}
static void unused_sig_wrapper () __attribute__((const, unused));
#undef errno
#define errno ((DWORD volatile) _impure_ptr) + (((char *) &_impure_ptr->_errno) - ((char *) _impure_ptr))
static void
unused_sig_wrapper ()
2000-02-18 03:38:33 +08:00
{
/* Signal cleanup stuff. Cleans up stack (too bad that we didn't
prototype signal handlers as __stdcall), calls _set_process_mask
2001-01-27 11:02:15 +08:00
to restore any mask, restores any potentially clobbered registers
and returns to original caller. */
__asm__ volatile ("\n\
.text \n\
_sigreturn: \n\
addl $4,%%esp # Remove argument \n\
movl %%esp,%%ebp \n\
addl $36,%%ebp \n\
call _set_process_mask@4 \n\
\n\
cmpl $0,%4 # Did a signal come in? \n\
jz 1f # No, if zero \n\
call _call_signal_handler_now@0 # yes handle the signal \n\
\n\
1: popl %%eax # saved errno \n\
testl %%eax,%%eax # Is it < 0 \n\
jl 2f # yup. ignore it \n\
movl %1,%%ebx \n\
movl %%eax,(%%ebx) \n\
2: popl %%eax \n\
popl %%ebx \n\
popl %%ecx \n\
popl %%edx \n\
popl %%edi \n\
popl %%esi \n\
popf \n\
popl %%ebp \n\
ret \n\
\n\
__no_sig_start: \n\
_sigdelayed: \n\
pushl %2 # original return address \n\
_sigdelayed0: \n\
pushl %%ebp \n\
movl %%esp,%%ebp \n\
pushf \n\
pushl %%esi \n\
pushl %%edi \n\
pushl %%edx \n\
pushl %%ecx \n\
pushl %%ebx \n\
pushl %%eax \n\
pushl %6 # saved errno \n\
pushl %3 # oldmask \n\
pushl %4 # signal argument \n\
pushl $_sigreturn \n\
\n\
call _reset_signal_arrived@0 \n\
pushl %5 # signal number \n\
pushl %7 # newmask \n\
movl $0,%0 # zero the signal number as a \n\
# flag to the signal handler thread\n\
# that it is ok to set up sigsave\n\
\n\
call _set_process_mask@4 \n\
popl %%eax \n\
jmp *%%eax \n\
__no_sig_end: \n\
" : "=m" (sigsave.sig): "X" ((char *) &_impure_ptr->_errno),
2000-02-18 03:38:33 +08:00
"g" (sigsave.retaddr), "g" (sigsave.oldmask), "g" (sigsave.sig),
"g" (sigsave.func), "g" (sigsave.saved_errno), "g" (sigsave.newmask)
);
2000-02-18 03:38:33 +08:00
}
}