d3d9/tests: Add a test for cube texture mipmap autogeneration.
[wine.git] / dlls / kernel32 / except.c
blob2a9f0f14d33790584eb2e112cadedef10fd491a2
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 <stdarg.h>
42 #include <stdio.h>
43 #include "ntstatus.h"
44 #define WIN32_NO_STATUS
45 #include "windef.h"
46 #include "winbase.h"
47 #include "winternl.h"
48 #include "wingdi.h"
49 #include "winuser.h"
50 #include "wine/exception.h"
51 #include "wine/library.h"
52 #include "excpt.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;
76 if (nbargs && args)
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;
94 int len,len2;
96 switch(rec->ExceptionCode)
98 case EXCEPTION_INT_DIVIDE_BY_ZERO:
99 len = snprintf( buffer, size, "Unhandled division by zero" );
100 break;
101 case EXCEPTION_INT_OVERFLOW:
102 len = snprintf( buffer, size, "Unhandled overflow" );
103 break;
104 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
105 len = snprintf( buffer, size, "Unhandled array bounds" );
106 break;
107 case EXCEPTION_ILLEGAL_INSTRUCTION:
108 len = snprintf( buffer, size, "Unhandled illegal instruction" );
109 break;
110 case EXCEPTION_STACK_OVERFLOW:
111 len = snprintf( buffer, size, "Unhandled stack overflow" );
112 break;
113 case EXCEPTION_PRIV_INSTRUCTION:
114 len = snprintf( buffer, size, "Unhandled privileged instruction" );
115 break;
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]);
122 else
123 len = snprintf( buffer, size, "Unhandled page fault");
124 break;
125 case EXCEPTION_DATATYPE_MISALIGNMENT:
126 len = snprintf( buffer, size, "Unhandled alignment" );
127 break;
128 case CONTROL_C_EXIT:
129 len = snprintf( buffer, size, "Unhandled ^C");
130 break;
131 case STATUS_POSSIBLE_DEADLOCK:
132 len = snprintf( buffer, size, "Critical section %08lx wait failed",
133 rec->ExceptionInformation[0]);
134 break;
135 case EXCEPTION_WINE_STUB:
136 if ((ULONG_PTR)rec->ExceptionInformation[1] >> 16)
137 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
138 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
139 else
140 len = snprintf( buffer, size, "Unimplemented function %s.%ld called",
141 (char *)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
142 break;
143 case EXCEPTION_WINE_ASSERTION:
144 len = snprintf( buffer, size, "Assertion failed" );
145 break;
146 default:
147 len = snprintf( buffer, size, "Unhandled exception 0x%08x in thread %x", rec->ExceptionCode, GetCurrentThreadId());
148 break;
150 if ((len<0) || (len>=size))
151 return -1;
152 #ifdef __i386__
153 if (ptr->ContextRecord->SegCs != wine_get_cs())
154 len2 = snprintf(buffer+len, size-len, " at address 0x%04x:0x%08x",
155 ptr->ContextRecord->SegCs,
156 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
157 else
158 #endif
159 len2 = snprintf(buffer+len, size-len, " at address %p",
160 ptr->ExceptionRecord->ExceptionAddress);
161 if ((len2<0) || (len>=size-len))
162 return -1;
163 return len+len2;
167 /******************************************************************
168 * start_debugger
170 * Does the effective debugger startup according to 'format'
172 static BOOL start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
174 OBJECT_ATTRIBUTES attr;
175 UNICODE_STRING nameW;
176 char *cmdline, *env, *p;
177 HANDLE hDbgConf;
178 DWORD bAuto = TRUE;
179 PROCESS_INFORMATION info;
180 STARTUPINFOA startup;
181 char* format = NULL;
182 BOOL ret = FALSE;
183 char buffer[256];
185 static const WCHAR AeDebugW[] = {'\\','R','e','g','i','s','t','r','y','\\',
186 'M','a','c','h','i','n','e','\\',
187 'S','o','f','t','w','a','r','e','\\',
188 'M','i','c','r','o','s','o','f','t','\\',
189 'W','i','n','d','o','w','s',' ','N','T','\\',
190 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
191 'A','e','D','e','b','u','g',0};
192 static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
193 static const WCHAR AutoW[] = {'A','u','t','o',0};
195 format_exception_msg( epointers, buffer, sizeof(buffer) );
196 MESSAGE("wine: %s (thread %04x), starting debugger...\n", buffer, GetCurrentThreadId());
198 attr.Length = sizeof(attr);
199 attr.RootDirectory = 0;
200 attr.ObjectName = &nameW;
201 attr.Attributes = 0;
202 attr.SecurityDescriptor = NULL;
203 attr.SecurityQualityOfService = NULL;
204 RtlInitUnicodeString( &nameW, AeDebugW );
206 if (!NtOpenKey( &hDbgConf, KEY_READ, &attr ))
208 KEY_VALUE_PARTIAL_INFORMATION *info;
209 DWORD format_size = 0;
211 RtlInitUnicodeString( &nameW, DebuggerW );
212 if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
213 NULL, 0, &format_size ) == STATUS_BUFFER_TOO_SMALL)
215 char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
216 NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
217 data, format_size, &format_size );
218 info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
219 RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
220 format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
221 RtlUnicodeToMultiByteN( format, format_size, NULL,
222 (WCHAR *)info->Data, info->DataLength );
223 format[format_size] = 0;
225 if (info->Type == REG_EXPAND_SZ)
227 char* tmp;
229 /* Expand environment variable references */
230 format_size=ExpandEnvironmentStringsA(format,NULL,0);
231 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
232 ExpandEnvironmentStringsA(format,tmp,format_size);
233 HeapFree(GetProcessHeap(), 0, format);
234 format=tmp;
236 HeapFree( GetProcessHeap(), 0, data );
239 RtlInitUnicodeString( &nameW, AutoW );
240 if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
241 buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
243 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
244 if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
245 else if (info->Type == REG_SZ)
247 WCHAR *str = (WCHAR *)info->Data;
248 str[info->DataLength/sizeof(WCHAR)] = 0;
249 bAuto = atoiW( str );
253 NtClose(hDbgConf);
256 if (format)
258 size_t format_size = strlen(format) + 2*20;
259 cmdline = HeapAlloc(GetProcessHeap(), 0, format_size);
260 snprintf(cmdline, format_size, format, (long)GetCurrentProcessId(), (long)HandleToLong(hEvent));
261 HeapFree(GetProcessHeap(), 0, format);
263 else
265 cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
266 snprintf(cmdline, 80, "winedbg --auto %ld %ld", /* as in tools/wine.inf */
267 (long)GetCurrentProcessId(), (long)HandleToLong(hEvent));
270 if (!bAuto)
272 HMODULE mod = GetModuleHandleA( "user32.dll" );
273 MessageBoxA_funcptr pMessageBoxA = NULL;
275 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
276 if (pMessageBoxA)
278 static const char msg[] = ".\nDo you wish to debug it?";
280 format_exception_msg( epointers, buffer, sizeof(buffer)-sizeof(msg) );
281 strcat( buffer, msg );
282 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
284 TRACE("Killing process\n");
285 goto EXIT;
290 /* make WINEDEBUG empty in the environment */
291 env = GetEnvironmentStringsA();
292 for (p = env; *p; p += strlen(p) + 1)
294 if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
296 char *next = p + strlen(p);
297 char *end = next + 1;
298 while (*end) end += strlen(end) + 1;
299 memmove( p + sizeof("WINEDEBUG=") - 1, next, end + 1 - next );
300 break;
304 TRACE("Starting debugger %s\n", debugstr_a(cmdline));
305 memset(&startup, 0, sizeof(startup));
306 startup.cb = sizeof(startup);
307 startup.dwFlags = STARTF_USESHOWWINDOW;
308 startup.wShowWindow = SW_SHOWNORMAL;
309 ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
310 FreeEnvironmentStringsA( env );
312 if (ret)
314 /* wait for debugger to come up... */
315 HANDLE handles[2];
316 CloseHandle(info.hThread);
317 handles[0]=hEvent;
318 handles[1]=info.hProcess;
319 WaitForMultipleObjects(2, handles, FALSE, INFINITE);
320 CloseHandle(info.hProcess);
322 else ERR("Couldn't start debugger (%s) (%d)\n"
323 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
324 debugstr_a(cmdline), GetLastError());
325 EXIT:
326 HeapFree(GetProcessHeap(), 0, cmdline);
327 return ret;
330 /******************************************************************
331 * start_debugger_atomic
333 * starts the debugger in an atomic way:
334 * - either the debugger is not started and it is started
335 * - or the debugger has already been started by another thread
336 * - or the debugger couldn't be started
338 * returns TRUE for the two first conditions, FALSE for the last
340 static BOOL start_debugger_atomic(PEXCEPTION_POINTERS epointers)
342 static HANDLE hRunOnce /* = 0 */;
344 if (hRunOnce == 0)
346 OBJECT_ATTRIBUTES attr;
347 HANDLE hEvent;
349 attr.Length = sizeof(attr);
350 attr.RootDirectory = 0;
351 attr.Attributes = OBJ_INHERIT;
352 attr.ObjectName = NULL;
353 attr.SecurityDescriptor = NULL;
354 attr.SecurityQualityOfService = NULL;
356 /* ask for manual reset, so that once the debugger is started,
357 * every thread will know it */
358 NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE );
359 if (InterlockedCompareExchangePointer( &hRunOnce, hEvent, 0 ) == 0)
361 /* ok, our event has been set... we're the winning thread */
362 BOOL ret = start_debugger( epointers, hRunOnce );
363 DWORD tmp;
365 if (!ret)
367 /* so that the other threads won't be stuck */
368 NtSetEvent( hRunOnce, &tmp );
370 return ret;
373 /* someone beat us here... */
374 CloseHandle( hEvent );
377 /* and wait for the winner to have actually created the debugger */
378 WaitForSingleObject( hRunOnce, INFINITE );
379 /* in fact, here, we only know that someone has tried to start the debugger,
380 * we'll know by reposting the exception if it has actually attached
381 * to the current process */
382 return TRUE;
386 /*******************************************************************
387 * check_resource_write
389 * Check if the exception is a write attempt to the resource data.
390 * If yes, we unprotect the resources to let broken apps continue
391 * (Windows does this too).
393 static inline BOOL check_resource_write( void *addr )
395 DWORD old_prot;
396 void *rsrc;
397 DWORD size;
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( info.AllocationBase, TRUE,
403 IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
404 return FALSE;
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_READWRITE, &old_prot );
408 return TRUE;
412 /*******************************************************************
413 * UnhandledExceptionFilter (KERNEL32.@)
415 LONG WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
417 const EXCEPTION_RECORD *rec = epointers->ExceptionRecord;
419 if (rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && rec->NumberParameters >= 2)
421 switch(rec->ExceptionInformation[0])
423 case EXCEPTION_WRITE_FAULT:
424 if (check_resource_write( (void *)rec->ExceptionInformation[1] ))
425 return EXCEPTION_CONTINUE_EXECUTION;
426 break;
430 if (!NtCurrentTeb()->Peb->BeingDebugged)
432 if (rec->ExceptionCode == CONTROL_C_EXIT)
434 /* do not launch the debugger on ^C, simply terminate the process */
435 TerminateProcess( GetCurrentProcess(), 1 );
438 if (top_filter)
440 LONG ret = top_filter( epointers );
441 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
444 /* FIXME: Should check the current error mode */
446 if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
447 return EXCEPTION_EXECUTE_HANDLER;
449 return EXCEPTION_CONTINUE_SEARCH;
453 /***********************************************************************
454 * SetUnhandledExceptionFilter (KERNEL32.@)
456 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI DECLSPEC_HOTPATCH SetUnhandledExceptionFilter(
457 LPTOP_LEVEL_EXCEPTION_FILTER filter )
459 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
460 top_filter = filter;
461 return old;
465 /**************************************************************************
466 * FatalAppExitA (KERNEL32.@)
468 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
470 HMODULE mod = GetModuleHandleA( "user32.dll" );
471 MessageBoxA_funcptr pMessageBoxA = NULL;
473 WARN("AppExit\n");
475 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
476 if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
477 else ERR( "%s\n", debugstr_a(str) );
478 ExitProcess(0);
482 /**************************************************************************
483 * FatalAppExitW (KERNEL32.@)
485 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
487 static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
489 HMODULE mod = GetModuleHandleW( User32DllW );
490 MessageBoxW_funcptr pMessageBoxW = NULL;
492 WARN("AppExit\n");
494 if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
495 if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
496 else ERR( "%s\n", debugstr_w(str) );
497 ExitProcess(0);
501 /**************************************************************************
502 * FatalExit (KERNEL32.@)
504 void WINAPI FatalExit(int ExitCode)
506 WARN("FatalExit\n");
507 ExitProcess(ExitCode);