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