- use Interlocked* functions in AddRef and Release.
[wine/wine64.git] / dlls / kernel / except.c
blobf2e9ff9143672141ea4b0f342d6edecfcfa8ce96
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 <stdarg.h>
42 #include <stdio.h>
43 #include "ntstatus.h"
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winerror.h"
47 #include "winreg.h"
48 #include "winternl.h"
49 #include "wingdi.h"
50 #include "winuser.h"
51 #include "wine/exception.h"
52 #include "wine/library.h"
53 #include "thread.h"
54 #include "excpt.h"
55 #include "wine/server.h"
56 #include "wine/unicode.h"
57 #include "wine/debug.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(seh);
61 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
63 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
64 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
66 /*******************************************************************
67 * RaiseException (KERNEL32.@)
69 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const LPDWORD args )
71 EXCEPTION_RECORD record;
73 /* Compose an exception record */
75 record.ExceptionCode = code;
76 record.ExceptionFlags = flags & EH_NONCONTINUABLE;
77 record.ExceptionRecord = NULL;
78 record.ExceptionAddress = RaiseException;
79 if (nbargs && args)
81 if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
82 record.NumberParameters = nbargs;
83 memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
85 else record.NumberParameters = 0;
87 RtlRaiseException( &record );
91 /*******************************************************************
92 * format_exception_msg
94 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
96 const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
97 int len,len2;
99 switch(rec->ExceptionCode)
101 case EXCEPTION_INT_DIVIDE_BY_ZERO:
102 len = snprintf( buffer, size, "Unhandled division by zero" );
103 break;
104 case EXCEPTION_INT_OVERFLOW:
105 len = snprintf( buffer, size, "Unhandled overflow" );
106 break;
107 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
108 len = snprintf( buffer, size, "Unhandled array bounds" );
109 break;
110 case EXCEPTION_ILLEGAL_INSTRUCTION:
111 len = snprintf( buffer, size, "Unhandled illegal instruction" );
112 break;
113 case EXCEPTION_STACK_OVERFLOW:
114 len = snprintf( buffer, size, "Unhandled stack overflow" );
115 break;
116 case EXCEPTION_PRIV_INSTRUCTION:
117 len = snprintf( buffer, size, "Unhandled privileged instruction" );
118 break;
119 case EXCEPTION_ACCESS_VIOLATION:
120 if (rec->NumberParameters == 2)
121 len = snprintf( buffer, size, "Unhandled page fault on %s access to 0x%08lx",
122 rec->ExceptionInformation[0] ? "write" : "read",
123 rec->ExceptionInformation[1]);
124 else
125 len = snprintf( buffer, size, "Unhandled page fault");
126 break;
127 case EXCEPTION_DATATYPE_MISALIGNMENT:
128 len = snprintf( buffer, size, "Unhandled alignment" );
129 break;
130 case CONTROL_C_EXIT:
131 len = snprintf( buffer, size, "Unhandled ^C");
132 break;
133 case STATUS_POSSIBLE_DEADLOCK:
134 len = snprintf( buffer, size, "Critical section %08lx wait failed",
135 rec->ExceptionInformation[0]);
136 break;
137 case EXCEPTION_WINE_STUB:
138 if (HIWORD(rec->ExceptionInformation[1]))
139 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
140 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
141 else
142 len = snprintf( buffer, size, "Unimplemented function %s.%ld called",
143 (char *)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
144 break;
145 case EXCEPTION_WINE_ASSERTION:
146 len = snprintf( buffer, size, "Assertion failed" );
147 break;
148 case EXCEPTION_VM86_INTx:
149 len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
150 rec->ExceptionInformation[0]);
151 break;
152 case EXCEPTION_VM86_STI:
153 len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
154 break;
155 case EXCEPTION_VM86_PICRETURN:
156 len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
157 break;
158 default:
159 len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
160 break;
162 if ((len<0) || (len>=size))
163 return -1;
164 #ifdef __i386__
165 if (ptr->ContextRecord->SegCs != wine_get_cs())
166 len2 = snprintf(buffer+len, size-len,
167 " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
168 ptr->ContextRecord->SegCs,
169 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
170 else
171 #endif
172 len2 = snprintf(buffer+len, size-len,
173 " at address 0x%08lx.\nDo you wish to debug it ?",
174 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
175 if ((len2<0) || (len>=size-len))
176 return -1;
177 return len+len2;
181 /**********************************************************************
182 * send_debug_event
184 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
186 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
188 NTSTATUS ret;
189 HANDLE handle = 0;
191 SERVER_START_REQ( queue_exception_event )
193 req->first = first_chance;
194 wine_server_add_data( req, context, sizeof(*context) );
195 wine_server_add_data( req, rec, sizeof(*rec) );
196 if (!(ret = wine_server_call( req ))) handle = reply->handle;
198 SERVER_END_REQ;
199 if (ret) return ret;
201 /* No need to wait on the handle since the process gets suspended
202 * once the event is passed to the debugger, so when we get back
203 * here the event has been continued already.
205 SERVER_START_REQ( get_exception_status )
207 req->handle = handle;
208 wine_server_set_reply( req, context, sizeof(*context) );
209 wine_server_call( req );
210 ret = reply->status;
212 SERVER_END_REQ;
213 NtClose( handle );
214 return ret;
217 /******************************************************************
218 * start_debugger
220 * Does the effective debugger startup according to 'format'
222 static BOOL start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
224 OBJECT_ATTRIBUTES attr;
225 UNICODE_STRING nameW;
226 char *cmdline, *env, *p;
227 HKEY hDbgConf;
228 DWORD bAuto = FALSE;
229 PROCESS_INFORMATION info;
230 STARTUPINFOA startup;
231 char* format = NULL;
232 BOOL ret = FALSE;
234 static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
235 'S','o','f','t','w','a','r','e','\\',
236 'M','i','c','r','o','s','o','f','t','\\',
237 'W','i','n','d','o','w','s',' ','N','T','\\',
238 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
239 'A','e','D','e','b','u','g',0};
240 static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
241 static const WCHAR AutoW[] = {'A','u','t','o',0};
243 MESSAGE("wine: Unhandled exception (thread %04lx), starting debugger...\n", GetCurrentThreadId());
245 attr.Length = sizeof(attr);
246 attr.RootDirectory = 0;
247 attr.ObjectName = &nameW;
248 attr.Attributes = 0;
249 attr.SecurityDescriptor = NULL;
250 attr.SecurityQualityOfService = NULL;
251 RtlInitUnicodeString( &nameW, AeDebugW );
253 if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
255 char buffer[64];
256 KEY_VALUE_PARTIAL_INFORMATION *info;
257 DWORD format_size = 0;
259 RtlInitUnicodeString( &nameW, DebuggerW );
260 if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
261 NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
263 char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
264 NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
265 data, format_size, &format_size );
266 info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
267 RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
268 format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
269 RtlUnicodeToMultiByteN( format, format_size, NULL,
270 (WCHAR *)info->Data, info->DataLength );
271 format[format_size] = 0;
273 if (info->Type == REG_EXPAND_SZ)
275 char* tmp;
277 /* Expand environment variable references */
278 format_size=ExpandEnvironmentStringsA(format,NULL,0);
279 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
280 ExpandEnvironmentStringsA(format,tmp,format_size);
281 HeapFree(GetProcessHeap(), 0, format);
282 format=tmp;
284 HeapFree( GetProcessHeap(), 0, data );
287 RtlInitUnicodeString( &nameW, AutoW );
288 if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
289 buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
291 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
292 if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
293 else if (info->Type == REG_SZ)
295 WCHAR *str = (WCHAR *)info->Data;
296 str[info->DataLength/sizeof(WCHAR)] = 0;
297 bAuto = atoiW( str );
300 else bAuto = TRUE;
302 NtClose(hDbgConf);
305 if (format)
307 cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
308 sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
309 HeapFree(GetProcessHeap(), 0, format);
311 else
313 cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
314 sprintf(cmdline, "winedbg --auto %ld %ld",
315 GetCurrentProcessId(), (ULONG_PTR)hEvent);
318 if (!bAuto)
320 HMODULE mod = GetModuleHandleA( "user32.dll" );
321 MessageBoxA_funcptr pMessageBoxA = NULL;
323 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
324 if (pMessageBoxA)
326 char buffer[256];
327 format_exception_msg( epointers, buffer, sizeof(buffer) );
328 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
330 TRACE("Killing process\n");
331 goto EXIT;
336 /* remove WINEDEBUG from the environment */
337 env = GetEnvironmentStringsA();
338 for (p = env; *p; p += strlen(p) + 1)
340 if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
342 char *next = p + strlen(p) + 1;
343 char *end = next;
344 while (*end) end += strlen(end) + 1;
345 memmove( p, next, end + 1 - next );
346 break;
350 TRACE("Starting debugger %s\n", debugstr_a(cmdline));
351 memset(&startup, 0, sizeof(startup));
352 startup.cb = sizeof(startup);
353 startup.dwFlags = STARTF_USESHOWWINDOW;
354 startup.wShowWindow = SW_SHOWNORMAL;
355 ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
356 FreeEnvironmentStringsA( env );
358 if (ret) WaitForSingleObject(hEvent, INFINITE); /* wait for debugger to come up... */
359 else ERR("Couldn't start debugger (%s) (%ld)\n"
360 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
361 debugstr_a(cmdline), GetLastError());
362 EXIT:
363 HeapFree(GetProcessHeap(), 0, cmdline);
364 return ret;
367 /******************************************************************
368 * start_debugger_atomic
370 * starts the debugger in an atomic way:
371 * - either the debugger is not started and it is started
372 * - or the debugger has already been started by another thread
373 * - or the debugger couldn't be started
375 * returns TRUE for the two first conditions, FALSE for the last
377 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers)
379 static HANDLE hRunOnce /* = 0 */;
381 if (hRunOnce == 0)
383 OBJECT_ATTRIBUTES attr;
384 HANDLE hEvent;
386 attr.Length = sizeof(attr);
387 attr.RootDirectory = 0;
388 attr.Attributes = OBJ_INHERIT;
389 attr.ObjectName = NULL;
390 attr.SecurityDescriptor = NULL;
391 attr.SecurityQualityOfService = NULL;
393 /* ask for manual reset, so that once the debugger is started,
394 * every thread will know it */
395 NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
396 if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
398 /* ok, our event has been set... we're the winning thread */
399 BOOL ret = start_debugger( epointers, hRunOnce );
400 DWORD tmp;
402 if (!ret)
404 /* so that the other threads won't be stuck */
405 NtSetEvent( hRunOnce, &tmp );
407 return ret;
410 /* someone beat us here... */
411 CloseHandle( hEvent );
414 /* and wait for the winner to have actually created the debugger */
415 WaitForSingleObject( hRunOnce, INFINITE );
416 /* in fact, here, we only know that someone has tried to start the debugger,
417 * we'll know by reposting the exception if it has actually attached
418 * to the current process */
419 return TRUE;
423 /*******************************************************************
424 * check_resource_write
426 * Check if the exception is a write attempt to the resource data.
427 * If yes, we unprotect the resources to let broken apps continue
428 * (Windows does this too).
430 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
432 void *addr, *rsrc;
433 DWORD size;
434 MEMORY_BASIC_INFORMATION info;
436 if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return FALSE;
437 if (rec->NumberParameters < 2) return FALSE;
438 if (!rec->ExceptionInformation[0]) return FALSE; /* not a write access */
439 addr = (void *)rec->ExceptionInformation[1];
440 if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
441 if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
442 IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
443 return FALSE;
444 if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
445 TRACE( "Broken app is writing to the resource data, enabling work-around\n" );
446 VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
447 return TRUE;
451 /*******************************************************************
452 * UnhandledExceptionFilter (KERNEL32.@)
454 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
456 NTSTATUS status;
458 if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
460 if (!NtCurrentTeb()->Peb->BeingDebugged)
462 if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
464 /* do not launch the debugger on ^C, simply terminate the process */
465 TerminateProcess( GetCurrentProcess(), 1 );
468 if (top_filter)
470 DWORD ret = top_filter( epointers );
471 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
474 /* FIXME: Should check the current error mode */
476 if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
477 return EXCEPTION_EXECUTE_HANDLER;
480 /* send a last chance event to the debugger */
481 status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
482 switch (status)
484 case DBG_CONTINUE:
485 return EXCEPTION_CONTINUE_EXECUTION;
486 case DBG_EXCEPTION_NOT_HANDLED:
487 TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
488 break; /* not reached */
489 default:
490 FIXME("Unhandled error on debug event: %lx\n", status);
491 break;
493 return EXCEPTION_EXECUTE_HANDLER;
497 /***********************************************************************
498 * SetUnhandledExceptionFilter (KERNEL32.@)
500 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
501 LPTOP_LEVEL_EXCEPTION_FILTER filter )
503 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
504 top_filter = filter;
505 return old;
509 /**************************************************************************
510 * FatalAppExitA (KERNEL32.@)
512 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
514 HMODULE mod = GetModuleHandleA( "user32.dll" );
515 MessageBoxA_funcptr pMessageBoxA = NULL;
517 WARN("AppExit\n");
519 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
520 if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
521 else ERR( "%s\n", debugstr_a(str) );
522 ExitProcess(0);
526 /**************************************************************************
527 * FatalAppExitW (KERNEL32.@)
529 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
531 static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
533 HMODULE mod = GetModuleHandleW( User32DllW );
534 MessageBoxW_funcptr pMessageBoxW = NULL;
536 WARN("AppExit\n");
538 if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
539 if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
540 else ERR( "%s\n", debugstr_w(str) );
541 ExitProcess(0);
545 /**************************************************************************
546 * FatalExit (KERNEL32.@)
548 void WINAPI FatalExit(int ExitCode)
550 WARN("FatalExit\n");
551 ExitProcess(ExitCode);