Support float and function ptr args better, -W warning fixes.
[wine/wine64.git] / win32 / except.c
blob8e6a5bcc60e7bcb3ebad51a3dabaefab689168af
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 "stackframe.h"
51 #include "excpt.h"
52 #include "wine/server.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 LPDWORD 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] ? "write" : "read",
120 rec->ExceptionInformation[1]);
121 else
122 len = snprintf( buffer, size, "Unhandled page fault");
123 break;
124 case EXCEPTION_DATATYPE_MISALIGNMENT:
125 len = snprintf( buffer, size, "Unhandled alignment" );
126 break;
127 case CONTROL_C_EXIT:
128 len = snprintf( buffer, size, "Unhandled ^C");
129 break;
130 case STATUS_POSSIBLE_DEADLOCK:
131 len = snprintf( buffer, size, "Critical section %08lx wait failed",
132 rec->ExceptionInformation[0]);
133 break;
134 case EXCEPTION_WINE_STUB:
135 len = snprintf( buffer, size, "Unimplemented function %s.%s called",
136 (char *)rec->ExceptionInformation[0], (char *)rec->ExceptionInformation[1] );
137 break;
138 case EXCEPTION_WINE_ASSERTION:
139 len = snprintf( buffer, size, "Assertion failed" );
140 break;
141 case EXCEPTION_VM86_INTx:
142 len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
143 rec->ExceptionInformation[0]);
144 break;
145 case EXCEPTION_VM86_STI:
146 len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
147 break;
148 case EXCEPTION_VM86_PICRETURN:
149 len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
150 break;
151 default:
152 len = snprintf( buffer, size, "Unhandled exception 0x%08lx", rec->ExceptionCode);
153 break;
155 if ((len<0) || (len>=size))
156 return -1;
157 #ifdef __i386__
158 if (ptr->ContextRecord->SegCs != wine_get_cs())
159 len2 = snprintf(buffer+len, size-len,
160 " at address 0x%04lx:0x%08lx.\nDo you wish to debug it ?",
161 ptr->ContextRecord->SegCs,
162 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
163 else
164 #endif
165 len2 = snprintf(buffer+len, size-len,
166 " at address 0x%08lx.\nDo you wish to debug it ?",
167 (DWORD)ptr->ExceptionRecord->ExceptionAddress);
168 if ((len2<0) || (len>=size-len))
169 return -1;
170 return len+len2;
174 /**********************************************************************
175 * send_debug_event
177 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
179 static int send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
181 int ret;
182 HANDLE handle = 0;
184 SERVER_START_REQ( queue_exception_event )
186 req->first = first_chance;
187 wine_server_add_data( req, context, sizeof(*context) );
188 wine_server_add_data( req, rec, sizeof(*rec) );
189 if (!wine_server_call(req)) handle = reply->handle;
191 SERVER_END_REQ;
192 if (!handle) return 0; /* no debugger present or other error */
194 /* No need to wait on the handle since the process gets suspended
195 * once the event is passed to the debugger, so when we get back
196 * here the event has been continued already.
198 SERVER_START_REQ( get_exception_status )
200 req->handle = handle;
201 wine_server_set_reply( req, context, sizeof(*context) );
202 wine_server_call( req );
203 ret = reply->status;
205 SERVER_END_REQ;
206 NtClose( handle );
207 return ret;
210 /******************************************************************
211 * start_debugger
213 * Does the effective debugger startup according to 'format'
215 static BOOL start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
217 OBJECT_ATTRIBUTES attr;
218 UNICODE_STRING nameW;
219 HKEY hDbgConf;
220 DWORD bAuto = FALSE;
221 PROCESS_INFORMATION info;
222 STARTUPINFOA startup;
223 char* cmdline;
224 char* format = NULL;
225 BOOL ret = FALSE;
227 static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
228 'S','o','f','t','w','a','r','e','\\',
229 'M','i','c','r','o','s','o','f','t','\\',
230 'W','i','n','d','o','w','s',' ','N','T','\\',
231 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
232 'A','e','D','e','b','u','g',0};
233 static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
234 static const WCHAR AutoW[] = {'A','u','t','o',0};
236 MESSAGE("wine: Unhandled exception (thread %04lx), starting debugger...\n", GetCurrentThreadId());
238 attr.Length = sizeof(attr);
239 attr.RootDirectory = 0;
240 attr.ObjectName = &nameW;
241 attr.Attributes = 0;
242 attr.SecurityDescriptor = NULL;
243 attr.SecurityQualityOfService = NULL;
244 RtlInitUnicodeString( &nameW, AeDebugW );
246 if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
248 char buffer[64];
249 KEY_VALUE_PARTIAL_INFORMATION *info;
250 DWORD format_size = 0;
252 RtlInitUnicodeString( &nameW, DebuggerW );
253 if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
254 NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
256 char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
257 NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
258 data, format_size, &format_size );
259 info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
260 RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
261 format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
262 RtlUnicodeToMultiByteN( format, format_size, NULL,
263 (WCHAR *)info->Data, info->DataLength );
264 format[format_size] = 0;
266 if (info->Type == REG_EXPAND_SZ)
268 char* tmp;
270 /* Expand environment variable references */
271 format_size=ExpandEnvironmentStringsA(format,NULL,0);
272 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
273 ExpandEnvironmentStringsA(format,tmp,format_size);
274 HeapFree(GetProcessHeap(), 0, format);
275 format=tmp;
277 HeapFree( GetProcessHeap(), 0, data );
280 RtlInitUnicodeString( &nameW, AutoW );
281 if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
282 buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
284 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
285 if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
286 else if (info->Type == REG_SZ)
288 WCHAR *str = (WCHAR *)info->Data;
289 str[info->DataLength/sizeof(WCHAR)] = 0;
290 bAuto = atoiW( str );
293 else bAuto = TRUE;
295 NtClose(hDbgConf);
298 if (format)
300 cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
301 sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
302 HeapFree(GetProcessHeap(), 0, format);
304 else
306 cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
307 sprintf(cmdline, "winedbg --debugmsg -all --auto %ld %ld",
308 GetCurrentProcessId(), (ULONG_PTR)hEvent);
311 if (!bAuto)
313 HMODULE mod = GetModuleHandleA( "user32.dll" );
314 MessageBoxA_funcptr pMessageBoxA = NULL;
316 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
317 if (pMessageBoxA)
319 char buffer[256];
320 format_exception_msg( epointers, buffer, sizeof(buffer) );
321 if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
323 TRACE("Killing process\n");
324 goto EXIT;
329 TRACE("Starting debugger %s\n", debugstr_a(cmdline));
330 memset(&startup, 0, sizeof(startup));
331 startup.cb = sizeof(startup);
332 startup.dwFlags = STARTF_USESHOWWINDOW;
333 startup.wShowWindow = SW_SHOWNORMAL;
334 ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &info);
336 if (ret) WaitForSingleObject(hEvent, INFINITE); /* wait for debugger to come up... */
337 else ERR("Couldn't start debugger (%s) (%ld)\n"
338 "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
339 debugstr_a(cmdline), GetLastError());
340 EXIT:
341 HeapFree(GetProcessHeap(), 0, cmdline);
342 return ret;
345 /******************************************************************
346 * start_debugger_atomic
348 * starts the debugger in an atomic way:
349 * - either the debugger is not started and it is started
350 * - or the debugger has already been started by another thread
351 * - or the debugger couldn't be started
353 * returns TRUE for the two first conditions, FALSE for the last
355 static int start_debugger_atomic(PEXCEPTION_POINTERS epointers)
357 static HANDLE hRunOnce /* = 0 */;
359 if (hRunOnce == 0)
361 OBJECT_ATTRIBUTES attr;
362 HANDLE hEvent;
364 attr.Length = sizeof(attr);
365 attr.RootDirectory = 0;
366 attr.Attributes = OBJ_INHERIT;
367 attr.ObjectName = NULL;
368 attr.SecurityDescriptor = NULL;
369 attr.SecurityQualityOfService = NULL;
371 /* ask for manual reset, so that once the debugger is started,
372 * every thread will know it */
373 NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
374 if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
376 /* ok, our event has been set... we're the winning thread */
377 BOOL ret = start_debugger( epointers, hRunOnce );
378 DWORD tmp;
380 if (!ret)
382 /* so that the other threads won't be stuck */
383 NtSetEvent( hRunOnce, &tmp );
385 return ret;
388 /* someone beat us here... */
389 CloseHandle( hEvent );
392 /* and wait for the winner to have actually created the debugger */
393 WaitForSingleObject( hRunOnce, INFINITE );
394 /* in fact, here, we only know that someone has tried to start the debugger,
395 * we'll know by reposting the exception if it has actually attached
396 * to the current process */
397 return TRUE;
401 /*******************************************************************
402 * check_resource_write
404 * Check if the exception is a write attempt to the resource data.
405 * If yes, we unprotect the resources to let broken apps continue
406 * (Windows does this too).
408 inline static BOOL check_resource_write( const EXCEPTION_RECORD *rec )
410 void *addr, *rsrc;
411 DWORD size;
412 MEMORY_BASIC_INFORMATION info;
414 if (rec->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) return FALSE;
415 if (!rec->ExceptionInformation[0]) return FALSE; /* not a write access */
416 addr = (void *)rec->ExceptionInformation[1];
417 if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
418 if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
419 IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
420 return FALSE;
421 if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
422 FIXME( "Broken app is writing to the resource data, enabling work-around\n" );
423 VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
424 return TRUE;
428 /*******************************************************************
429 * UnhandledExceptionFilter (KERNEL32.@)
431 DWORD WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
433 int status;
434 int loop = 0;
436 if (check_resource_write( epointers->ExceptionRecord )) return EXCEPTION_CONTINUE_EXECUTION;
438 for (loop = 0; loop <= 1; loop++)
440 /* send a last chance event to the debugger */
441 status = send_debug_event( epointers->ExceptionRecord, FALSE, epointers->ContextRecord );
442 switch (status)
444 case DBG_CONTINUE:
445 return EXCEPTION_CONTINUE_EXECUTION;
446 case DBG_EXCEPTION_NOT_HANDLED:
447 TerminateProcess( GetCurrentProcess(), epointers->ExceptionRecord->ExceptionCode );
448 break; /* not reached */
449 case 0: /* no debugger is present */
450 if (epointers->ExceptionRecord->ExceptionCode == CONTROL_C_EXIT)
452 /* do not launch the debugger on ^C, simply terminate the process */
453 TerminateProcess( GetCurrentProcess(), 1 );
455 /* second try, the debugger isn't present... */
456 if (loop == 1) return EXCEPTION_EXECUTE_HANDLER;
457 break;
458 default:
459 FIXME("Unsupported yet debug continue value %d (please report)\n", status);
460 return EXCEPTION_EXECUTE_HANDLER;
463 /* should only be there when loop == 0 */
465 if (top_filter)
467 DWORD ret = top_filter( epointers );
468 if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
471 /* FIXME: Should check the current error mode */
473 if (!start_debugger_atomic( epointers ))
474 return EXCEPTION_EXECUTE_HANDLER;
475 /* now that we should have a debugger attached, try to resend event */
478 return EXCEPTION_EXECUTE_HANDLER;
482 /***********************************************************************
483 * SetUnhandledExceptionFilter (KERNEL32.@)
485 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
486 LPTOP_LEVEL_EXCEPTION_FILTER filter )
488 LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
489 top_filter = filter;
490 return old;
494 /**************************************************************************
495 * FatalAppExitA (KERNEL32.@)
497 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
499 HMODULE mod = GetModuleHandleA( "user32.dll" );
500 MessageBoxA_funcptr pMessageBoxA = NULL;
502 WARN("AppExit\n");
504 if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
505 if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
506 else ERR( "%s\n", debugstr_a(str) );
507 ExitProcess(0);
511 /**************************************************************************
512 * FatalAppExitW (KERNEL32.@)
514 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
516 static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
518 HMODULE mod = GetModuleHandleW( User32DllW );
519 MessageBoxW_funcptr pMessageBoxW = NULL;
521 WARN("AppExit\n");
523 if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
524 if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
525 else ERR( "%s\n", debugstr_w(str) );
526 ExitProcess(0);
530 /**************************************************************************
531 * FatalExit (KERNEL32.@)
533 void WINAPI FatalExit(int ExitCode)
535 WARN("FatalExit\n");
536 ExitProcess(ExitCode);