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"
47 #include "wine/exception.h"
48 #include "wine/library.h"
50 #include "stackframe.h"
51 #include "msvcrt/excpt.h"
52 #include "wine/server.h"
53 #include "wine/unicode.h"
54 #include "wine/debug.h"
56 WINE_DEFAULT_DEBUG_CHANNEL(seh
);
58 static PTOP_LEVEL_EXCEPTION_FILTER top_filter
;
60 typedef INT (WINAPI
*MessageBoxA_funcptr
)(HWND
,LPCSTR
,LPCSTR
,UINT
);
61 typedef INT (WINAPI
*MessageBoxW_funcptr
)(HWND
,LPCWSTR
,LPCWSTR
,UINT
);
63 /*******************************************************************
64 * RaiseException (KERNEL32.@)
66 void WINAPI
RaiseException( DWORD code
, DWORD flags
, DWORD nbargs
, const LPDWORD args
)
68 EXCEPTION_RECORD record
;
70 /* Compose an exception record */
72 record
.ExceptionCode
= code
;
73 record
.ExceptionFlags
= flags
& EH_NONCONTINUABLE
;
74 record
.ExceptionRecord
= NULL
;
75 record
.ExceptionAddress
= RaiseException
;
78 if (nbargs
> EXCEPTION_MAXIMUM_PARAMETERS
) nbargs
= EXCEPTION_MAXIMUM_PARAMETERS
;
79 record
.NumberParameters
= nbargs
;
80 memcpy( record
.ExceptionInformation
, args
, nbargs
* sizeof(*args
) );
82 else record
.NumberParameters
= 0;
84 RtlRaiseException( &record
);
88 /*******************************************************************
89 * format_exception_msg
91 static int format_exception_msg( const EXCEPTION_POINTERS
*ptr
, char *buffer
, int size
)
93 const EXCEPTION_RECORD
*rec
= ptr
->ExceptionRecord
;
96 switch(rec
->ExceptionCode
)
98 case EXCEPTION_INT_DIVIDE_BY_ZERO
:
99 len
= snprintf( buffer
, size
, "Unhandled division by zero" );
101 case EXCEPTION_INT_OVERFLOW
:
102 len
= snprintf( buffer
, size
, "Unhandled overflow" );
104 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED
:
105 len
= snprintf( buffer
, size
, "Unhandled array bounds" );
107 case EXCEPTION_ILLEGAL_INSTRUCTION
:
108 len
= snprintf( buffer
, size
, "Unhandled illegal instruction" );
110 case EXCEPTION_STACK_OVERFLOW
:
111 len
= snprintf( buffer
, size
, "Unhandled stack overflow" );
113 case EXCEPTION_PRIV_INSTRUCTION
:
114 len
= snprintf( buffer
, size
, "Unhandled privileged instruction" );
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] ? "write" : "read",
120 rec
->ExceptionInformation
[1]);
122 len
= snprintf( buffer
, size
, "Unhandled page fault");
124 case EXCEPTION_DATATYPE_MISALIGNMENT
:
125 len
= snprintf( buffer
, size
, "Unhandled alignment" );
128 len
= snprintf( buffer
, size
, "Unhandled ^C");
130 case EXCEPTION_CRITICAL_SECTION_WAIT
:
131 len
= snprintf( buffer
, size
, "Critical section %08lx wait failed",
132 rec
->ExceptionInformation
[0]);
134 case EXCEPTION_WINE_STUB
:
135 len
= snprintf( buffer
, size
, "Unimplemented function %s.%s called",
136 (char *)rec
->ExceptionInformation
[0], (char *)rec
->ExceptionInformation
[1] );
138 case EXCEPTION_VM86_INTx
:
139 len
= snprintf( buffer
, size
, "Unhandled interrupt %02lx in vm86 mode",
140 rec
->ExceptionInformation
[0]);
142 case EXCEPTION_VM86_STI
:
143 len
= snprintf( buffer
, size
, "Unhandled sti in vm86 mode");
145 case EXCEPTION_VM86_PICRETURN
:
146 len
= snprintf( buffer
, size
, "Unhandled PIC return in vm86 mode");
149 len
= snprintf( buffer
, size
, "Unhandled exception 0x%08lx", rec
->ExceptionCode
);
152 if ((len
<0) || (len
>=size
))
155 if (ptr
->ContextRecord
->SegCs
!= wine_get_cs())
156 len2
= snprintf(buffer
+len
, size
-len
,
157 " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
158 ptr
->ContextRecord
->SegCs
,
159 (DWORD
)ptr
->ExceptionRecord
->ExceptionAddress
);
162 len2
= snprintf(buffer
+len
, size
-len
,
163 " at address 0x%08lx.\nDo you wish to debug it ?",
164 (DWORD
)ptr
->ExceptionRecord
->ExceptionAddress
);
165 if ((len2
<0) || (len
>=size
-len
))
171 /**********************************************************************
174 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
176 static int send_debug_event( EXCEPTION_RECORD
*rec
, int first_chance
, CONTEXT
*context
)
181 SERVER_START_REQ( queue_exception_event
)
183 req
->first
= first_chance
;
184 wine_server_add_data( req
, context
, sizeof(*context
) );
185 wine_server_add_data( req
, rec
, sizeof(*rec
) );
186 if (!wine_server_call(req
)) handle
= reply
->handle
;
189 if (!handle
) return 0; /* no debugger present or other error */
191 /* No need to wait on the handle since the process gets suspended
192 * once the event is passed to the debugger, so when we get back
193 * here the event has been continued already.
195 SERVER_START_REQ( get_exception_status
)
197 req
->handle
= handle
;
198 wine_server_set_reply( req
, context
, sizeof(*context
) );
199 wine_server_call( req
);
207 /******************************************************************
210 * Does the effective debugger startup according to 'format'
212 static BOOL
start_debugger(PEXCEPTION_POINTERS epointers
, HANDLE hEvent
)
214 OBJECT_ATTRIBUTES attr
;
215 UNICODE_STRING nameW
;
218 PROCESS_INFORMATION info
;
219 STARTUPINFOA startup
;
220 char* cmdline
= NULL
;
225 static const WCHAR AeDebugW
[] = {'M','a','c','h','i','n','e','\\',
226 'S','o','f','t','w','a','r','e','\\',
227 'M','i','c','r','o','s','o','f','t','\\',
228 'W','i','n','d','o','w','s',' ','N','T','\\',
229 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
230 'A','e','D','e','b','u','g',0};
231 static const WCHAR DebuggerW
[] = {'D','e','b','u','g','g','e','r',0};
232 static const WCHAR AutoW
[] = {'A','u','t','o',0};
234 MESSAGE("wine: Unhandled exception, starting debugger...\n");
236 attr
.Length
= sizeof(attr
);
237 attr
.RootDirectory
= 0;
238 attr
.ObjectName
= &nameW
;
240 attr
.SecurityDescriptor
= NULL
;
241 attr
.SecurityQualityOfService
= NULL
;
242 RtlInitUnicodeString( &nameW
, AeDebugW
);
244 if (!NtOpenKey( &hDbgConf
, KEY_ALL_ACCESS
, &attr
))
247 KEY_VALUE_PARTIAL_INFORMATION
*info
;
250 RtlInitUnicodeString( &nameW
, DebuggerW
);
251 if (NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
252 NULL
, 0, &format_size
) == STATUS_BUFFER_OVERFLOW
)
254 char *data
= HeapAlloc(GetProcessHeap(), 0, format_size
);
255 NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
256 data
, format_size
, &format_size
);
257 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)data
;
258 RtlUnicodeToMultiByteSize( &format_size
, (WCHAR
*)info
->Data
, info
->DataLength
);
259 format
= HeapAlloc( GetProcessHeap(), 0, format_size
+1 );
260 RtlUnicodeToMultiByteN( format
, format_size
, NULL
,
261 (WCHAR
*)info
->Data
, info
->DataLength
);
262 format
[format_size
] = 0;
264 if (info
->Type
== REG_EXPAND_SZ
)
268 /* Expand environment variable references */
269 format_size
=ExpandEnvironmentStringsA(format
,NULL
,0);
270 tmp
=HeapAlloc(GetProcessHeap(), 0, format_size
);
271 ExpandEnvironmentStringsA(format
,tmp
,format_size
);
272 HeapFree(GetProcessHeap(), 0, format
);
275 HeapFree( GetProcessHeap(), 0, data
);
278 RtlInitUnicodeString( &nameW
, AutoW
);
279 if (!NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
280 buffer
, sizeof(buffer
)-sizeof(WCHAR
), &format_size
))
282 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
283 if (info
->Type
== REG_DWORD
) memcpy( &bAuto
, info
->Data
, sizeof(DWORD
) );
284 else if (info
->Type
== REG_SZ
)
286 WCHAR
*str
= (WCHAR
*)info
->Data
;
287 str
[info
->DataLength
/sizeof(WCHAR
)] = 0;
288 bAuto
= atoiW( str
);
295 /* try a default setup... */
296 strcpy( format
, "winedbg --debugmsg -all --auto %ld %ld" );
301 HMODULE mod
= GetModuleHandleA( "user32.dll" );
302 MessageBoxA_funcptr pMessageBoxA
= NULL
;
304 if (mod
) pMessageBoxA
= (MessageBoxA_funcptr
)GetProcAddress( mod
, "MessageBoxA" );
308 format_exception_msg( epointers
, buffer
, sizeof(buffer
) );
309 if (pMessageBoxA( 0, buffer
, "Exception raised", MB_YESNO
| MB_ICONHAND
) == IDNO
)
311 TRACE("Killing process\n");
318 TRACE("Starting debugger (fmt=%s)\n", format
);
319 cmdline
=HeapAlloc(GetProcessHeap(), 0, format_size
+2*20);
320 sprintf(cmdline
, format
, GetCurrentProcessId(), hEvent
);
321 memset(&startup
, 0, sizeof(startup
));
322 startup
.cb
= sizeof(startup
);
323 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
324 startup
.wShowWindow
= SW_SHOWNORMAL
;
325 if (CreateProcessA(NULL
, cmdline
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &startup
, &info
)) {
326 /* wait for debugger to come up... */
327 WaitForSingleObject(hEvent
, INFINITE
);
334 ERR("Couldn't start debugger (%s) (%ld)\n"
335 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
336 debugstr_a(cmdline
), GetLastError());
340 HeapFree(GetProcessHeap(), 0, cmdline
);
342 HeapFree(GetProcessHeap(), 0, format
);
346 /******************************************************************
347 * start_debugger_atomic
349 * starts the debugger in an atomic way:
350 * - either the debugger is not started and it is started
351 * - or the debugger has already been started by another thread
352 * - or the debugger couldn't be started
354 * returns TRUE for the two first conditions, FALSE for the last
356 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers
)
358 static HANDLE hRunOnce
/* = 0 */;
362 OBJECT_ATTRIBUTES attr
;
365 attr
.Length
= sizeof(attr
);
366 attr
.RootDirectory
= 0;
367 attr
.Attributes
= OBJ_INHERIT
;
368 attr
.ObjectName
= NULL
;
369 attr
.SecurityDescriptor
= NULL
;
370 attr
.SecurityQualityOfService
= NULL
;
372 /* ask for manual reset, so that once the debugger is started,
373 * every thread will know it */
374 NtCreateEvent( &hEvent
, EVENT_ALL_ACCESS
, &attr
, TRUE
, FALSE
);
375 if (InterlockedCompareExchange( (LPLONG
)&hRunOnce
, hEvent
, 0 ) == 0)
377 /* ok, our event has been set... we're the winning thread */
378 BOOL ret
= start_debugger( epointers
, hRunOnce
);
383 /* so that the other threads won't be stuck */
384 NtSetEvent( hRunOnce
, &tmp
);
389 /* someone beat us here... */
390 CloseHandle( hEvent
);
393 /* and wait for the winner to have actually created the debugger */
394 WaitForSingleObject( hRunOnce
, INFINITE
);
395 /* in fact, here, we only know that someone has tried to start the debugger,
396 * we'll know by reposting the exception if it has actually attached
397 * to the current process */
402 /*******************************************************************
403 * check_resource_write
405 * Check if the exception is a write attempt to the resource data.
406 * If yes, we unprotect the resources to let broken apps continue
407 * (Windows does this too).
409 inline static BOOL
check_resource_write( const EXCEPTION_RECORD
*rec
)
413 MEMORY_BASIC_INFORMATION info
;
415 if (rec
->ExceptionCode
!= EXCEPTION_ACCESS_VIOLATION
) return FALSE
;
416 if (!rec
->ExceptionInformation
[0]) return FALSE
; /* not a write access */
417 addr
= (void *)rec
->ExceptionInformation
[1];
418 if (!VirtualQuery( addr
, &info
, sizeof(info
) )) return FALSE
;
419 if (!(rsrc
= RtlImageDirectoryEntryToData( (HMODULE
)info
.AllocationBase
, TRUE
,
420 IMAGE_DIRECTORY_ENTRY_RESOURCE
, &size
)))
422 if (addr
< rsrc
|| (char *)addr
>= (char *)rsrc
+ size
) return FALSE
;
423 FIXME( "Broken app is writing to the resource data, enabling work-around\n" );
424 VirtualProtect( rsrc
, size
, PAGE_WRITECOPY
, NULL
);
429 /*******************************************************************
430 * UnhandledExceptionFilter (KERNEL32.@)
432 DWORD WINAPI
UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers
)
437 if (check_resource_write( epointers
->ExceptionRecord
)) return EXCEPTION_CONTINUE_EXECUTION
;
439 for (loop
= 0; loop
<= 1; loop
++)
441 /* send a last chance event to the debugger */
442 status
= send_debug_event( epointers
->ExceptionRecord
, FALSE
, epointers
->ContextRecord
);
446 return EXCEPTION_CONTINUE_EXECUTION
;
447 case DBG_EXCEPTION_NOT_HANDLED
:
448 TerminateProcess( GetCurrentProcess(), epointers
->ExceptionRecord
->ExceptionCode
);
449 break; /* not reached */
450 case 0: /* no debugger is present */
451 if (epointers
->ExceptionRecord
->ExceptionCode
== CONTROL_C_EXIT
)
453 /* do not launch the debugger on ^C, simply terminate the process */
454 TerminateProcess( GetCurrentProcess(), 1 );
456 /* second try, the debugger isn't present... */
457 if (loop
== 1) return EXCEPTION_EXECUTE_HANDLER
;
460 FIXME("Unsupported yet debug continue value %d (please report)\n", status
);
461 return EXCEPTION_EXECUTE_HANDLER
;
464 /* should only be there when loop == 0 */
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
))
475 return EXCEPTION_EXECUTE_HANDLER
;
476 /* now that we should have a debugger attached, try to resend event */
479 return EXCEPTION_EXECUTE_HANDLER
;
483 /***********************************************************************
484 * SetUnhandledExceptionFilter (KERNEL32.@)
486 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI
SetUnhandledExceptionFilter(
487 LPTOP_LEVEL_EXCEPTION_FILTER filter
)
489 LPTOP_LEVEL_EXCEPTION_FILTER old
= top_filter
;
495 /**************************************************************************
496 * FatalAppExitA (KERNEL32.@)
498 void WINAPI
FatalAppExitA( UINT action
, LPCSTR str
)
500 HMODULE mod
= GetModuleHandleA( "user32.dll" );
501 MessageBoxA_funcptr pMessageBoxA
= NULL
;
505 if (mod
) pMessageBoxA
= (MessageBoxA_funcptr
)GetProcAddress( mod
, "MessageBoxA" );
506 if (pMessageBoxA
) pMessageBoxA( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
507 else ERR( "%s\n", debugstr_a(str
) );
512 /**************************************************************************
513 * FatalAppExitW (KERNEL32.@)
515 void WINAPI
FatalAppExitW( UINT action
, LPCWSTR str
)
517 HMODULE mod
= GetModuleHandleA( "user32.dll" );
518 MessageBoxW_funcptr pMessageBoxW
= NULL
;
522 if (mod
) pMessageBoxW
= (MessageBoxW_funcptr
)GetProcAddress( mod
, "MessageBoxW" );
523 if (pMessageBoxW
) pMessageBoxW( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
524 else ERR( "%s\n", debugstr_w(str
) );