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