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"
50 #include "wine/exception.h"
51 #include "wine/library.h"
53 #include "wine/server.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
57 WINE_DEFAULT_DEBUG_CHANNEL(seh);
59 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
61 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
62 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
64 /*******************************************************************
65 * RaiseException (KERNEL32.@)
67 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const ULONG_PTR *args )
69 EXCEPTION_RECORD record;
71 /* Compose an exception record */
73 record.ExceptionCode = code;
74 record.ExceptionFlags = flags & EH_NONCONTINUABLE;
75 record.ExceptionRecord = NULL;
76 record.ExceptionAddress = RaiseException;
79 if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
80 record.NumberParameters = nbargs;
81 memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
83 else record.NumberParameters = 0;
85 RtlRaiseException( &record );
89 /*******************************************************************
90 * format_exception_msg
92 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
94 const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
97 switch(rec->ExceptionCode)
99 case EXCEPTION_INT_DIVIDE_BY_ZERO:
100 len = snprintf( buffer, size, "Unhandled division by zero" );
102 case EXCEPTION_INT_OVERFLOW:
103 len = snprintf( buffer, size, "Unhandled overflow" );
105 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
106 len = snprintf( buffer, size, "Unhandled array bounds" );
108 case EXCEPTION_ILLEGAL_INSTRUCTION:
109 len = snprintf( buffer, size, "Unhandled illegal instruction" );
111 case EXCEPTION_STACK_OVERFLOW:
112 len = snprintf( buffer, size, "Unhandled stack overflow" );
114 case EXCEPTION_PRIV_INSTRUCTION:
115 len = snprintf( buffer, size, "Unhandled privileged instruction" );
117 case EXCEPTION_ACCESS_VIOLATION:
118 if (rec->NumberParameters == 2)
119 len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
120 rec->ExceptionInformation[0] ? "write" : "read",
121 rec->ExceptionInformation[1]);
123 len = snprintf( buffer, size, "Unhandled page fault");
125 case EXCEPTION_DATATYPE_MISALIGNMENT:
126 len = snprintf( buffer, size, "Unhandled alignment" );
129 len = snprintf( buffer, size, "Unhandled ^C");
131 case STATUS_POSSIBLE_DEADLOCK:
132 len = snprintf( buffer, size, "Critical section %08lx wait failed",
133 rec->ExceptionInformation[0]);
135 case EXCEPTION_WINE_STUB:
136 if (HIWORD(rec->ExceptionInformation[1]))
137 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
138 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
140 len = snprintf( buffer, size, "Unimplemented function %s.%ld called",
141 (char *)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
143 case EXCEPTION_WINE_ASSERTION:
144 len = snprintf( buffer, size, "Assertion failed" );
146 case EXCEPTION_VM86_INTx:
147 len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
148 rec->ExceptionInformation[0]);
150 case EXCEPTION_VM86_STI:
151 len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
153 case EXCEPTION_VM86_PICRETURN:
154 len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
157 len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
160 if ((len<0) || (len>=size))
163 if (ptr->ContextRecord->SegCs != wine_get_cs())
164 len2 = snprintf(buffer+len, size-len, " at address 0x%04lx:0x%08lx",
165 ptr->ContextRecord->SegCs,
166 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
169 len2 = snprintf(buffer+len, size-len, " at address %p",
170 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 WaitForSingleObject( handle, INFINITE );
199 SERVER_START_REQ( get_exception_status )
201 req->handle = handle;
202 wine_server_set_reply( req, context, sizeof(*context) );
203 ret = wine_server_call( req );
209 /******************************************************************
212 * Does the effective debugger startup according to 'format'
214 static BOOL start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
216 OBJECT_ATTRIBUTES attr;
217 UNICODE_STRING nameW;
218 char *cmdline, *env, *p;
221 PROCESS_INFORMATION info;
222 STARTUPINFOA startup;
227 static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
228 'S','o','f','t','w','a','r','e','\\',
229 'M','i','c','r','o','s','o','f','t','\\',
230 'W','i','n','d','o','w','s',' ','N','T','\\',
231 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
232 'A','e','D','e','b','u','g',0};
233 static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
234 static const WCHAR AutoW[] = {'A','u','t','o',0};
236 format_exception_msg( epointers, buffer, sizeof(buffer) );
237 MESSAGE("wine: %s (thread %04lx), starting debugger...\n", buffer, GetCurrentThreadId());
239 attr.Length = sizeof(attr);
240 attr.RootDirectory = 0;
241 attr.ObjectName = &nameW;
243 attr.SecurityDescriptor = NULL;
244 attr.SecurityQualityOfService = NULL;
245 RtlInitUnicodeString( &nameW, AeDebugW );
247 if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
250 KEY_VALUE_PARTIAL_INFORMATION *info;
251 DWORD format_size = 0;
253 RtlInitUnicodeString( &nameW, DebuggerW );
254 if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
255 NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
257 char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
258 NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
259 data, format_size, &format_size );
260 info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
261 RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
262 format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
263 RtlUnicodeToMultiByteN( format, format_size, NULL,
264 (WCHAR *)info->Data, info->DataLength );
265 format[format_size] = 0;
267 if (info->Type == REG_EXPAND_SZ)
271 /* Expand environment variable references */
272 format_size=ExpandEnvironmentStringsA(format,NULL,0);
273 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
274 ExpandEnvironmentStringsA(format,tmp,format_size);
275 HeapFree(GetProcessHeap(), 0, format);
278 HeapFree( GetProcessHeap(), 0, data );
281 RtlInitUnicodeString( &nameW, AutoW );
282 if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
283 buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
285 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
286 if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
287 else if (info->Type == REG_SZ)
289 WCHAR *str = (WCHAR *)info->Data;
290 str[info->DataLength/sizeof(WCHAR)] = 0;
291 bAuto = atoiW( str );
301 cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
302 sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
303 HeapFree(GetProcessHeap(), 0, format);
307 cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
308 sprintf(cmdline, "winedbg --auto %ld %ld",
309 GetCurrentProcessId(), (ULONG_PTR)hEvent);
314 HMODULE mod = GetModuleHandleA( "user32.dll" );
315 MessageBoxA_funcptr pMessageBoxA = NULL;
317 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
320 static const char msg[] = ".\nDo you wish to debug it?";
323 format_exception_msg( epointers, buffer, sizeof(buffer)-sizeof(msg) );
324 strcat( buffer, msg );
325 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
327 TRACE("Killing process\n");
333 /* make WINEDEBUG empty in the environment */
334 env = GetEnvironmentStringsA();
335 for (p = env; *p; p += strlen(p) + 1)
337 if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
339 char *next = p + strlen(p);
340 char *end = next + 1;
341 while (*end) end += strlen(end) + 1;
342 memmove( p + sizeof("WINEDEBUG=") - 1, next, end + 1 - next );
347 TRACE("Starting debugger %s\n", debugstr_a(cmdline));
348 memset(&startup, 0, sizeof(startup));
349 startup.cb = sizeof(startup);
350 startup.dwFlags = STARTF_USESHOWWINDOW;
351 startup.wShowWindow = SW_SHOWNORMAL;
352 ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
353 FreeEnvironmentStringsA( env );
355 if (ret) WaitForSingleObject(hEvent, INFINITE); /* wait for debugger to come up... */
356 else ERR("Couldn't start debugger (%s) (%ld)\n"
357 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
358 debugstr_a(cmdline), GetLastError());
360 HeapFree(GetProcessHeap(), 0, cmdline);
364 /******************************************************************
365 * start_debugger_atomic
367 * starts the debugger in an atomic way:
368 * - either the debugger is not started and it is started
369 * - or the debugger has already been started by another thread
370 * - or the debugger couldn't be started
372 * returns TRUE for the two first conditions, FALSE for the last
374 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers)
376 static HANDLE hRunOnce /* = 0 */;
380 OBJECT_ATTRIBUTES attr;
383 attr.Length = sizeof(attr);
384 attr.RootDirectory = 0;
385 attr.Attributes = OBJ_INHERIT;
386 attr.ObjectName = NULL;
387 attr.SecurityDescriptor = NULL;
388 attr.SecurityQualityOfService = NULL;
390 /* ask for manual reset, so that once the debugger is started,
391 * every thread will know it */
392 NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
393 if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
395 /* ok, our event has been set... we're the winning thread */
396 BOOL ret = start_debugger( epointers, hRunOnce );
401 /* so that the other threads won't be stuck */
402 NtSetEvent( hRunOnce, &tmp );
407 /* someone beat us here... */
408 CloseHandle( hEvent );
411 /* and wait for the winner to have actually created the debugger */
412 WaitForSingleObject( hRunOnce, INFINITE );
413 /* in fact, here, we only know that someone has tried to start the debugger,
414 * we'll know by reposting the exception if it has actually attached
415 * to the current process */
420 /*******************************************************************
421 * check_resource_write
423 * Check if the exception is a write attempt to the resource data.
424 * If yes, we unprotect the resources to let broken apps continue
425 * (Windows does this too).
427 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
431 MEMORY_BASIC_INFORMATION info;
433 if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return FALSE;
434 if (rec->NumberParameters < 2) return FALSE;
435 if (!rec->ExceptionInformation[0]) return FALSE; /* not a write access */
436 addr = (void *)rec->ExceptionInformation[1];
437 if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
438 if (info.State == MEM_FREE) return FALSE;
439 if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
440 IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
442 if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
443 TRACE( "Broken app is writing to the resource data, enabling work-around\n" );
444 VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
449 /*******************************************************************
450 * UnhandledExceptionFilter (KERNEL32.@)
452 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
456 if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
458 if (!NtCurrentTeb()->Peb->BeingDebugged)
460 if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
462 /* do not launch the debugger on ^C, simply terminate the process */
463 TerminateProcess( GetCurrentProcess(), 1 );
468 DWORD ret = top_filter( epointers );
469 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
472 /* FIXME: Should check the current error mode */
474 if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
475 return EXCEPTION_EXECUTE_HANDLER;
478 /* send a last chance event to the debugger */
479 status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
483 return EXCEPTION_CONTINUE_EXECUTION;
484 case DBG_EXCEPTION_NOT_HANDLED:
485 TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
486 break; /* not reached */
488 FIXME("Unhandled error on debug event: %lx\n", status);
491 return EXCEPTION_EXECUTE_HANDLER;
495 /***********************************************************************
496 * SetUnhandledExceptionFilter (KERNEL32.@)
498 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
499 LPTOP_LEVEL_EXCEPTION_FILTER filter )
501 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
507 /**************************************************************************
508 * FatalAppExitA (KERNEL32.@)
510 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
512 HMODULE mod = GetModuleHandleA( "user32.dll" );
513 MessageBoxA_funcptr pMessageBoxA = NULL;
517 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
518 if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
519 else ERR( "%s\n", debugstr_a(str) );
524 /**************************************************************************
525 * FatalAppExitW (KERNEL32.@)
527 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
529 static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
531 HMODULE mod = GetModuleHandleW( User32DllW );
532 MessageBoxW_funcptr pMessageBoxW = NULL;
536 if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
537 if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
538 else ERR( "%s\n", debugstr_w(str) );
543 /**************************************************************************
544 * FatalExit (KERNEL32.@)
546 void WINAPI FatalExit(int ExitCode)
549 ExitProcess(ExitCode);