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 int 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 (!wine_server_call(req
)) handle
= reply
->handle
;
195 if (!handle
) return 0; /* no debugger present or other error */
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
;
224 PROCESS_INFORMATION info
;
225 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 --debugmsg -all --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 TRACE("Starting debugger %s\n", debugstr_a(cmdline
));
333 memset(&startup
, 0, sizeof(startup
));
334 startup
.cb
= sizeof(startup
);
335 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
336 startup
.wShowWindow
= SW_SHOWNORMAL
;
337 ret
= CreateProcessA(NULL
, cmdline
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &startup
, &info
);
339 if (ret
) WaitForSingleObject(hEvent
, INFINITE
); /* wait for debugger to come up... */
340 else ERR("Couldn't start debugger (%s) (%ld)\n"
341 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
342 debugstr_a(cmdline
), GetLastError());
344 HeapFree(GetProcessHeap(), 0, cmdline
);
348 /******************************************************************
349 * start_debugger_atomic
351 * starts the debugger in an atomic way:
352 * - either the debugger is not started and it is started
353 * - or the debugger has already been started by another thread
354 * - or the debugger couldn't be started
356 * returns TRUE for the two first conditions, FALSE for the last
358 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers
)
360 static HANDLE hRunOnce
/* = 0 */;
364 OBJECT_ATTRIBUTES attr
;
367 attr
.Length
= sizeof(attr
);
368 attr
.RootDirectory
= 0;
369 attr
.Attributes
= OBJ_INHERIT
;
370 attr
.ObjectName
= NULL
;
371 attr
.SecurityDescriptor
= NULL
;
372 attr
.SecurityQualityOfService
= NULL
;
374 /* ask for manual reset, so that once the debugger is started,
375 * every thread will know it */
376 NtCreateEvent( &hEvent
, EVENT_ALL_ACCESS
, &attr
, TRUE
, FALSE
);
377 if (InterlockedCompareExchangePointer( (PVOID
)&hRunOnce
, hEvent
, 0 ) == 0)
379 /* ok, our event has been set... we're the winning thread */
380 BOOL ret
= start_debugger( epointers
, hRunOnce
);
385 /* so that the other threads won't be stuck */
386 NtSetEvent( hRunOnce
, &tmp
);
391 /* someone beat us here... */
392 CloseHandle( hEvent
);
395 /* and wait for the winner to have actually created the debugger */
396 WaitForSingleObject( hRunOnce
, INFINITE
);
397 /* in fact, here, we only know that someone has tried to start the debugger,
398 * we'll know by reposting the exception if it has actually attached
399 * to the current process */
404 /*******************************************************************
405 * check_resource_write
407 * Check if the exception is a write attempt to the resource data.
408 * If yes, we unprotect the resources to let broken apps continue
409 * (Windows does this too).
411 inline static BOOL
check_resource_write( const EXCEPTION_RECORD
*rec
)
415 MEMORY_BASIC_INFORMATION info
;
417 if (rec
->ExceptionCode
!= EXCEPTION_ACCESS_VIOLATION
) return FALSE
;
418 if (!rec
->ExceptionInformation
[0]) return FALSE
; /* not a write access */
419 addr
= (void *)rec
->ExceptionInformation
[1];
420 if (!VirtualQuery( addr
, &info
, sizeof(info
) )) return FALSE
;
421 if (!(rsrc
= RtlImageDirectoryEntryToData( (HMODULE
)info
.AllocationBase
, TRUE
,
422 IMAGE_DIRECTORY_ENTRY_RESOURCE
, &size
)))
424 if (addr
< rsrc
|| (char *)addr
>= (char *)rsrc
+ size
) return FALSE
;
425 FIXME( "Broken app is writing to the resource data, enabling work-around\n" );
426 VirtualProtect( rsrc
, size
, PAGE_WRITECOPY
, NULL
);
431 /*******************************************************************
432 * UnhandledExceptionFilter (KERNEL32.@)
434 DWORD WINAPI
UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers
)
439 if (check_resource_write( epointers
->ExceptionRecord
)) return EXCEPTION_CONTINUE_EXECUTION
;
441 for (loop
= 0; loop
<= 1; loop
++)
443 /* send a last chance event to the debugger */
444 status
= send_debug_event( epointers
->ExceptionRecord
, FALSE
, epointers
->ContextRecord
);
448 return EXCEPTION_CONTINUE_EXECUTION
;
449 case DBG_EXCEPTION_NOT_HANDLED
:
450 TerminateProcess( GetCurrentProcess(), epointers
->ExceptionRecord
->ExceptionCode
);
451 break; /* not reached */
452 case 0: /* no debugger is present */
453 if (epointers
->ExceptionRecord
->ExceptionCode
== CONTROL_C_EXIT
)
455 /* do not launch the debugger on ^C, simply terminate the process */
456 TerminateProcess( GetCurrentProcess(), 1 );
458 /* second try, the debugger isn't present... */
459 if (loop
== 1) return EXCEPTION_EXECUTE_HANDLER
;
462 FIXME("Unsupported yet debug continue value %d (please report)\n", status
);
463 return EXCEPTION_EXECUTE_HANDLER
;
466 /* should only be there when loop == 0 */
470 DWORD ret
= top_filter( epointers
);
471 if (ret
!= EXCEPTION_CONTINUE_SEARCH
) return ret
;
474 /* FIXME: Should check the current error mode */
476 if (!start_debugger_atomic( epointers
))
477 return EXCEPTION_EXECUTE_HANDLER
;
478 /* now that we should have a debugger attached, try to resend event */
481 return EXCEPTION_EXECUTE_HANDLER
;
485 /***********************************************************************
486 * SetUnhandledExceptionFilter (KERNEL32.@)
488 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI
SetUnhandledExceptionFilter(
489 LPTOP_LEVEL_EXCEPTION_FILTER filter
)
491 LPTOP_LEVEL_EXCEPTION_FILTER old
= top_filter
;
497 /**************************************************************************
498 * FatalAppExitA (KERNEL32.@)
500 void WINAPI
FatalAppExitA( UINT action
, LPCSTR str
)
502 HMODULE mod
= GetModuleHandleA( "user32.dll" );
503 MessageBoxA_funcptr pMessageBoxA
= NULL
;
507 if (mod
) pMessageBoxA
= (MessageBoxA_funcptr
)GetProcAddress( mod
, "MessageBoxA" );
508 if (pMessageBoxA
) pMessageBoxA( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
509 else ERR( "%s\n", debugstr_a(str
) );
514 /**************************************************************************
515 * FatalAppExitW (KERNEL32.@)
517 void WINAPI
FatalAppExitW( UINT action
, LPCWSTR str
)
519 static const WCHAR User32DllW
[] = {'u','s','e','r','3','2','.','d','l','l',0};
521 HMODULE mod
= GetModuleHandleW( User32DllW
);
522 MessageBoxW_funcptr pMessageBoxW
= NULL
;
526 if (mod
) pMessageBoxW
= (MessageBoxW_funcptr
)GetProcAddress( mod
, "MessageBoxW" );
527 if (pMessageBoxW
) pMessageBoxW( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
528 else ERR( "%s\n", debugstr_w(str
) );
533 /**************************************************************************
534 * FatalExit (KERNEL32.@)
536 void WINAPI
FatalExit(int ExitCode
)
539 ExitProcess(ExitCode
);