2 * Win32 exception functions
4 * Copyright (c) 1996 Onno Hovers, (onno@stack.urc.tue.nl)
5 * Copyright (c) 1999 Alexandre Julliard
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.
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.
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
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
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).
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
39 #include "wine/port.h"
51 #include "wine/exception.h"
52 #include "wine/library.h"
55 #include "wine/server.h"
56 #include "wine/unicode.h"
57 #include "wine/debug.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(seh);
61 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
63 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
64 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
66 /*******************************************************************
67 * RaiseException (KERNEL32.@)
69 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const LPDWORD args )
71 EXCEPTION_RECORD record;
73 /* Compose an exception record */
75 record.ExceptionCode = code;
76 record.ExceptionFlags = flags & EH_NONCONTINUABLE;
77 record.ExceptionRecord = NULL;
78 record.ExceptionAddress = RaiseException;
81 if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
82 record.NumberParameters = nbargs;
83 memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
85 else record.NumberParameters = 0;
87 RtlRaiseException( &record );
91 /*******************************************************************
92 * format_exception_msg
94 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
96 const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
99 switch(rec->ExceptionCode)
101 case EXCEPTION_INT_DIVIDE_BY_ZERO:
102 len = snprintf( buffer, size, "Unhandled division by zero" );
104 case EXCEPTION_INT_OVERFLOW:
105 len = snprintf( buffer, size, "Unhandled overflow" );
107 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
108 len = snprintf( buffer, size, "Unhandled array bounds" );
110 case EXCEPTION_ILLEGAL_INSTRUCTION:
111 len = snprintf( buffer, size, "Unhandled illegal instruction" );
113 case EXCEPTION_STACK_OVERFLOW:
114 len = snprintf( buffer, size, "Unhandled stack overflow" );
116 case EXCEPTION_PRIV_INSTRUCTION:
117 len = snprintf( buffer, size, "Unhandled privileged instruction" );
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]);
125 len = snprintf( buffer, size, "Unhandled page fault");
127 case EXCEPTION_DATATYPE_MISALIGNMENT:
128 len = snprintf( buffer, size, "Unhandled alignment" );
131 len = snprintf( buffer, size, "Unhandled ^C");
133 case STATUS_POSSIBLE_DEADLOCK:
134 len = snprintf( buffer, size, "Critical section %08lx wait failed",
135 rec->ExceptionInformation[0]);
137 case EXCEPTION_WINE_STUB:
138 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
139 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
141 case EXCEPTION_WINE_ASSERTION:
142 len = snprintf( buffer, size, "Assertion failed" );
144 case EXCEPTION_VM86_INTx:
145 len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
146 rec->ExceptionInformation[0]);
148 case EXCEPTION_VM86_STI:
149 len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
151 case EXCEPTION_VM86_PICRETURN:
152 len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
155 len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
158 if ((len<0) || (len>=size))
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);
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))
177 /**********************************************************************
180 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
182 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
187 SERVER_START_REQ( queue_exception_event )
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;
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.
201 SERVER_START_REQ( get_exception_status )
203 req->handle = handle;
204 wine_server_set_reply( req, context, sizeof(*context) );
205 wine_server_call( req );
213 /******************************************************************
216 * Does the effective debugger startup according to 'format'
218 static BOOL start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
220 OBJECT_ATTRIBUTES attr;
221 UNICODE_STRING nameW;
222 char *cmdline, *env, *p;
225 PROCESS_INFORMATION info;
226 STARTUPINFOA startup;
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};
239 MESSAGE("wine: Unhandled exception (thread %04lx), starting debugger...\n", GetCurrentThreadId());
241 attr.Length = sizeof(attr);
242 attr.RootDirectory = 0;
243 attr.ObjectName = &nameW;
245 attr.SecurityDescriptor = NULL;
246 attr.SecurityQualityOfService = NULL;
247 RtlInitUnicodeString( &nameW, AeDebugW );
249 if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
252 KEY_VALUE_PARTIAL_INFORMATION *info;
253 DWORD format_size = 0;
255 RtlInitUnicodeString( &nameW, DebuggerW );
256 if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
257 NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
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;
269 if (info->Type == REG_EXPAND_SZ)
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);
280 HeapFree( GetProcessHeap(), 0, data );
283 RtlInitUnicodeString( &nameW, AutoW );
284 if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
285 buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
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)
291 WCHAR *str = (WCHAR *)info->Data;
292 str[info->DataLength/sizeof(WCHAR)] = 0;
293 bAuto = atoiW( str );
303 cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
304 sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
305 HeapFree(GetProcessHeap(), 0, format);
309 cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
310 sprintf(cmdline, "winedbg --auto %ld %ld",
311 GetCurrentProcessId(), (ULONG_PTR)hEvent);
316 HMODULE mod = GetModuleHandleA( "user32.dll" );
317 MessageBoxA_funcptr pMessageBoxA = NULL;
319 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
323 format_exception_msg( epointers, buffer, sizeof(buffer) );
324 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
326 TRACE("Killing process\n");
332 /* remove WINEDEBUG from the environment */
333 env = GetEnvironmentStringsA();
334 for (p = env; *p; p += strlen(p) + 1)
336 if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
338 char *next = p + strlen(p) + 1;
340 while (*end) end += strlen(end) + 1;
341 memmove( p, next, end + 1 - next );
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 );
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());
359 HeapFree(GetProcessHeap(), 0, cmdline);
363 /******************************************************************
364 * start_debugger_atomic
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
371 * returns TRUE for the two first conditions, FALSE for the last
373 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers)
375 static HANDLE hRunOnce /* = 0 */;
379 OBJECT_ATTRIBUTES attr;
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;
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)
394 /* ok, our event has been set... we're the winning thread */
395 BOOL ret = start_debugger( epointers, hRunOnce );
400 /* so that the other threads won't be stuck */
401 NtSetEvent( hRunOnce, &tmp );
406 /* someone beat us here... */
407 CloseHandle( hEvent );
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 */
419 /*******************************************************************
420 * check_resource_write
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).
426 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
430 MEMORY_BASIC_INFORMATION info;
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 )))
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 );
447 /*******************************************************************
448 * UnhandledExceptionFilter (KERNEL32.@)
450 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
454 if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
456 if (!NtCurrentTeb()->Peb->BeingDebugged)
458 if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
460 /* do not launch the debugger on ^C, simply terminate the process */
461 TerminateProcess( GetCurrentProcess(), 1 );
466 DWORD ret = top_filter( epointers );
467 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
470 /* FIXME: Should check the current error mode */
472 if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
473 return EXCEPTION_EXECUTE_HANDLER;
476 /* send a last chance event to the debugger */
477 status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
481 return EXCEPTION_CONTINUE_EXECUTION;
482 case DBG_EXCEPTION_NOT_HANDLED:
483 TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
484 break; /* not reached */
486 FIXME("Unhandled error on debug event: %lx\n", status);
489 return EXCEPTION_EXECUTE_HANDLER;
493 /***********************************************************************
494 * SetUnhandledExceptionFilter (KERNEL32.@)
496 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
497 LPTOP_LEVEL_EXCEPTION_FILTER filter )
499 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
505 /**************************************************************************
506 * FatalAppExitA (KERNEL32.@)
508 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
510 HMODULE mod = GetModuleHandleA( "user32.dll" );
511 MessageBoxA_funcptr pMessageBoxA = NULL;
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) );
522 /**************************************************************************
523 * FatalAppExitW (KERNEL32.@)
525 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
527 static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
529 HMODULE mod = GetModuleHandleW( User32DllW );
530 MessageBoxW_funcptr pMessageBoxW = NULL;
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) );
541 /**************************************************************************
542 * FatalExit (KERNEL32.@)
544 void WINAPI FatalExit(int ExitCode)
547 ExitProcess(ExitCode);