Make wine_server_fd_to_handle use attributes instead of inherit flag.
[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 #define WIN32_NO_STATUS
45 #include "windef.h"
46 #include "winbase.h"
47 #include "winerror.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, " at address 0x%04lx:0x%08lx",
166                         ptr->ContextRecord->SegCs,
167                         (DWORD)ptr->ExceptionRecord->ExceptionAddress);
168     else
169 #endif
170         len2 = snprintf(buffer+len, size-len, " at address %p",
171                         ptr->ExceptionRecord->ExceptionAddress);
172     if ((len2<0) || (len>=size-len))
173         return -1;
174     return len+len2;
175 }
176
177
178 /**********************************************************************
179  *           send_debug_event
180  *
181  * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
182  */
183 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
184 {
185     NTSTATUS ret;
186     HANDLE handle = 0;
187
188     SERVER_START_REQ( queue_exception_event )
189     {
190         req->first   = first_chance;
191         wine_server_add_data( req, context, sizeof(*context) );
192         wine_server_add_data( req, rec, sizeof(*rec) );
193         if (!(ret = wine_server_call( req ))) handle = reply->handle;
194     }
195     SERVER_END_REQ;
196     if (ret) return ret;
197
198     WaitForSingleObject( handle, INFINITE );
199
200     SERVER_START_REQ( get_exception_status )
201     {
202         req->handle = handle;
203         wine_server_set_reply( req, context, sizeof(*context) );
204         ret = wine_server_call( req );
205     }
206     SERVER_END_REQ;
207     return ret;
208 }
209
210 /******************************************************************
211  *              start_debugger
212  *
213  * Does the effective debugger startup according to 'format'
214  */
215 static BOOL     start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
216 {
217     OBJECT_ATTRIBUTES attr;
218     UNICODE_STRING nameW;
219     char *cmdline, *env, *p;
220     HANDLE              hDbgConf;
221     DWORD               bAuto = FALSE;
222     PROCESS_INFORMATION info;
223     STARTUPINFOA        startup;
224     char*               format = NULL;
225     BOOL                ret = FALSE;
226     char buffer[256];
227
228     static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
229                                      'S','o','f','t','w','a','r','e','\\',
230                                      'M','i','c','r','o','s','o','f','t','\\',
231                                      'W','i','n','d','o','w','s',' ','N','T','\\',
232                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
233                                      'A','e','D','e','b','u','g',0};
234     static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
235     static const WCHAR AutoW[] = {'A','u','t','o',0};
236
237     format_exception_msg( epointers, buffer, sizeof(buffer) );
238     MESSAGE("wine: %s (thread %04lx), starting debugger...\n", buffer, GetCurrentThreadId());
239
240     attr.Length = sizeof(attr);
241     attr.RootDirectory = 0;
242     attr.ObjectName = &nameW;
243     attr.Attributes = 0;
244     attr.SecurityDescriptor = NULL;
245     attr.SecurityQualityOfService = NULL;
246     RtlInitUnicodeString( &nameW, AeDebugW );
247
248     if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
249     {
250         char buffer[64];
251         KEY_VALUE_PARTIAL_INFORMATION *info;
252         DWORD format_size = 0;
253
254         RtlInitUnicodeString( &nameW, DebuggerW );
255         if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
256                              NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
257         {
258             char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
259             NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
260                              data, format_size, &format_size );
261             info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
262             RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
263             format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
264             RtlUnicodeToMultiByteN( format, format_size, NULL,
265                                     (WCHAR *)info->Data, info->DataLength );
266             format[format_size] = 0;
267
268             if (info->Type == REG_EXPAND_SZ)
269             {
270                 char* tmp;
271
272                 /* Expand environment variable references */
273                 format_size=ExpandEnvironmentStringsA(format,NULL,0);
274                 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
275                 ExpandEnvironmentStringsA(format,tmp,format_size);
276                 HeapFree(GetProcessHeap(), 0, format);
277                 format=tmp;
278             }
279             HeapFree( GetProcessHeap(), 0, data );
280         }
281
282         RtlInitUnicodeString( &nameW, AutoW );
283         if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
284                               buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
285        {
286            info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
287            if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
288            else if (info->Type == REG_SZ)
289            {
290                WCHAR *str = (WCHAR *)info->Data;
291                str[info->DataLength/sizeof(WCHAR)] = 0;
292                bAuto = atoiW( str );
293            }
294        }
295        else bAuto = TRUE;
296
297        NtClose(hDbgConf);
298     }
299
300     if (format)
301     {
302         cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
303         sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
304         HeapFree(GetProcessHeap(), 0, format);
305     }
306     else
307     {
308         cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
309         sprintf(cmdline, "winedbg --auto %ld %ld",
310                 GetCurrentProcessId(), (ULONG_PTR)hEvent);
311     }
312
313     if (!bAuto)
314     {
315         HMODULE                 mod = GetModuleHandleA( "user32.dll" );
316         MessageBoxA_funcptr     pMessageBoxA = NULL;
317
318         if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
319         if (pMessageBoxA)
320         {
321             static const char msg[] = ".\nDo you wish to debug it?";
322             char buffer[256];
323
324             format_exception_msg( epointers, buffer, sizeof(buffer)-sizeof(msg) );
325             strcat( buffer, msg );
326             if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
327             {
328                 TRACE("Killing process\n");
329                 goto EXIT;
330             }
331         }
332     }
333
334     /* make WINEDEBUG empty in the environment */
335     env = GetEnvironmentStringsA();
336     for (p = env; *p; p += strlen(p) + 1)
337     {
338         if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
339         {
340             char *next = p + strlen(p);
341             char *end = next + 1;
342             while (*end) end += strlen(end) + 1;
343             memmove( p + sizeof("WINEDEBUG=") - 1, next, end + 1 - next );
344             break;
345         }
346     }
347
348     TRACE("Starting debugger %s\n", debugstr_a(cmdline));
349     memset(&startup, 0, sizeof(startup));
350     startup.cb = sizeof(startup);
351     startup.dwFlags = STARTF_USESHOWWINDOW;
352     startup.wShowWindow = SW_SHOWNORMAL;
353     ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
354     FreeEnvironmentStringsA( env );
355
356     if (ret) WaitForSingleObject(hEvent, INFINITE);  /* wait for debugger to come up... */
357     else ERR("Couldn't start debugger (%s) (%ld)\n"
358              "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
359              debugstr_a(cmdline), GetLastError());
360 EXIT:
361     HeapFree(GetProcessHeap(), 0, cmdline);
362     return ret;
363 }
364
365 /******************************************************************
366  *              start_debugger_atomic
367  *
368  * starts the debugger in an atomic way:
369  *      - either the debugger is not started and it is started
370  *      - or the debugger has already been started by another thread
371  *      - or the debugger couldn't be started
372  *
373  * returns TRUE for the two first conditions, FALSE for the last
374  */
375 static  int     start_debugger_atomic(PEXCEPTION_POINTERS epointers)
376 {
377     static HANDLE       hRunOnce /* = 0 */;
378
379     if (hRunOnce == 0)
380     {
381         OBJECT_ATTRIBUTES       attr;
382         HANDLE                  hEvent;
383
384         attr.Length                   = sizeof(attr);
385         attr.RootDirectory            = 0;
386         attr.Attributes               = OBJ_INHERIT;
387         attr.ObjectName               = NULL;
388         attr.SecurityDescriptor       = NULL;
389         attr.SecurityQualityOfService = NULL;
390
391         /* ask for manual reset, so that once the debugger is started,
392          * every thread will know it */
393         NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
394         if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
395         {
396             /* ok, our event has been set... we're the winning thread */
397             BOOL        ret = start_debugger( epointers, hRunOnce );
398             DWORD       tmp;
399
400             if (!ret)
401             {
402                 /* so that the other threads won't be stuck */
403                 NtSetEvent( hRunOnce, &tmp );
404             }
405             return ret;
406         }
407
408         /* someone beat us here... */
409         CloseHandle( hEvent );
410     }
411
412     /* and wait for the winner to have actually created the debugger */
413     WaitForSingleObject( hRunOnce, INFINITE );
414     /* in fact, here, we only know that someone has tried to start the debugger,
415      * we'll know by reposting the exception if it has actually attached
416      * to the current process */
417     return TRUE;
418 }
419
420
421 /*******************************************************************
422  *         check_resource_write
423  *
424  * Check if the exception is a write attempt to the resource data.
425  * If yes, we unprotect the resources to let broken apps continue
426  * (Windows does this too).
427  */
428 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
429 {
430     void *addr, *rsrc;
431     DWORD size;
432     MEMORY_BASIC_INFORMATION info;
433
434     if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return FALSE;
435     if (rec->NumberParameters < 2) return FALSE;
436     if (!rec->ExceptionInformation[0]) return FALSE;  /* not a write access */
437     addr = (void *)rec->ExceptionInformation[1];
438     if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
439     if (info.State == MEM_FREE) return FALSE;
440     if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
441                                               IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
442         return FALSE;
443     if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
444     TRACE( "Broken app is writing to the resource data, enabling work-around\n" );
445     VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
446     return TRUE;
447 }
448
449
450 /*******************************************************************
451  *         UnhandledExceptionFilter   (KERNEL32.@)
452  */
453 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
454 {
455     NTSTATUS status;
456
457     if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
458
459     if (!NtCurrentTeb()->Peb->BeingDebugged)
460     {
461         if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
462         {
463             /* do not launch the debugger on ^C, simply terminate the process */
464             TerminateProcess( GetCurrentProcess(), 1 );
465         }
466
467         if (top_filter)
468         {
469             DWORD ret = top_filter( epointers );
470             if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
471         }
472
473         /* FIXME: Should check the current error mode */
474
475         if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
476             return EXCEPTION_EXECUTE_HANDLER;
477     }
478
479     /* send a last chance event to the debugger */
480     status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
481     switch (status)
482     {
483     case DBG_CONTINUE:
484         return EXCEPTION_CONTINUE_EXECUTION;
485     case DBG_EXCEPTION_NOT_HANDLED:
486         TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
487         break; /* not reached */
488     default:
489         FIXME("Unhandled error on debug event: %lx\n", status);
490         break;
491     }
492     return EXCEPTION_EXECUTE_HANDLER;
493 }
494
495
496 /***********************************************************************
497  *            SetUnhandledExceptionFilter   (KERNEL32.@)
498  */
499 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
500                                           LPTOP_LEVEL_EXCEPTION_FILTER filter )
501 {
502     LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
503     top_filter = filter;
504     return old;
505 }
506
507
508 /**************************************************************************
509  *           FatalAppExitA   (KERNEL32.@)
510  */
511 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
512 {
513     HMODULE mod = GetModuleHandleA( "user32.dll" );
514     MessageBoxA_funcptr pMessageBoxA = NULL;
515
516     WARN("AppExit\n");
517
518     if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
519     if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
520     else ERR( "%s\n", debugstr_a(str) );
521     ExitProcess(0);
522 }
523
524
525 /**************************************************************************
526  *           FatalAppExitW   (KERNEL32.@)
527  */
528 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
529 {
530     static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
531
532     HMODULE mod = GetModuleHandleW( User32DllW );
533     MessageBoxW_funcptr pMessageBoxW = NULL;
534
535     WARN("AppExit\n");
536
537     if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
538     if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
539     else ERR( "%s\n", debugstr_w(str) );
540     ExitProcess(0);
541 }
542
543
544 /**************************************************************************
545  *           FatalExit   (KERNEL32.@)
546  */
547 void WINAPI FatalExit(int ExitCode)
548 {
549     WARN("FatalExit\n");
550     ExitProcess(ExitCode);
551 }