kernel32: Move MODULE_get_binary_info implementation to process.c.
[wine.git] / dlls / kernel32 / except.c
blobc4f7fafabb627c28dd560f338f8db92be437e7d1
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);
57 WINE_DECLARE_DEBUG_CHANNEL(winedbg);
59 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
61 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
62 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
64 /*******************************************************************
65 * RaiseException (KERNEL32.@)
67 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const ULONG_PTR *args )
69 EXCEPTION_RECORD record;
71 /* Compose an exception record */
73 record.ExceptionCode = code;
74 record.ExceptionFlags = flags & EH_NONCONTINUABLE;
75 record.ExceptionRecord = NULL;
76 record.ExceptionAddress = RaiseException;
77 if (nbargs && args)
79 if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
80 record.NumberParameters = nbargs;
81 memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
83 else record.NumberParameters = 0;
85 RtlRaiseException( &record );
89 /*******************************************************************
90 * format_exception_msg
92 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
94 const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
95 int len,len2;
97 switch(rec->ExceptionCode)
99 case EXCEPTION_INT_DIVIDE_BY_ZERO:
100 len = snprintf( buffer, size, "Unhandled division by zero" );
101 break;
102 case EXCEPTION_INT_OVERFLOW:
103 len = snprintf( buffer, size, "Unhandled overflow" );
104 break;
105 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
106 len = snprintf( buffer, size, "Unhandled array bounds" );
107 break;
108 case EXCEPTION_ILLEGAL_INSTRUCTION:
109 len = snprintf( buffer, size, "Unhandled illegal instruction" );
110 break;
111 case EXCEPTION_STACK_OVERFLOW:
112 len = snprintf( buffer, size, "Unhandled stack overflow" );
113 break;
114 case EXCEPTION_PRIV_INSTRUCTION:
115 len = snprintf( buffer, size, "Unhandled privileged instruction" );
116 break;
117 case EXCEPTION_ACCESS_VIOLATION:
118 if (rec->NumberParameters == 2)
119 len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
120 rec->ExceptionInformation[0] == EXCEPTION_WRITE_FAULT ? "write" :
121 rec->ExceptionInformation[0] == EXCEPTION_EXECUTE_FAULT ? "execute" : "read",
122 rec->ExceptionInformation[1]);
123 else
124 len = snprintf( buffer, size, "Unhandled page fault");
125 break;
126 case EXCEPTION_DATATYPE_MISALIGNMENT:
127 len = snprintf( buffer, size, "Unhandled alignment" );
128 break;
129 case CONTROL_C_EXIT:
130 len = snprintf( buffer, size, "Unhandled ^C");
131 break;
132 case STATUS_POSSIBLE_DEADLOCK:
133 len = snprintf( buffer, size, "Critical section %08lx wait failed",
134 rec->ExceptionInformation[0]);
135 break;
136 case EXCEPTION_WINE_STUB:
137 if ((ULONG_PTR)rec->ExceptionInformation[1] >> 16)
138 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
139 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
140 else
141 len = snprintf( buffer, size, "Unimplemented function %s.%ld called",
142 (char *)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
143 break;
144 case EXCEPTION_WINE_ASSERTION:
145 len = snprintf( buffer, size, "Assertion failed" );
146 break;
147 default:
148 len = snprintf( buffer, size, "Unhandled exception 0x%08x in thread %x", rec->ExceptionCode, GetCurrentThreadId());
149 break;
151 if ((len<0) || (len>=size))
152 return -1;
153 #ifdef __i386__
154 if (LOWORD(ptr->ContextRecord->SegCs) != wine_get_cs())
155 len2 = snprintf(buffer+len, size-len, " at address 0x%04x:0x%08x",
156 LOWORD(ptr->ContextRecord->SegCs),
157 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
158 else
159 #endif
160 len2 = snprintf(buffer+len, size-len, " at address %p",
161 ptr->ExceptionRecord->ExceptionAddress);
162 if ((len2<0) || (len>=size-len))
163 return -1;
164 return len+len2;
168 /******************************************************************
169 * start_debugger
171 * Does the effective debugger startup according to 'format'
173 static BOOL start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
175 OBJECT_ATTRIBUTES attr;
176 UNICODE_STRING nameW;
177 char *cmdline, *env, *p;
178 HANDLE hDbgConf;
179 DWORD bAuto = TRUE;
180 PROCESS_INFORMATION info;
181 STARTUPINFOA startup;
182 char* format = NULL;
183 BOOL ret = FALSE;
184 char buffer[256];
186 static const WCHAR AeDebugW[] = {'\\','R','e','g','i','s','t','r','y','\\',
187 'M','a','c','h','i','n','e','\\',
188 'S','o','f','t','w','a','r','e','\\',
189 'M','i','c','r','o','s','o','f','t','\\',
190 'W','i','n','d','o','w','s',' ','N','T','\\',
191 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
192 'A','e','D','e','b','u','g',0};
193 static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
194 static const WCHAR AutoW[] = {'A','u','t','o',0};
196 format_exception_msg( epointers, buffer, sizeof(buffer) );
197 MESSAGE("wine: %s (thread %04x), starting debugger...\n", buffer, GetCurrentThreadId());
199 attr.Length = sizeof(attr);
200 attr.RootDirectory = 0;
201 attr.ObjectName = &nameW;
202 attr.Attributes = 0;
203 attr.SecurityDescriptor = NULL;
204 attr.SecurityQualityOfService = NULL;
205 RtlInitUnicodeString( &nameW, AeDebugW );
207 if (!NtOpenKey( &hDbgConf, KEY_READ, &attr ))
209 KEY_VALUE_PARTIAL_INFORMATION *info;
210 DWORD format_size = 0;
212 RtlInitUnicodeString( &nameW, DebuggerW );
213 if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
214 NULL, 0, &format_size ) == STATUS_BUFFER_TOO_SMALL)
216 char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
217 NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
218 data, format_size, &format_size );
219 info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
220 RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
221 format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
222 RtlUnicodeToMultiByteN( format, format_size, NULL,
223 (WCHAR *)info->Data, info->DataLength );
224 format[format_size] = 0;
226 if (info->Type == REG_EXPAND_SZ)
228 char* tmp;
230 /* Expand environment variable references */
231 format_size=ExpandEnvironmentStringsA(format,NULL,0);
232 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
233 ExpandEnvironmentStringsA(format,tmp,format_size);
234 HeapFree(GetProcessHeap(), 0, format);
235 format=tmp;
237 HeapFree( GetProcessHeap(), 0, data );
240 RtlInitUnicodeString( &nameW, AutoW );
241 if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
242 buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
244 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
245 if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
246 else if (info->Type == REG_SZ)
248 WCHAR *str = (WCHAR *)info->Data;
249 str[info->DataLength/sizeof(WCHAR)] = 0;
250 bAuto = atoiW( str );
254 NtClose(hDbgConf);
257 if (format)
259 size_t format_size = strlen(format) + 2*20;
260 cmdline = HeapAlloc(GetProcessHeap(), 0, format_size);
261 snprintf(cmdline, format_size, format, (long)GetCurrentProcessId(), (long)HandleToLong(hEvent));
262 HeapFree(GetProcessHeap(), 0, format);
264 else
266 cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
267 snprintf(cmdline, 80, "winedbg --auto %ld %ld", /* as in tools/wine.inf */
268 (long)GetCurrentProcessId(), (long)HandleToLong(hEvent));
271 if (!bAuto)
273 HMODULE mod = GetModuleHandleA( "user32.dll" );
274 MessageBoxA_funcptr pMessageBoxA = NULL;
276 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
277 if (pMessageBoxA)
279 static const char msg[] = ".\nDo you wish to debug it?";
281 format_exception_msg( epointers, buffer, sizeof(buffer)-sizeof(msg) );
282 strcat( buffer, msg );
283 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
285 TRACE("Killing process\n");
286 goto EXIT;
291 /* make WINEDEBUG empty in the environment */
292 env = GetEnvironmentStringsA();
293 if (!TRACE_ON(winedbg))
295 for (p = env; *p; p += strlen(p) + 1)
297 if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
299 char *next = p + strlen(p);
300 char *end = next + 1;
301 while (*end) end += strlen(end) + 1;
302 memmove( p + sizeof("WINEDEBUG=") - 1, next, end + 1 - next );
303 break;
308 TRACE("Starting debugger %s\n", debugstr_a(cmdline));
309 memset(&startup, 0, sizeof(startup));
310 startup.cb = sizeof(startup);
311 startup.dwFlags = STARTF_USESHOWWINDOW;
312 startup.wShowWindow = SW_SHOWNORMAL;
313 ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
314 FreeEnvironmentStringsA( env );
316 if (ret)
318 /* wait for debugger to come up... */
319 HANDLE handles[2];
320 CloseHandle(info.hThread);
321 handles[0]=hEvent;
322 handles[1]=info.hProcess;
323 WaitForMultipleObjects(2, handles, FALSE, INFINITE);
324 CloseHandle(info.hProcess);
326 else ERR("Couldn't start debugger (%s) (%d)\n"
327 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
328 debugstr_a(cmdline), GetLastError());
329 EXIT:
330 HeapFree(GetProcessHeap(), 0, cmdline);
331 return ret;
334 /******************************************************************
335 * start_debugger_atomic
337 * starts the debugger in an atomic way:
338 * - either the debugger is not started and it is started
339 * - or the debugger has already been started by another thread
340 * - or the debugger couldn't be started
342 * returns TRUE for the two first conditions, FALSE for the last
344 static BOOL start_debugger_atomic(PEXCEPTION_POINTERS epointers)
346 static HANDLE hRunOnce /* = 0 */;
348 if (hRunOnce == 0)
350 OBJECT_ATTRIBUTES attr;
351 HANDLE hEvent;
353 attr.Length = sizeof(attr);
354 attr.RootDirectory = 0;
355 attr.Attributes = OBJ_INHERIT;
356 attr.ObjectName = NULL;
357 attr.SecurityDescriptor = NULL;
358 attr.SecurityQualityOfService = NULL;
360 /* ask for manual reset, so that once the debugger is started,
361 * every thread will know it */
362 NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, NotificationEvent, FALSE );
363 if (InterlockedCompareExchangePointer( &hRunOnce, hEvent, 0 ) == 0)
365 /* ok, our event has been set... we're the winning thread */
366 BOOL ret = start_debugger( epointers, hRunOnce );
367 DWORD tmp;
369 if (!ret)
371 /* so that the other threads won't be stuck */
372 NtSetEvent( hRunOnce, &tmp );
374 return ret;
377 /* someone beat us here... */
378 CloseHandle( hEvent );
381 /* and wait for the winner to have actually created the debugger */
382 WaitForSingleObject( hRunOnce, INFINITE );
383 /* in fact, here, we only know that someone has tried to start the debugger,
384 * we'll know by reposting the exception if it has actually attached
385 * to the current process */
386 return TRUE;
390 /*******************************************************************
391 * check_resource_write
393 * Check if the exception is a write attempt to the resource data.
394 * If yes, we unprotect the resources to let broken apps continue
395 * (Windows does this too).
397 static inline BOOL check_resource_write( void *addr )
399 DWORD old_prot;
400 void *rsrc;
401 DWORD size;
402 MEMORY_BASIC_INFORMATION info;
404 if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
405 if (info.State == MEM_FREE || !(info.Type & MEM_IMAGE)) return FALSE;
406 if (!(rsrc = RtlImageDirectoryEntryToData( info.AllocationBase, TRUE,
407 IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
408 return FALSE;
409 if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
410 TRACE( "Broken app is writing to the resource data, enabling work-around\n" );
411 VirtualProtect( rsrc, size, PAGE_READWRITE, &old_prot );
412 return TRUE;
416 /*******************************************************************
417 * UnhandledExceptionFilter (KERNEL32.@)
419 LONG WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
421 const EXCEPTION_RECORD *rec = epointers->ExceptionRecord;
423 if (rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && rec->NumberParameters >= 2)
425 switch(rec->ExceptionInformation[0])
427 case EXCEPTION_WRITE_FAULT:
428 if (check_resource_write( (void *)rec->ExceptionInformation[1] ))
429 return EXCEPTION_CONTINUE_EXECUTION;
430 break;
434 if (!NtCurrentTeb()->Peb->BeingDebugged)
436 if (rec->ExceptionCode == CONTROL_C_EXIT)
438 /* do not launch the debugger on ^C, simply terminate the process */
439 TerminateProcess( GetCurrentProcess(), 1 );
442 if (top_filter)
444 LONG ret = top_filter( epointers );
445 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
448 /* FIXME: Should check the current error mode */
450 if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
451 return EXCEPTION_EXECUTE_HANDLER;
453 return EXCEPTION_CONTINUE_SEARCH;
457 /***********************************************************************
458 * SetUnhandledExceptionFilter (KERNEL32.@)
460 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI DECLSPEC_HOTPATCH SetUnhandledExceptionFilter(
461 LPTOP_LEVEL_EXCEPTION_FILTER filter )
463 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
464 top_filter = filter;
465 return old;
469 /**************************************************************************
470 * FatalAppExitA (KERNEL32.@)
472 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
474 HMODULE mod = GetModuleHandleA( "user32.dll" );
475 MessageBoxA_funcptr pMessageBoxA = NULL;
477 WARN("AppExit\n");
479 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
480 if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
481 else ERR( "%s\n", debugstr_a(str) );
482 ExitProcess(0);
486 /**************************************************************************
487 * FatalAppExitW (KERNEL32.@)
489 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
491 static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
493 HMODULE mod = GetModuleHandleW( User32DllW );
494 MessageBoxW_funcptr pMessageBoxW = NULL;
496 WARN("AppExit\n");
498 if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
499 if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
500 else ERR( "%s\n", debugstr_w(str) );
501 ExitProcess(0);
505 /**************************************************************************
506 * FatalExit (KERNEL32.@)
508 void WINAPI FatalExit(int ExitCode)
510 WARN("FatalExit\n");
511 ExitProcess(ExitCode);