Removed the FailReadOnly option, this is now the default behavior.
[wine] / dlls / kernel / 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  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * Notes:
22  *  What really happens behind the scenes of those new
23  *  __try{...}__except(..){....}  and
24  *  __try{...}__finally{...}
25  *  statements is simply not documented by Microsoft. There could be different
26  *  reasons for this:
27  *  One reason could be that they try to hide the fact that exception
28  *  handling in Win32 looks almost the same as in OS/2 2.x.
29  *  Another reason could be that Microsoft does not want others to write
30  *  binary compatible implementations of the Win32 API (like us).
31  *
32  *  Whatever the reason, THIS SUCKS!! Ensuring portability or future
33  *  compatibility may be valid reasons to keep some things undocumented.
34  *  But exception handling is so basic to Win32 that it should be
35  *  documented!
36  *
37  */
38 #include "config.h"
39 #include "wine/port.h"
40
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include "ntstatus.h"
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winerror.h"
47 #include "winreg.h"
48 #include "winternl.h"
49 #include "wingdi.h"
50 #include "winuser.h"
51 #include "wine/exception.h"
52 #include "wine/library.h"
53 #include "thread.h"
54 #include "excpt.h"
55 #include "wine/server.h"
56 #include "wine/unicode.h"
57 #include "wine/debug.h"
58
59 WINE_DEFAULT_DEBUG_CHANNEL(seh);
60
61 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
62
63 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
64 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
65
66 /*******************************************************************
67  *         RaiseException  (KERNEL32.@)
68  */
69 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const LPDWORD args )
70 {
71     EXCEPTION_RECORD record;
72
73     /* Compose an exception record */
74
75     record.ExceptionCode    = code;
76     record.ExceptionFlags   = flags & EH_NONCONTINUABLE;
77     record.ExceptionRecord  = NULL;
78     record.ExceptionAddress = RaiseException;
79     if (nbargs && args)
80     {
81         if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
82         record.NumberParameters = nbargs;
83         memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
84     }
85     else record.NumberParameters = 0;
86
87     RtlRaiseException( &record );
88 }
89
90
91 /*******************************************************************
92  *         format_exception_msg
93  */
94 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
95 {
96     const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
97     int len,len2;
98
99     switch(rec->ExceptionCode)
100     {
101     case EXCEPTION_INT_DIVIDE_BY_ZERO:
102         len = snprintf( buffer, size, "Unhandled division by zero" );
103         break;
104     case EXCEPTION_INT_OVERFLOW:
105         len = snprintf( buffer, size, "Unhandled overflow" );
106         break;
107     case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
108         len = snprintf( buffer, size, "Unhandled array bounds" );
109         break;
110     case EXCEPTION_ILLEGAL_INSTRUCTION:
111         len = snprintf( buffer, size, "Unhandled illegal instruction" );
112         break;
113     case EXCEPTION_STACK_OVERFLOW:
114         len = snprintf( buffer, size, "Unhandled stack overflow" );
115         break;
116     case EXCEPTION_PRIV_INSTRUCTION:
117         len = snprintf( buffer, size, "Unhandled privileged instruction" );
118         break;
119     case EXCEPTION_ACCESS_VIOLATION:
120         if (rec->NumberParameters == 2)
121             len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
122                      rec->ExceptionInformation[0] ? "write" : "read",
123                      rec->ExceptionInformation[1]);
124         else
125             len = snprintf( buffer, size, "Unhandled page fault");
126         break;
127     case EXCEPTION_DATATYPE_MISALIGNMENT:
128         len = snprintf( buffer, size, "Unhandled alignment" );
129         break;
130     case CONTROL_C_EXIT:
131         len = snprintf( buffer, size, "Unhandled ^C");
132         break;
133     case STATUS_POSSIBLE_DEADLOCK:
134         len = snprintf( buffer, size, "Critical section %08lx wait failed",
135                  rec->ExceptionInformation[0]);
136         break;
137     case EXCEPTION_WINE_STUB:
138         len = snprintf( buffer, size, "Unimplemented function %s.%s called",
139                  (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
140         break;
141     case EXCEPTION_WINE_ASSERTION:
142         len = snprintf( buffer, size, "Assertion failed" );
143         break;
144     case EXCEPTION_VM86_INTx:
145         len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
146                  rec->ExceptionInformation[0]);
147         break;
148     case EXCEPTION_VM86_STI:
149         len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
150         break;
151     case EXCEPTION_VM86_PICRETURN:
152         len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
153         break;
154     default:
155         len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
156         break;
157     }
158     if ((len<0) || (len>=size))
159         return -1;
160 #ifdef __i386__
161     if (ptr->ContextRecord->SegCs != wine_get_cs())
162         len2 = snprintf(buffer+len, size-len,
163                         " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
164                         ptr->ContextRecord->SegCs,
165                         (DWORD)ptr->ExceptionRecord->ExceptionAddress);
166     else
167 #endif
168         len2 = snprintf(buffer+len, size-len,
169                         " at address 0x%08lx.\nDo you wish to debug it ?",
170                         (DWORD)ptr->ExceptionRecord->ExceptionAddress);
171     if ((len2<0) || (len>=size-len))
172         return -1;
173     return len+len2;
174 }
175
176
177 /**********************************************************************
178  *           send_debug_event
179  *
180  * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
181  */
182 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
183 {
184     NTSTATUS ret;
185     HANDLE handle = 0;
186
187     SERVER_START_REQ( queue_exception_event )
188     {
189         req->first   = first_chance;
190         wine_server_add_data( req, context, sizeof(*context) );
191         wine_server_add_data( req, rec, sizeof(*rec) );
192         if (!(ret = wine_server_call( req ))) handle = reply->handle;
193     }
194     SERVER_END_REQ;
195     if (ret) return ret;
196
197     /* No need to wait on the handle since the process gets suspended
198      * once the event is passed to the debugger, so when we get back
199      * here the event has been continued already.
200      */
201     SERVER_START_REQ( get_exception_status )
202     {
203         req->handle = handle;
204         wine_server_set_reply( req, context, sizeof(*context) );
205         wine_server_call( req );
206         ret = reply->status;
207     }
208     SERVER_END_REQ;
209     NtClose( handle );
210     return ret;
211 }
212
213 /******************************************************************
214  *              start_debugger
215  *
216  * Does the effective debugger startup according to 'format'
217  */
218 static BOOL     start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
219 {
220     OBJECT_ATTRIBUTES attr;
221     UNICODE_STRING nameW;
222     char *cmdline, *env, *p;
223     HKEY                hDbgConf;
224     DWORD               bAuto = FALSE;
225     PROCESS_INFORMATION info;
226     STARTUPINFOA        startup;
227     char*               format = NULL;
228     BOOL                ret = FALSE;
229
230     static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
231                                      'S','o','f','t','w','a','r','e','\\',
232                                      'M','i','c','r','o','s','o','f','t','\\',
233                                      'W','i','n','d','o','w','s',' ','N','T','\\',
234                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
235                                      'A','e','D','e','b','u','g',0};
236     static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
237     static const WCHAR AutoW[] = {'A','u','t','o',0};
238
239     MESSAGE("wine: Unhandled exception (thread %04lx), starting debugger...\n", GetCurrentThreadId());
240
241     attr.Length = sizeof(attr);
242     attr.RootDirectory = 0;
243     attr.ObjectName = &nameW;
244     attr.Attributes = 0;
245     attr.SecurityDescriptor = NULL;
246     attr.SecurityQualityOfService = NULL;
247     RtlInitUnicodeString( &nameW, AeDebugW );
248
249     if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
250     {
251         char buffer[64];
252         KEY_VALUE_PARTIAL_INFORMATION *info;
253         DWORD format_size = 0;
254
255         RtlInitUnicodeString( &nameW, DebuggerW );
256         if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
257                              NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
258         {
259             char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
260             NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
261                              data, format_size, &format_size );
262             info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
263             RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
264             format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
265             RtlUnicodeToMultiByteN( format, format_size, NULL,
266                                     (WCHAR *)info->Data, info->DataLength );
267             format[format_size] = 0;
268
269             if (info->Type == REG_EXPAND_SZ)
270             {
271                 char* tmp;
272
273                 /* Expand environment variable references */
274                 format_size=ExpandEnvironmentStringsA(format,NULL,0);
275                 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
276                 ExpandEnvironmentStringsA(format,tmp,format_size);
277                 HeapFree(GetProcessHeap(), 0, format);
278                 format=tmp;
279             }
280             HeapFree( GetProcessHeap(), 0, data );
281         }
282
283         RtlInitUnicodeString( &nameW, AutoW );
284         if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
285                               buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
286        {
287            info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
288            if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
289            else if (info->Type == REG_SZ)
290            {
291                WCHAR *str = (WCHAR *)info->Data;
292                str[info->DataLength/sizeof(WCHAR)] = 0;
293                bAuto = atoiW( str );
294            }
295        }
296        else bAuto = TRUE;
297
298        NtClose(hDbgConf);
299     }
300
301     if (format)
302     {
303         cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
304         sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
305         HeapFree(GetProcessHeap(), 0, format);
306     }
307     else
308     {
309         cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
310         sprintf(cmdline, "winedbg --auto %ld %ld",
311                 GetCurrentProcessId(), (ULONG_PTR)hEvent);
312     }
313
314     if (!bAuto)
315     {
316         HMODULE                 mod = GetModuleHandleA( "user32.dll" );
317         MessageBoxA_funcptr     pMessageBoxA = NULL;
318
319         if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
320         if (pMessageBoxA)
321         {
322             char buffer[256];
323             format_exception_msg( epointers, buffer, sizeof(buffer) );
324             if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
325             {
326                 TRACE("Killing process\n");
327                 goto EXIT;
328             }
329         }
330     }
331
332     /* remove WINEDEBUG from the environment */
333     env = GetEnvironmentStringsA();
334     for (p = env; *p; p += strlen(p) + 1)
335     {
336         if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
337         {
338             char *next = p + strlen(p) + 1;
339             char *end = next;
340             while (*end) end += strlen(end) + 1;
341             memmove( p, next, end + 1 - next );
342             break;
343         }
344     }
345
346     TRACE("Starting debugger %s\n", debugstr_a(cmdline));
347     memset(&startup, 0, sizeof(startup));
348     startup.cb = sizeof(startup);
349     startup.dwFlags = STARTF_USESHOWWINDOW;
350     startup.wShowWindow = SW_SHOWNORMAL;
351     ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
352     FreeEnvironmentStringsA( env );
353
354     if (ret) WaitForSingleObject(hEvent, INFINITE);  /* wait for debugger to come up... */
355     else ERR("Couldn't start debugger (%s) (%ld)\n"
356              "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
357              debugstr_a(cmdline), GetLastError());
358 EXIT:
359     HeapFree(GetProcessHeap(), 0, cmdline);
360     return ret;
361 }
362
363 /******************************************************************
364  *              start_debugger_atomic
365  *
366  * starts the debugger in an atomic way:
367  *      - either the debugger is not started and it is started
368  *      - or the debugger has already been started by another thread
369  *      - or the debugger couldn't be started
370  *
371  * returns TRUE for the two first conditions, FALSE for the last
372  */
373 static  int     start_debugger_atomic(PEXCEPTION_POINTERS epointers)
374 {
375     static HANDLE       hRunOnce /* = 0 */;
376
377     if (hRunOnce == 0)
378     {
379         OBJECT_ATTRIBUTES       attr;
380         HANDLE                  hEvent;
381
382         attr.Length                   = sizeof(attr);
383         attr.RootDirectory            = 0;
384         attr.Attributes               = OBJ_INHERIT;
385         attr.ObjectName               = NULL;
386         attr.SecurityDescriptor       = NULL;
387         attr.SecurityQualityOfService = NULL;
388
389         /* ask for manual reset, so that once the debugger is started,
390          * every thread will know it */
391         NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
392         if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
393         {
394             /* ok, our event has been set... we're the winning thread */
395             BOOL        ret = start_debugger( epointers, hRunOnce );
396             DWORD       tmp;
397
398             if (!ret)
399             {
400                 /* so that the other threads won't be stuck */
401                 NtSetEvent( hRunOnce, &tmp );
402             }
403             return ret;
404         }
405
406         /* someone beat us here... */
407         CloseHandle( hEvent );
408     }
409
410     /* and wait for the winner to have actually created the debugger */
411     WaitForSingleObject( hRunOnce, INFINITE );
412     /* in fact, here, we only know that someone has tried to start the debugger,
413      * we'll know by reposting the exception if it has actually attached
414      * to the current process */
415     return TRUE;
416 }
417
418
419 /*******************************************************************
420  *         check_resource_write
421  *
422  * Check if the exception is a write attempt to the resource data.
423  * If yes, we unprotect the resources to let broken apps continue
424  * (Windows does this too).
425  */
426 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
427 {
428     void *addr, *rsrc;
429     DWORD size;
430     MEMORY_BASIC_INFORMATION info;
431
432     if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return FALSE;
433     if (rec->NumberParameters < 2) return FALSE;
434     if (!rec->ExceptionInformation[0]) return FALSE;  /* not a write access */
435     addr = (void *)rec->ExceptionInformation[1];
436     if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
437     if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
438                                               IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
439         return FALSE;
440     if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
441     FIXME( "Broken app is writing to the resource data, enabling work-around\n" );
442     VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
443     return TRUE;
444 }
445
446
447 /*******************************************************************
448  *         UnhandledExceptionFilter   (KERNEL32.@)
449  */
450 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
451 {
452     NTSTATUS status;
453
454     if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
455
456     if (!NtCurrentTeb()->Peb->BeingDebugged)
457     {
458         if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
459         {
460             /* do not launch the debugger on ^C, simply terminate the process */
461             TerminateProcess( GetCurrentProcess(), 1 );
462         }
463
464         if (top_filter)
465         {
466             DWORD ret = top_filter( epointers );
467             if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
468         }
469
470         /* FIXME: Should check the current error mode */
471
472         if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
473             return EXCEPTION_EXECUTE_HANDLER;
474     }
475
476     /* send a last chance event to the debugger */
477     status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
478     switch (status)
479     {
480     case DBG_CONTINUE:
481         return EXCEPTION_CONTINUE_EXECUTION;
482     case DBG_EXCEPTION_NOT_HANDLED:
483         TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
484         break; /* not reached */
485     default:
486         FIXME("Unhandled error on debug event: %lx\n", status);
487         break;
488     }
489     return EXCEPTION_EXECUTE_HANDLER;
490 }
491
492
493 /***********************************************************************
494  *            SetUnhandledExceptionFilter   (KERNEL32.@)
495  */
496 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
497                                           LPTOP_LEVEL_EXCEPTION_FILTER filter )
498 {
499     LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
500     top_filter = filter;
501     return old;
502 }
503
504
505 /**************************************************************************
506  *           FatalAppExitA   (KERNEL32.@)
507  */
508 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
509 {
510     HMODULE mod = GetModuleHandleA( "user32.dll" );
511     MessageBoxA_funcptr pMessageBoxA = NULL;
512
513     WARN("AppExit\n");
514
515     if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
516     if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
517     else ERR( "%s\n", debugstr_a(str) );
518     ExitProcess(0);
519 }
520
521
522 /**************************************************************************
523  *           FatalAppExitW   (KERNEL32.@)
524  */
525 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
526 {
527     static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
528
529     HMODULE mod = GetModuleHandleW( User32DllW );
530     MessageBoxW_funcptr pMessageBoxW = NULL;
531
532     WARN("AppExit\n");
533
534     if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
535     if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
536     else ERR( "%s\n", debugstr_w(str) );
537     ExitProcess(0);
538 }
539
540
541 /**************************************************************************
542  *           FatalExit   (KERNEL32.@)
543  */
544 void WINAPI FatalExit(int ExitCode)
545 {
546     WARN("FatalExit\n");
547     ExitProcess(ExitCode);
548 }