Merge from lostwages faq.
[wine/multimedia.git] / win32 / except.c
blobd7cb912febb40c59b50bf9a5e8050678973257d5
1 /*
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
21 * Notes:
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
26 * reasons for this:
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
35 * documented!
38 #include "config.h"
39 #include "wine/port.h"
41 #include <stdio.h>
42 #include "windef.h"
43 #include "winerror.h"
44 #include "winternl.h"
45 #include "wingdi.h"
46 #include "winuser.h"
47 #include "wine/exception.h"
48 #include "wine/library.h"
49 #include "thread.h"
50 #include "excpt.h"
51 #include "wine/server.h"
52 #include "wine/unicode.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(seh);
57 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
59 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
60 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
62 /*******************************************************************
63 * RaiseException (KERNEL32.@)
65 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const LPDWORD args )
67 EXCEPTION_RECORD record;
69 /* Compose an exception record */
71 record.ExceptionCode = code;
72 record.ExceptionFlags = flags & EH_NONCONTINUABLE;
73 record.ExceptionRecord = NULL;
74 record.ExceptionAddress = RaiseException;
75 if (nbargs && args)
77 if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
78 record.NumberParameters = nbargs;
79 memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
81 else record.NumberParameters = 0;
83 RtlRaiseException( &record );
87 /*******************************************************************
88 * format_exception_msg
90 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
92 const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
93 int len,len2;
95 switch(rec->ExceptionCode)
97 case EXCEPTION_INT_DIVIDE_BY_ZERO:
98 len = snprintf( buffer, size, "Unhandled division by zero" );
99 break;
100 case EXCEPTION_INT_OVERFLOW:
101 len = snprintf( buffer, size, "Unhandled overflow" );
102 break;
103 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
104 len = snprintf( buffer, size, "Unhandled array bounds" );
105 break;
106 case EXCEPTION_ILLEGAL_INSTRUCTION:
107 len = snprintf( buffer, size, "Unhandled illegal instruction" );
108 break;
109 case EXCEPTION_STACK_OVERFLOW:
110 len = snprintf( buffer, size, "Unhandled stack overflow" );
111 break;
112 case EXCEPTION_PRIV_INSTRUCTION:
113 len = snprintf( buffer, size, "Unhandled privileged instruction" );
114 break;
115 case EXCEPTION_ACCESS_VIOLATION:
116 if (rec->NumberParameters == 2)
117 len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
118 rec->ExceptionInformation[0] ? "write" : "read",
119 rec->ExceptionInformation[1]);
120 else
121 len = snprintf( buffer, size, "Unhandled page fault");
122 break;
123 case EXCEPTION_DATATYPE_MISALIGNMENT:
124 len = snprintf( buffer, size, "Unhandled alignment" );
125 break;
126 case CONTROL_C_EXIT:
127 len = snprintf( buffer, size, "Unhandled ^C");
128 break;
129 case STATUS_POSSIBLE_DEADLOCK:
130 len = snprintf( buffer, size, "Critical section %08lx wait failed",
131 rec->ExceptionInformation[0]);
132 break;
133 case EXCEPTION_WINE_STUB:
134 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
135 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
136 break;
137 case EXCEPTION_WINE_ASSERTION:
138 len = snprintf( buffer, size, "Assertion failed" );
139 break;
140 case EXCEPTION_VM86_INTx:
141 len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
142 rec->ExceptionInformation[0]);
143 break;
144 case EXCEPTION_VM86_STI:
145 len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
146 break;
147 case EXCEPTION_VM86_PICRETURN:
148 len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
149 break;
150 default:
151 len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
152 break;
154 if ((len<0) || (len>=size))
155 return -1;
156 #ifdef __i386__
157 if (ptr->ContextRecord->SegCs != wine_get_cs())
158 len2 = snprintf(buffer+len, size-len,
159 " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
160 ptr->ContextRecord->SegCs,
161 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
162 else
163 #endif
164 len2 = snprintf(buffer+len, size-len,
165 " at address 0x%08lx.\nDo you wish to debug it ?",
166 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
167 if ((len2<0) || (len>=size-len))
168 return -1;
169 return len+len2;
173 /**********************************************************************
174 * send_debug_event
176 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
178 static int send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
180 int ret;
181 HANDLE handle = 0;
183 SERVER_START_REQ( queue_exception_event )
185 req->first = first_chance;
186 wine_server_add_data( req, context, sizeof(*context) );
187 wine_server_add_data( req, rec, sizeof(*rec) );
188 if (!wine_server_call(req)) handle = reply->handle;
190 SERVER_END_REQ;
191 if (!handle) return 0; /* no debugger present or other error */
193 /* No need to wait on the handle since the process gets suspended
194 * once the event is passed to the debugger, so when we get back
195 * here the event has been continued already.
197 SERVER_START_REQ( get_exception_status )
199 req->handle = handle;
200 wine_server_set_reply( req, context, sizeof(*context) );
201 wine_server_call( req );
202 ret = reply->status;
204 SERVER_END_REQ;
205 NtClose( handle );
206 return ret;
209 /******************************************************************
210 * start_debugger
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 HKEY hDbgConf;
219 DWORD bAuto = FALSE;
220 PROCESS_INFORMATION info;
221 STARTUPINFOA startup;
222 char* cmdline;
223 char* format = NULL;
224 BOOL ret = FALSE;
226 static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
227 'S','o','f','t','w','a','r','e','\\',
228 'M','i','c','r','o','s','o','f','t','\\',
229 'W','i','n','d','o','w','s',' ','N','T','\\',
230 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
231 'A','e','D','e','b','u','g',0};
232 static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
233 static const WCHAR AutoW[] = {'A','u','t','o',0};
235 MESSAGE("wine: Unhandled exception (thread %04lx), starting debugger...\n", GetCurrentThreadId());
237 attr.Length = sizeof(attr);
238 attr.RootDirectory = 0;
239 attr.ObjectName = &nameW;
240 attr.Attributes = 0;
241 attr.SecurityDescriptor = NULL;
242 attr.SecurityQualityOfService = NULL;
243 RtlInitUnicodeString( &nameW, AeDebugW );
245 if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
247 char buffer[64];
248 KEY_VALUE_PARTIAL_INFORMATION *info;
249 DWORD format_size = 0;
251 RtlInitUnicodeString( &nameW, DebuggerW );
252 if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
253 NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
255 char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
256 NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
257 data, format_size, &format_size );
258 info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
259 RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
260 format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
261 RtlUnicodeToMultiByteN( format, format_size, NULL,
262 (WCHAR *)info->Data, info->DataLength );
263 format[format_size] = 0;
265 if (info->Type == REG_EXPAND_SZ)
267 char* tmp;
269 /* Expand environment variable references */
270 format_size=ExpandEnvironmentStringsA(format,NULL,0);
271 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
272 ExpandEnvironmentStringsA(format,tmp,format_size);
273 HeapFree(GetProcessHeap(), 0, format);
274 format=tmp;
276 HeapFree( GetProcessHeap(), 0, data );
279 RtlInitUnicodeString( &nameW, AutoW );
280 if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
281 buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
283 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
284 if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
285 else if (info->Type == REG_SZ)
287 WCHAR *str = (WCHAR *)info->Data;
288 str[info->DataLength/sizeof(WCHAR)] = 0;
289 bAuto = atoiW( str );
292 else bAuto = TRUE;
294 NtClose(hDbgConf);
297 if (format)
299 cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
300 sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
301 HeapFree(GetProcessHeap(), 0, format);
303 else
305 cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
306 sprintf(cmdline, "winedbg --debugmsg -all --auto %ld %ld",
307 GetCurrentProcessId(), (ULONG_PTR)hEvent);
310 if (!bAuto)
312 HMODULE mod = GetModuleHandleA( "user32.dll" );
313 MessageBoxA_funcptr pMessageBoxA = NULL;
315 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
316 if (pMessageBoxA)
318 char buffer[256];
319 format_exception_msg( epointers, buffer, sizeof(buffer) );
320 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
322 TRACE("Killing process\n");
323 goto EXIT;
328 TRACE("Starting debugger %s\n", debugstr_a(cmdline));
329 memset(&startup, 0, sizeof(startup));
330 startup.cb = sizeof(startup);
331 startup.dwFlags = STARTF_USESHOWWINDOW;
332 startup.wShowWindow = SW_SHOWNORMAL;
333 ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &info);
335 if (ret) WaitForSingleObject(hEvent, INFINITE); /* wait for debugger to come up... */
336 else ERR("Couldn't start debugger (%s) (%ld)\n"
337 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
338 debugstr_a(cmdline), GetLastError());
339 EXIT:
340 HeapFree(GetProcessHeap(), 0, cmdline);
341 return ret;
344 /******************************************************************
345 * start_debugger_atomic
347 * starts the debugger in an atomic way:
348 * - either the debugger is not started and it is started
349 * - or the debugger has already been started by another thread
350 * - or the debugger couldn't be started
352 * returns TRUE for the two first conditions, FALSE for the last
354 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers)
356 static HANDLE hRunOnce /* = 0 */;
358 if (hRunOnce == 0)
360 OBJECT_ATTRIBUTES attr;
361 HANDLE hEvent;
363 attr.Length = sizeof(attr);
364 attr.RootDirectory = 0;
365 attr.Attributes = OBJ_INHERIT;
366 attr.ObjectName = NULL;
367 attr.SecurityDescriptor = NULL;
368 attr.SecurityQualityOfService = NULL;
370 /* ask for manual reset, so that once the debugger is started,
371 * every thread will know it */
372 NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
373 if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
375 /* ok, our event has been set... we're the winning thread */
376 BOOL ret = start_debugger( epointers, hRunOnce );
377 DWORD tmp;
379 if (!ret)
381 /* so that the other threads won't be stuck */
382 NtSetEvent( hRunOnce, &tmp );
384 return ret;
387 /* someone beat us here... */
388 CloseHandle( hEvent );
391 /* and wait for the winner to have actually created the debugger */
392 WaitForSingleObject( hRunOnce, INFINITE );
393 /* in fact, here, we only know that someone has tried to start the debugger,
394 * we'll know by reposting the exception if it has actually attached
395 * to the current process */
396 return TRUE;
400 /*******************************************************************
401 * check_resource_write
403 * Check if the exception is a write attempt to the resource data.
404 * If yes, we unprotect the resources to let broken apps continue
405 * (Windows does this too).
407 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
409 void *addr, *rsrc;
410 DWORD size;
411 MEMORY_BASIC_INFORMATION info;
413 if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return FALSE;
414 if (!rec->ExceptionInformation[0]) return FALSE; /* not a write access */
415 addr = (void *)rec->ExceptionInformation[1];
416 if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
417 if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
418 IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
419 return FALSE;
420 if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
421 FIXME( "Broken app is writing to the resource data, enabling work-around\n" );
422 VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
423 return TRUE;
427 /*******************************************************************
428 * UnhandledExceptionFilter (KERNEL32.@)
430 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
432 int status;
433 int loop = 0;
435 if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
437 for (loop = 0; loop <= 1; loop++)
439 /* send a last chance event to the debugger */
440 status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
441 switch (status)
443 case DBG_CONTINUE:
444 return EXCEPTION_CONTINUE_EXECUTION;
445 case DBG_EXCEPTION_NOT_HANDLED:
446 TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
447 break; /* not reached */
448 case 0: /* no debugger is present */
449 if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
451 /* do not launch the debugger on ^C, simply terminate the process */
452 TerminateProcess( GetCurrentProcess(), 1 );
454 /* second try, the debugger isn't present... */
455 if (loop == 1) return EXCEPTION_EXECUTE_HANDLER;
456 break;
457 default:
458 FIXME("Unsupported yet debug continue value %d (please report)\n", status);
459 return EXCEPTION_EXECUTE_HANDLER;
462 /* should only be there when loop == 0 */
464 if (top_filter)
466 DWORD ret = top_filter( epointers );
467 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
470 /* FIXME: Should check the current error mode */
472 if (!start_debugger_atomic( epointers ))
473 return EXCEPTION_EXECUTE_HANDLER;
474 /* now that we should have a debugger attached, try to resend event */
477 return EXCEPTION_EXECUTE_HANDLER;
481 /***********************************************************************
482 * SetUnhandledExceptionFilter (KERNEL32.@)
484 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
485 LPTOP_LEVEL_EXCEPTION_FILTER filter )
487 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
488 top_filter = filter;
489 return old;
493 /**************************************************************************
494 * FatalAppExitA (KERNEL32.@)
496 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
498 HMODULE mod = GetModuleHandleA( "user32.dll" );
499 MessageBoxA_funcptr pMessageBoxA = NULL;
501 WARN("AppExit\n");
503 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
504 if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
505 else ERR( "%s\n", debugstr_a(str) );
506 ExitProcess(0);
510 /**************************************************************************
511 * FatalAppExitW (KERNEL32.@)
513 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
515 static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
517 HMODULE mod = GetModuleHandleW( User32DllW );
518 MessageBoxW_funcptr pMessageBoxW = NULL;
520 WARN("AppExit\n");
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) );
525 ExitProcess(0);
529 /**************************************************************************
530 * FatalExit (KERNEL32.@)
532 void WINAPI FatalExit(int ExitCode)
534 WARN("FatalExit\n");
535 ExitProcess(ExitCode);