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
;
224 static const WCHAR AeDebugW
[] = {'M','a','c','h','i','n','e','\\',
225 'S','o','f','t','w','a','r','e','\\',
226 'M','i','c','r','o','s','o','f','t','\\',
227 'W','i','n','d','o','w','s',' ','N','T','\\',
228 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
229 'A','e','D','e','b','u','g',0};
230 static const WCHAR DebuggerW
[] = {'D','e','b','u','g','g','e','r',0};
231 static const WCHAR AutoW
[] = {'A','u','t','o',0};
233 MESSAGE("wine: Unhandled exception, starting debugger...\n");
235 attr
.Length
= sizeof(attr
);
236 attr
.RootDirectory
= 0;
237 attr
.ObjectName
= &nameW
;
239 attr
.SecurityDescriptor
= NULL
;
240 attr
.SecurityQualityOfService
= NULL
;
241 RtlInitUnicodeString( &nameW
, AeDebugW
);
243 if (!NtOpenKey( &hDbgConf
, KEY_ALL_ACCESS
, &attr
))
246 KEY_VALUE_PARTIAL_INFORMATION
*info
;
247 DWORD format_size
= 0;
249 RtlInitUnicodeString( &nameW
, DebuggerW
);
250 if (NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
251 NULL
, 0, &format_size
) == STATUS_BUFFER_OVERFLOW
)
253 char *data
= HeapAlloc(GetProcessHeap(), 0, format_size
);
254 NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
255 data
, format_size
, &format_size
);
256 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)data
;
257 RtlUnicodeToMultiByteSize( &format_size
, (WCHAR
*)info
->Data
, info
->DataLength
);
258 format
= HeapAlloc( GetProcessHeap(), 0, format_size
+1 );
259 RtlUnicodeToMultiByteN( format
, format_size
, NULL
,
260 (WCHAR
*)info
->Data
, info
->DataLength
);
261 format
[format_size
] = 0;
263 if (info
->Type
== REG_EXPAND_SZ
)
267 /* Expand environment variable references */
268 format_size
=ExpandEnvironmentStringsA(format
,NULL
,0);
269 tmp
=HeapAlloc(GetProcessHeap(), 0, format_size
);
270 ExpandEnvironmentStringsA(format
,tmp
,format_size
);
271 HeapFree(GetProcessHeap(), 0, format
);
274 HeapFree( GetProcessHeap(), 0, data
);
277 RtlInitUnicodeString( &nameW
, AutoW
);
278 if (!NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
279 buffer
, sizeof(buffer
)-sizeof(WCHAR
), &format_size
))
281 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
282 if (info
->Type
== REG_DWORD
) memcpy( &bAuto
, info
->Data
, sizeof(DWORD
) );
283 else if (info
->Type
== REG_SZ
)
285 WCHAR
*str
= (WCHAR
*)info
->Data
;
286 str
[info
->DataLength
/sizeof(WCHAR
)] = 0;
287 bAuto
= atoiW( str
);
297 cmdline
= HeapAlloc(GetProcessHeap(), 0, strlen(format
) + 2*20);
298 sprintf(cmdline
, format
, GetCurrentProcessId(), hEvent
);
299 HeapFree(GetProcessHeap(), 0, format
);
303 cmdline
= HeapAlloc(GetProcessHeap(), 0, 80);
304 sprintf(cmdline
, "winedbg --debugmsg -all --auto %ld %d", GetCurrentProcessId(), hEvent
);
309 HMODULE mod
= GetModuleHandleA( "user32.dll" );
310 MessageBoxA_funcptr pMessageBoxA
= NULL
;
312 if (mod
) pMessageBoxA
= (MessageBoxA_funcptr
)GetProcAddress( mod
, "MessageBoxA" );
316 format_exception_msg( epointers
, buffer
, sizeof(buffer
) );
317 if (pMessageBoxA( 0, buffer
, "Exception raised", MB_YESNO
| MB_ICONHAND
) == IDNO
)
319 TRACE("Killing process\n");
325 TRACE("Starting debugger %s\n", debugstr_a(cmdline
));
326 memset(&startup
, 0, sizeof(startup
));
327 startup
.cb
= sizeof(startup
);
328 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
329 startup
.wShowWindow
= SW_SHOWNORMAL
;
330 ret
= CreateProcessA(NULL
, cmdline
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &startup
, &info
);
332 if (ret
) WaitForSingleObject(hEvent
, INFINITE
); /* wait for debugger to come up... */
333 else ERR("Couldn't start debugger (%s) (%ld)\n"
334 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
335 debugstr_a(cmdline
), GetLastError());
337 HeapFree(GetProcessHeap(), 0, cmdline
);
341 /******************************************************************
342 * start_debugger_atomic
344 * starts the debugger in an atomic way:
345 * - either the debugger is not started and it is started
346 * - or the debugger has already been started by another thread
347 * - or the debugger couldn't be started
349 * returns TRUE for the two first conditions, FALSE for the last
351 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers
)
353 static HANDLE hRunOnce
/* = 0 */;
357 OBJECT_ATTRIBUTES attr
;
360 attr
.Length
= sizeof(attr
);
361 attr
.RootDirectory
= 0;
362 attr
.Attributes
= OBJ_INHERIT
;
363 attr
.ObjectName
= NULL
;
364 attr
.SecurityDescriptor
= NULL
;
365 attr
.SecurityQualityOfService
= NULL
;
367 /* ask for manual reset, so that once the debugger is started,
368 * every thread will know it */
369 NtCreateEvent( &hEvent
, EVENT_ALL_ACCESS
, &attr
, TRUE
, FALSE
);
370 if (InterlockedCompareExchange( (LPLONG
)&hRunOnce
, hEvent
, 0 ) == 0)
372 /* ok, our event has been set... we're the winning thread */
373 BOOL ret
= start_debugger( epointers
, hRunOnce
);
378 /* so that the other threads won't be stuck */
379 NtSetEvent( hRunOnce
, &tmp
);
384 /* someone beat us here... */
385 CloseHandle( hEvent
);
388 /* and wait for the winner to have actually created the debugger */
389 WaitForSingleObject( hRunOnce
, INFINITE
);
390 /* in fact, here, we only know that someone has tried to start the debugger,
391 * we'll know by reposting the exception if it has actually attached
392 * to the current process */
397 /*******************************************************************
398 * check_resource_write
400 * Check if the exception is a write attempt to the resource data.
401 * If yes, we unprotect the resources to let broken apps continue
402 * (Windows does this too).
404 inline static BOOL
check_resource_write( const EXCEPTION_RECORD
*rec
)
408 MEMORY_BASIC_INFORMATION info
;
410 if (rec
->ExceptionCode
!= EXCEPTION_ACCESS_VIOLATION
) return FALSE
;
411 if (!rec
->ExceptionInformation
[0]) return FALSE
; /* not a write access */
412 addr
= (void *)rec
->ExceptionInformation
[1];
413 if (!VirtualQuery( addr
, &info
, sizeof(info
) )) return FALSE
;
414 if (!(rsrc
= RtlImageDirectoryEntryToData( (HMODULE
)info
.AllocationBase
, TRUE
,
415 IMAGE_DIRECTORY_ENTRY_RESOURCE
, &size
)))
417 if (addr
< rsrc
|| (char *)addr
>= (char *)rsrc
+ size
) return FALSE
;
418 FIXME( "Broken app is writing to the resource data, enabling work-around\n" );
419 VirtualProtect( rsrc
, size
, PAGE_WRITECOPY
, NULL
);
424 /*******************************************************************
425 * UnhandledExceptionFilter (KERNEL32.@)
427 DWORD WINAPI
UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers
)
432 if (check_resource_write( epointers
->ExceptionRecord
)) return EXCEPTION_CONTINUE_EXECUTION
;
434 for (loop
= 0; loop
<= 1; loop
++)
436 /* send a last chance event to the debugger */
437 status
= send_debug_event( epointers
->ExceptionRecord
, FALSE
, epointers
->ContextRecord
);
441 return EXCEPTION_CONTINUE_EXECUTION
;
442 case DBG_EXCEPTION_NOT_HANDLED
:
443 TerminateProcess( GetCurrentProcess(), epointers
->ExceptionRecord
->ExceptionCode
);
444 break; /* not reached */
445 case 0: /* no debugger is present */
446 if (epointers
->ExceptionRecord
->ExceptionCode
== CONTROL_C_EXIT
)
448 /* do not launch the debugger on ^C, simply terminate the process */
449 TerminateProcess( GetCurrentProcess(), 1 );
451 /* second try, the debugger isn't present... */
452 if (loop
== 1) return EXCEPTION_EXECUTE_HANDLER
;
455 FIXME("Unsupported yet debug continue value %d (please report)\n", status
);
456 return EXCEPTION_EXECUTE_HANDLER
;
459 /* should only be there when loop == 0 */
463 DWORD ret
= top_filter( epointers
);
464 if (ret
!= EXCEPTION_CONTINUE_SEARCH
) return ret
;
467 /* FIXME: Should check the current error mode */
469 if (!start_debugger_atomic( epointers
))
470 return EXCEPTION_EXECUTE_HANDLER
;
471 /* now that we should have a debugger attached, try to resend event */
474 return EXCEPTION_EXECUTE_HANDLER
;
478 /***********************************************************************
479 * SetUnhandledExceptionFilter (KERNEL32.@)
481 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI
SetUnhandledExceptionFilter(
482 LPTOP_LEVEL_EXCEPTION_FILTER filter
)
484 LPTOP_LEVEL_EXCEPTION_FILTER old
= top_filter
;
490 /**************************************************************************
491 * FatalAppExitA (KERNEL32.@)
493 void WINAPI
FatalAppExitA( UINT action
, LPCSTR str
)
495 HMODULE mod
= GetModuleHandleA( "user32.dll" );
496 MessageBoxA_funcptr pMessageBoxA
= NULL
;
500 if (mod
) pMessageBoxA
= (MessageBoxA_funcptr
)GetProcAddress( mod
, "MessageBoxA" );
501 if (pMessageBoxA
) pMessageBoxA( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
502 else ERR( "%s\n", debugstr_a(str
) );
507 /**************************************************************************
508 * FatalAppExitW (KERNEL32.@)
510 void WINAPI
FatalAppExitW( UINT action
, LPCWSTR str
)
512 HMODULE mod
= GetModuleHandleA( "user32.dll" );
513 MessageBoxW_funcptr pMessageBoxW
= NULL
;
517 if (mod
) pMessageBoxW
= (MessageBoxW_funcptr
)GetProcAddress( mod
, "MessageBoxW" );
518 if (pMessageBoxW
) pMessageBoxW( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
519 else ERR( "%s\n", debugstr_w(str
) );