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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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"
44 #define WIN32_NO_STATUS
50 #include "wine/exception.h"
51 #include "wine/library.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 ULONG_PTR
*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] == EXCEPTION_WRITE_FAULT
? "write" :
120 rec
->ExceptionInformation
[0] == EXCEPTION_EXECUTE_FAULT
? "execute" : "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%08x", 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%04x:0x%08x",
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 * Does the effective debugger startup according to 'format'
182 static BOOL
start_debugger(PEXCEPTION_POINTERS epointers
, HANDLE hEvent
)
184 OBJECT_ATTRIBUTES attr
;
185 UNICODE_STRING nameW
;
186 char *cmdline
, *env
, *p
;
189 PROCESS_INFORMATION info
;
190 STARTUPINFOA startup
;
195 static const WCHAR AeDebugW
[] = {'M','a','c','h','i','n','e','\\',
196 'S','o','f','t','w','a','r','e','\\',
197 'M','i','c','r','o','s','o','f','t','\\',
198 'W','i','n','d','o','w','s',' ','N','T','\\',
199 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
200 'A','e','D','e','b','u','g',0};
201 static const WCHAR DebuggerW
[] = {'D','e','b','u','g','g','e','r',0};
202 static const WCHAR AutoW
[] = {'A','u','t','o',0};
204 format_exception_msg( epointers
, buffer
, sizeof(buffer
) );
205 MESSAGE("wine: %s (thread %04x), starting debugger...\n", buffer
, GetCurrentThreadId());
207 attr
.Length
= sizeof(attr
);
208 attr
.RootDirectory
= 0;
209 attr
.ObjectName
= &nameW
;
211 attr
.SecurityDescriptor
= NULL
;
212 attr
.SecurityQualityOfService
= NULL
;
213 RtlInitUnicodeString( &nameW
, AeDebugW
);
215 if (!NtOpenKey( &hDbgConf
, KEY_ALL_ACCESS
, &attr
))
218 KEY_VALUE_PARTIAL_INFORMATION
*info
;
219 DWORD format_size
= 0;
221 RtlInitUnicodeString( &nameW
, DebuggerW
);
222 if (NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
223 NULL
, 0, &format_size
) == STATUS_BUFFER_OVERFLOW
)
225 char *data
= HeapAlloc(GetProcessHeap(), 0, format_size
);
226 NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
227 data
, format_size
, &format_size
);
228 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)data
;
229 RtlUnicodeToMultiByteSize( &format_size
, (WCHAR
*)info
->Data
, info
->DataLength
);
230 format
= HeapAlloc( GetProcessHeap(), 0, format_size
+1 );
231 RtlUnicodeToMultiByteN( format
, format_size
, NULL
,
232 (WCHAR
*)info
->Data
, info
->DataLength
);
233 format
[format_size
] = 0;
235 if (info
->Type
== REG_EXPAND_SZ
)
239 /* Expand environment variable references */
240 format_size
=ExpandEnvironmentStringsA(format
,NULL
,0);
241 tmp
=HeapAlloc(GetProcessHeap(), 0, format_size
);
242 ExpandEnvironmentStringsA(format
,tmp
,format_size
);
243 HeapFree(GetProcessHeap(), 0, format
);
246 HeapFree( GetProcessHeap(), 0, data
);
249 RtlInitUnicodeString( &nameW
, AutoW
);
250 if (!NtQueryValueKey( hDbgConf
, &nameW
, KeyValuePartialInformation
,
251 buffer
, sizeof(buffer
)-sizeof(WCHAR
), &format_size
))
253 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
254 if (info
->Type
== REG_DWORD
) memcpy( &bAuto
, info
->Data
, sizeof(DWORD
) );
255 else if (info
->Type
== REG_SZ
)
257 WCHAR
*str
= (WCHAR
*)info
->Data
;
258 str
[info
->DataLength
/sizeof(WCHAR
)] = 0;
259 bAuto
= atoiW( str
);
268 cmdline
= HeapAlloc(GetProcessHeap(), 0, strlen(format
) + 2*20);
269 sprintf(cmdline
, format
, GetCurrentProcessId(), hEvent
);
270 HeapFree(GetProcessHeap(), 0, format
);
274 cmdline
= HeapAlloc(GetProcessHeap(), 0, 80);
275 sprintf(cmdline
, "winedbg --auto %d %ld",
276 GetCurrentProcessId(), (ULONG_PTR
)hEvent
);
281 HMODULE mod
= GetModuleHandleA( "user32.dll" );
282 MessageBoxA_funcptr pMessageBoxA
= NULL
;
284 if (mod
) pMessageBoxA
= (MessageBoxA_funcptr
)GetProcAddress( mod
, "MessageBoxA" );
287 static const char msg
[] = ".\nDo you wish to debug it?";
290 format_exception_msg( epointers
, buffer
, sizeof(buffer
)-sizeof(msg
) );
291 strcat( buffer
, msg
);
292 if (pMessageBoxA( 0, buffer
, "Exception raised", MB_YESNO
| MB_ICONHAND
) == IDNO
)
294 TRACE("Killing process\n");
300 /* make WINEDEBUG empty in the environment */
301 env
= GetEnvironmentStringsA();
302 for (p
= env
; *p
; p
+= strlen(p
) + 1)
304 if (!memcmp( p
, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
306 char *next
= p
+ strlen(p
);
307 char *end
= next
+ 1;
308 while (*end
) end
+= strlen(end
) + 1;
309 memmove( p
+ sizeof("WINEDEBUG=") - 1, next
, end
+ 1 - next
);
314 TRACE("Starting debugger %s\n", debugstr_a(cmdline
));
315 memset(&startup
, 0, sizeof(startup
));
316 startup
.cb
= sizeof(startup
);
317 startup
.dwFlags
= STARTF_USESHOWWINDOW
;
318 startup
.wShowWindow
= SW_SHOWNORMAL
;
319 ret
= CreateProcessA(NULL
, cmdline
, NULL
, NULL
, TRUE
, 0, env
, NULL
, &startup
, &info
);
320 FreeEnvironmentStringsA( env
);
322 if (ret
) WaitForSingleObject(hEvent
, INFINITE
); /* wait for debugger to come up... */
323 else ERR("Couldn't start debugger (%s) (%d)\n"
324 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
325 debugstr_a(cmdline
), GetLastError());
327 HeapFree(GetProcessHeap(), 0, cmdline
);
331 /******************************************************************
332 * start_debugger_atomic
334 * starts the debugger in an atomic way:
335 * - either the debugger is not started and it is started
336 * - or the debugger has already been started by another thread
337 * - or the debugger couldn't be started
339 * returns TRUE for the two first conditions, FALSE for the last
341 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers
)
343 static HANDLE hRunOnce
/* = 0 */;
347 OBJECT_ATTRIBUTES attr
;
350 attr
.Length
= sizeof(attr
);
351 attr
.RootDirectory
= 0;
352 attr
.Attributes
= OBJ_INHERIT
;
353 attr
.ObjectName
= NULL
;
354 attr
.SecurityDescriptor
= NULL
;
355 attr
.SecurityQualityOfService
= NULL
;
357 /* ask for manual reset, so that once the debugger is started,
358 * every thread will know it */
359 NtCreateEvent( &hEvent
, EVENT_ALL_ACCESS
, &attr
, TRUE
, FALSE
);
360 if (InterlockedCompareExchangePointer( (PVOID
)&hRunOnce
, hEvent
, 0 ) == 0)
362 /* ok, our event has been set... we're the winning thread */
363 BOOL ret
= start_debugger( epointers
, hRunOnce
);
368 /* so that the other threads won't be stuck */
369 NtSetEvent( hRunOnce
, &tmp
);
374 /* someone beat us here... */
375 CloseHandle( hEvent
);
378 /* and wait for the winner to have actually created the debugger */
379 WaitForSingleObject( hRunOnce
, INFINITE
);
380 /* in fact, here, we only know that someone has tried to start the debugger,
381 * we'll know by reposting the exception if it has actually attached
382 * to the current process */
387 /*******************************************************************
388 * check_resource_write
390 * Check if the exception is a write attempt to the resource data.
391 * If yes, we unprotect the resources to let broken apps continue
392 * (Windows does this too).
394 static inline BOOL
check_resource_write( void *addr
)
398 MEMORY_BASIC_INFORMATION info
;
400 if (!VirtualQuery( addr
, &info
, sizeof(info
) )) return FALSE
;
401 if (info
.State
== MEM_FREE
|| !(info
.Type
& MEM_IMAGE
)) return FALSE
;
402 if (!(rsrc
= RtlImageDirectoryEntryToData( (HMODULE
)info
.AllocationBase
, TRUE
,
403 IMAGE_DIRECTORY_ENTRY_RESOURCE
, &size
)))
405 if (addr
< rsrc
|| (char *)addr
>= (char *)rsrc
+ size
) return FALSE
;
406 TRACE( "Broken app is writing to the resource data, enabling work-around\n" );
407 VirtualProtect( rsrc
, size
, PAGE_WRITECOPY
, NULL
);
412 /*******************************************************************
415 * Check for executing a protected area.
417 static inline BOOL
check_no_exec( void *addr
)
419 MEMORY_BASIC_INFORMATION info
;
421 if (!VirtualQuery( addr
, &info
, sizeof(info
) )) return FALSE
;
422 if (info
.State
== MEM_FREE
) return FALSE
;
424 /* prot |= PAGE_EXECUTE would be a lot easier, but MS developers
425 * apparently don't grasp the notion of protection bits */
428 case PAGE_READONLY
: info
.Protect
= PAGE_EXECUTE_READ
; break;
429 case PAGE_READWRITE
: info
.Protect
= PAGE_EXECUTE_READWRITE
; break;
430 case PAGE_WRITECOPY
: info
.Protect
= PAGE_EXECUTE_WRITECOPY
; break;
431 default: return FALSE
;
433 /* FIXME: we should probably have a per-app option, and maybe a message box */
434 FIXME( "No-exec fault triggered at %p, enabling work-around\n", addr
);
435 return VirtualProtect( addr
, 1, info
.Protect
, NULL
);
439 /*******************************************************************
440 * UnhandledExceptionFilter (KERNEL32.@)
442 LONG WINAPI
UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers
)
444 const EXCEPTION_RECORD
*rec
= epointers
->ExceptionRecord
;
446 if (rec
->ExceptionCode
== EXCEPTION_ACCESS_VIOLATION
&& rec
->NumberParameters
>= 2)
448 switch(rec
->ExceptionInformation
[0])
450 case EXCEPTION_WRITE_FAULT
:
451 if (check_resource_write( (void *)rec
->ExceptionInformation
[1] ))
452 return EXCEPTION_CONTINUE_EXECUTION
;
454 case EXCEPTION_EXECUTE_FAULT
:
455 if (check_no_exec( (void *)rec
->ExceptionInformation
[1] ))
456 return EXCEPTION_CONTINUE_EXECUTION
;
461 if (!NtCurrentTeb()->Peb
->BeingDebugged
)
463 if (rec
->ExceptionCode
== CONTROL_C_EXIT
)
465 /* do not launch the debugger on ^C, simply terminate the process */
466 TerminateProcess( GetCurrentProcess(), 1 );
471 LONG ret
= top_filter( epointers
);
472 if (ret
!= EXCEPTION_CONTINUE_SEARCH
) return ret
;
475 /* FIXME: Should check the current error mode */
477 if (!start_debugger_atomic( epointers
) || !NtCurrentTeb()->Peb
->BeingDebugged
)
478 return EXCEPTION_EXECUTE_HANDLER
;
480 return EXCEPTION_CONTINUE_SEARCH
;
484 /***********************************************************************
485 * SetUnhandledExceptionFilter (KERNEL32.@)
487 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI
SetUnhandledExceptionFilter(
488 LPTOP_LEVEL_EXCEPTION_FILTER filter
)
490 LPTOP_LEVEL_EXCEPTION_FILTER old
= top_filter
;
496 /**************************************************************************
497 * FatalAppExitA (KERNEL32.@)
499 void WINAPI
FatalAppExitA( UINT action
, LPCSTR str
)
501 HMODULE mod
= GetModuleHandleA( "user32.dll" );
502 MessageBoxA_funcptr pMessageBoxA
= NULL
;
506 if (mod
) pMessageBoxA
= (MessageBoxA_funcptr
)GetProcAddress( mod
, "MessageBoxA" );
507 if (pMessageBoxA
) pMessageBoxA( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
508 else ERR( "%s\n", debugstr_a(str
) );
513 /**************************************************************************
514 * FatalAppExitW (KERNEL32.@)
516 void WINAPI
FatalAppExitW( UINT action
, LPCWSTR str
)
518 static const WCHAR User32DllW
[] = {'u','s','e','r','3','2','.','d','l','l',0};
520 HMODULE mod
= GetModuleHandleW( User32DllW
);
521 MessageBoxW_funcptr pMessageBoxW
= NULL
;
525 if (mod
) pMessageBoxW
= (MessageBoxW_funcptr
)GetProcAddress( mod
, "MessageBoxW" );
526 if (pMessageBoxW
) pMessageBoxW( 0, str
, NULL
, MB_SYSTEMMODAL
| MB_OK
);
527 else ERR( "%s\n", debugstr_w(str
) );
532 /**************************************************************************
533 * FatalExit (KERNEL32.@)
535 void WINAPI
FatalExit(int ExitCode
)
538 ExitProcess(ExitCode
);