- fix wrong hexadecimal GetLastError() output
[wine] / win32 / except.c
1 /*
2  * Win32 exception functions
3  *
4  * Copyright (c) 1996 Onno Hovers, (onno@stack.urc.tue.nl)
5  * Copyright (c) 1999 Alexandre Julliard
6  *
7  * Notes:
8  *  What really happens behind the scenes of those new
9  *  __try{...}__except(..){....}  and
10  *  __try{...}__finally{...}
11  *  statements is simply not documented by Microsoft. There could be different
12  *  reasons for this: 
13  *  One reason could be that they try to hide the fact that exception 
14  *  handling in Win32 looks almost the same as in OS/2 2.x.  
15  *  Another reason could be that Microsoft does not want others to write
16  *  binary compatible implementations of the Win32 API (like us).  
17  *
18  *  Whatever the reason, THIS SUCKS!! Ensuring portability or future 
19  *  compatibility may be valid reasons to keep some things undocumented. 
20  *  But exception handling is so basic to Win32 that it should be 
21  *  documented!
22  *
23  */
24
25 #include <stdio.h>
26 #include "windef.h"
27 #include "winerror.h"
28 #include "ntddk.h"
29 #include "wingdi.h"
30 #include "winuser.h"
31 #include "wine/exception.h"
32 #include "thread.h"
33 #include "stackframe.h"
34 #include "wine/server.h"
35 #include "debugtools.h"
36
37 DEFAULT_DEBUG_CHANNEL(seh);
38
39 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
40
41 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
42 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
43
44 /*******************************************************************
45  *         RaiseException  (KERNEL32.@)
46  */
47 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const LPDWORD args )
48 {
49     EXCEPTION_RECORD record;
50
51     /* Compose an exception record */ 
52     
53     record.ExceptionCode    = code;
54     record.ExceptionFlags   = flags & EH_NONCONTINUABLE;
55     record.ExceptionRecord  = NULL;
56     record.ExceptionAddress = RaiseException;
57     if (nbargs && args)
58     {
59         if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
60         record.NumberParameters = nbargs;
61         memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
62     }
63     else record.NumberParameters = 0;
64
65     RtlRaiseException( &record );
66 }
67
68
69 /*******************************************************************
70  *         format_exception_msg
71  */
72 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
73 {
74     const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
75     int len,len2;
76
77     switch(rec->ExceptionCode)
78     {
79     case EXCEPTION_INT_DIVIDE_BY_ZERO:
80         len = snprintf( buffer, size, "Unhandled division by zero" );
81         break;
82     case EXCEPTION_INT_OVERFLOW:
83         len = snprintf( buffer, size, "Unhandled overflow" );
84         break;
85     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
86         len = snprintf( buffer, size, "Unhandled array bounds" );
87         break;
88     case EXCEPTION_ILLEGAL_INSTRUCTION:
89         len = snprintf( buffer, size, "Unhandled illegal instruction" );
90         break;
91     case EXCEPTION_STACK_OVERFLOW:
92         len = snprintf( buffer, size, "Unhandled stack overflow" );
93         break;
94     case EXCEPTION_PRIV_INSTRUCTION:
95         len = snprintf( buffer, size, "Unhandled privileged instruction" );
96         break;
97     case EXCEPTION_ACCESS_VIOLATION:
98         if (rec->NumberParameters == 2)
99             len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
100                      rec->ExceptionInformation[0] ? "write" : "read",
101                      rec->ExceptionInformation[1]);
102         else
103             len = snprintf( buffer, size, "Unhandled page fault");
104         break;
105     case EXCEPTION_DATATYPE_MISALIGNMENT:
106         len = snprintf( buffer, size, "Unhandled alignment" );
107         break;
108     case CONTROL_C_EXIT:
109         len = snprintf( buffer, size, "Unhandled ^C");
110         break;
111     case EXCEPTION_CRITICAL_SECTION_WAIT:
112         len = snprintf( buffer, size, "Critical section %08lx wait failed",
113                  rec->ExceptionInformation[0]);
114         break;
115     case EXCEPTION_WINE_STUB:
116         len = snprintf( buffer, size, "Unimplemented function %s.%s called",
117                  (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
118         break;
119     case EXCEPTION_VM86_INTx:
120         len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
121                  rec->ExceptionInformation[0]);
122         break;
123     case EXCEPTION_VM86_STI:
124         len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
125         break;
126     case EXCEPTION_VM86_PICRETURN:
127         len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
128         break;
129     default:
130         len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
131         break;
132     }
133     if ((len<0) || (len>=size))
134         return -1;
135 #ifdef __i386__
136     if (ptr->ContextRecord->SegCs != __get_cs())
137         len2 = snprintf(buffer+len, size-len,
138                         " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
139                         ptr->ContextRecord->SegCs,
140                         (DWORD)ptr->ExceptionRecord->ExceptionAddress);
141     else
142 #endif
143         len2 = snprintf(buffer+len, size-len,
144                         " at address 0x%08lx.\nDo you wish to debug it ?",
145                         (DWORD)ptr->ExceptionRecord->ExceptionAddress);
146     if ((len2<0) || (len>=size-len))
147         return -1;
148     return len+len2;
149 }
150
151
152 /**********************************************************************
153  *           send_debug_event
154  *
155  * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
156  */
157 static int send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
158 {
159     int ret;
160     HANDLE handle = 0;
161
162     SERVER_START_VAR_REQ( queue_exception_event, sizeof(*rec) + sizeof(*context) )
163     {
164         CONTEXT *context_ptr = server_data_ptr(req);
165         EXCEPTION_RECORD *rec_ptr = (EXCEPTION_RECORD *)(context_ptr + 1);
166         req->first   = first_chance;
167         *rec_ptr     = *rec;
168         *context_ptr = *context;
169         if (!SERVER_CALL()) handle = req->handle;
170     }
171     SERVER_END_VAR_REQ;
172     if (!handle) return 0;  /* no debugger present or other error */
173
174     /* No need to wait on the handle since the process gets suspended
175      * once the event is passed to the debugger, so when we get back
176      * here the event has been continued already.
177      */
178     SERVER_START_VAR_REQ( get_exception_status, sizeof(*context) )
179     {
180         req->handle = handle;
181         if (!SERVER_CALL()) *context = *(CONTEXT *)server_data_ptr(req);
182         ret = req->status;
183     }
184     SERVER_END_VAR_REQ;
185     NtClose( handle );
186     return ret;
187 }
188
189 /******************************************************************
190  *              start_debugger
191  *
192  * Does the effective debugger startup according to 'format'
193  */
194 static BOOL     start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
195 {
196     HKEY                hDbgConf;
197     DWORD               bAuto = FALSE;
198     PROCESS_INFORMATION info;
199     STARTUPINFOA        startup;
200     char*               cmdline = NULL;
201     char*               format = NULL;
202     DWORD               format_size;
203     BOOL                ret = FALSE;
204
205     MESSAGE("wine: Unhandled exception, starting debugger...\n");
206
207     if (!RegOpenKeyA(HKEY_LOCAL_MACHINE, 
208                      "Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug", &hDbgConf)) {
209        DWORD    type;
210        DWORD    count;
211
212        format_size = 0;
213        if (!RegQueryValueExA(hDbgConf, "Debugger", 0, &type, NULL, &format_size)) {
214            format = HeapAlloc(GetProcessHeap(), 0, format_size);
215            RegQueryValueExA(hDbgConf, "Debugger", 0, &type, format, &format_size);
216            if (type==REG_EXPAND_SZ) {
217                char* tmp;
218
219                /* Expand environment variable references */
220                format_size=ExpandEnvironmentStringsA(format,NULL,0);
221                tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
222                ExpandEnvironmentStringsA(format,tmp,format_size);
223                HeapFree(GetProcessHeap(), 0, format);
224                format=tmp;
225            }
226        }
227
228        count = sizeof(bAuto);
229        if (RegQueryValueExA(hDbgConf, "Auto", 0, &type, (char*)&bAuto, &count))
230           bAuto = TRUE;
231        else if (type == REG_SZ)
232        {
233            char autostr[10];
234            count = sizeof(autostr);
235            if (!RegQueryValueExA(hDbgConf, "Auto", 0, &type, autostr, &count))
236                bAuto = atoi(autostr);
237        }
238        RegCloseKey(hDbgConf);
239     } else {
240         /* try a default setup... */
241         strcpy( format, "winedbg --debugmsg -all -- --auto %ld %ld" );
242     }
243
244     if (!bAuto)
245     {
246         HMODULE                 mod = GetModuleHandleA( "user32.dll" );
247         MessageBoxA_funcptr     pMessageBoxA = NULL;
248
249         if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
250         if (pMessageBoxA)
251         {
252             char buffer[256];
253             format_exception_msg( epointers, buffer, sizeof(buffer) );
254             if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
255             {
256                 TRACE("Killing process\n");
257                 goto EXIT;
258             }
259         }
260     }
261
262     if (format) {
263         TRACE("Starting debugger (fmt=%s)\n", format);
264         cmdline=HeapAlloc(GetProcessHeap(), 0, format_size+2*20);
265         sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
266         memset(&startup, 0, sizeof(startup));
267         startup.cb = sizeof(startup);
268         startup.dwFlags = STARTF_USESHOWWINDOW;
269         startup.wShowWindow = SW_SHOWNORMAL;
270         if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &info)) {
271             /* wait for debugger to come up... */
272             WaitForSingleObject(hEvent, INFINITE);
273             ret = TRUE;
274             goto EXIT;
275         }
276     } else {
277         cmdline = NULL;
278     }
279     ERR("Couldn't start debugger (%s) (%ld)\n"
280         "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
281         debugstr_a(cmdline), GetLastError());
282
283 EXIT:
284     if (cmdline)
285         HeapFree(GetProcessHeap(), 0, cmdline);
286     if (format)
287         HeapFree(GetProcessHeap(), 0, format);
288     return ret;
289 }
290
291 /******************************************************************
292  *              start_debugger_atomic
293  *
294  * starts the debugger in an atomic way:
295  *      - either the debugger is not started and it is started
296  *      - or the debugger has already been started by another thread
297  *      - or the debugger couldn't be started
298  *
299  * returns TRUE for the two first conditions, FALSE for the last
300  */
301 static  int     start_debugger_atomic(PEXCEPTION_POINTERS epointers)
302 {
303     static HANDLE       hRunOnce /* = 0 */;
304
305     if (hRunOnce == 0)
306     {
307         OBJECT_ATTRIBUTES       attr;
308         HANDLE                  hEvent;
309
310         attr.Length                   = sizeof(attr);
311         attr.RootDirectory            = 0;
312         attr.Attributes               = OBJ_INHERIT;
313         attr.ObjectName               = NULL;
314         attr.SecurityDescriptor       = NULL;
315         attr.SecurityQualityOfService = NULL;
316
317         /* ask for manual reset, so that once the debugger is started,
318          * every thread will know it */
319         NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
320         if (InterlockedCompareExchange( (LPLONG)&hRunOnce, hEvent, 0 ) == 0)
321         {
322             /* ok, our event has been set... we're the winning thread */
323             BOOL        ret = start_debugger( epointers, hRunOnce );
324             DWORD       tmp;
325
326             if (!ret)
327             {
328                 /* so that the other threads won't be stuck */
329                 NtSetEvent( hRunOnce, &tmp );
330             }
331             return ret;
332         }
333         
334         /* someone beat us here... */
335         CloseHandle( hEvent );
336     }
337         
338     /* and wait for the winner to have actually created the debugger */
339     WaitForSingleObject( hRunOnce, INFINITE );
340     /* in fact, here, we only know that someone has tried to start the debugger,
341      * we'll know by reposting the exception if it has actually attached
342      * to the current process */
343     return TRUE;
344 }
345
346
347 /*******************************************************************
348  *         UnhandledExceptionFilter   (KERNEL32.@)
349  */
350 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
351 {
352     int                 status;
353     int                 loop = 0;
354
355     for (loop = 0; loop <= 1; loop++)
356     {
357         /* send a last chance event to the debugger */
358         status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
359         switch (status)
360         {
361         case DBG_CONTINUE: 
362             return EXCEPTION_CONTINUE_EXECUTION;
363         case DBG_EXCEPTION_NOT_HANDLED: 
364             TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
365             break; /* not reached */
366         case 0: /* no debugger is present */
367             if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
368             {
369                 /* do not launch the debugger on ^C, simply terminate the process */
370                 TerminateProcess( GetCurrentProcess(), 1 );
371             }
372             /* second try, the debugger isn't present... */
373             if (loop == 1) return EXCEPTION_EXECUTE_HANDLER;
374             break;
375         default:        
376             FIXME("Unsupported yet debug continue value %d (please report)\n", status);
377             return EXCEPTION_EXECUTE_HANDLER;
378         }
379
380         /* should only be there when loop == 0 */
381
382         if (top_filter)
383         {
384             DWORD ret = top_filter( epointers );
385             if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
386         }
387         
388         /* FIXME: Should check the current error mode */
389         
390         if (!start_debugger_atomic( epointers ))
391             return EXCEPTION_EXECUTE_HANDLER;
392         /* now that we should have a debugger attached, try to resend event */
393     }   
394         
395     return EXCEPTION_EXECUTE_HANDLER;
396 }
397
398
399 /***********************************************************************
400  *            SetUnhandledExceptionFilter   (KERNEL32.@)
401  */
402 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
403                                           LPTOP_LEVEL_EXCEPTION_FILTER filter )
404 {
405     LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
406     top_filter = filter;
407     return old;
408 }
409
410
411 /**************************************************************************
412  *           FatalAppExitA   (KERNEL32.@)
413  */
414 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
415 {
416     HMODULE mod = GetModuleHandleA( "user32.dll" );
417     MessageBoxA_funcptr pMessageBoxA = NULL;
418
419     WARN("AppExit\n");
420
421     if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
422     if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
423     else ERR( "%s\n", debugstr_a(str) );
424     ExitProcess(0);
425 }
426
427
428 /**************************************************************************
429  *           FatalAppExitW   (KERNEL32.@)
430  */
431 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
432 {
433     HMODULE mod = GetModuleHandleA( "user32.dll" );
434     MessageBoxW_funcptr pMessageBoxW = NULL;
435
436     WARN("AppExit\n");
437
438     if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
439     if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
440     else ERR( "%s\n", debugstr_w(str) );
441     ExitProcess(0);
442 }