kernel32: Fix LANGID for Korean resource.
[wine] / dlls / kernel32 / except.c
1 /*
2  * Win32 exception functions
3  *
4  * Copyright (c) 1996 Onno Hovers, (onno@stack.urc.tue.nl)
5  * Copyright (c) 1999 Alexandre Julliard
6  *
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.
11  *
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.
16  *
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
20  *
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).
31  *
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!
36  *
37  */
38 #include "config.h"
39 #include "wine/port.h"
40
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 "winerror.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 "excpt.h"
54 #include "wine/unicode.h"
55 #include "wine/debug.h"
56
57 WINE_DEFAULT_DEBUG_CHANNEL(seh);
58
59 static PTOP_LEVEL_EXCEPTION_FILTER top_filter;
60
61 typedef INT (WINAPI *MessageBoxA_funcptr)(HWND,LPCSTR,LPCSTR,UINT);
62 typedef INT (WINAPI *MessageBoxW_funcptr)(HWND,LPCWSTR,LPCWSTR,UINT);
63
64 /*******************************************************************
65  *         RaiseException  (KERNEL32.@)
66  */
67 void WINAPI RaiseException( DWORD code, DWORD flags, DWORD nbargs, const ULONG_PTR *args )
68 {
69     EXCEPTION_RECORD record;
70
71     /* Compose an exception record */
72
73     record.ExceptionCode    = code;
74     record.ExceptionFlags   = flags & EH_NONCONTINUABLE;
75     record.ExceptionRecord  = NULL;
76     record.ExceptionAddress = RaiseException;
77     if (nbargs && args)
78     {
79         if (nbargs > EXCEPTION_MAXIMUM_PARAMETERS) nbargs = EXCEPTION_MAXIMUM_PARAMETERS;
80         record.NumberParameters = nbargs;
81         memcpy( record.ExceptionInformation, args, nbargs * sizeof(*args) );
82     }
83     else record.NumberParameters = 0;
84
85     RtlRaiseException( &record );
86 }
87
88
89 /*******************************************************************
90  *         format_exception_msg
91  */
92 static int format_exception_msg( const EXCEPTION_POINTERS *ptr, char *buffer, int size )
93 {
94     const EXCEPTION_RECORD *rec = ptr->ExceptionRecord;
95     int len,len2;
96
97     switch(rec->ExceptionCode)
98     {
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 (HIWORD(rec->ExceptionInformation[1]))
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     case EXCEPTION_VM86_INTx:
148         len = snprintf( buffer, size, "Unhandled interrupt %02lx in vm86 mode",
149                  rec->ExceptionInformation[0]);
150         break;
151     case EXCEPTION_VM86_STI:
152         len = snprintf( buffer, size, "Unhandled sti in vm86 mode");
153         break;
154     case EXCEPTION_VM86_PICRETURN:
155         len = snprintf( buffer, size, "Unhandled PIC return in vm86 mode");
156         break;
157     default:
158         len = snprintf( buffer, size, "Unhandled exception 0x%08x", rec->ExceptionCode);
159         break;
160     }
161     if ((len<0) || (len>=size))
162         return -1;
163 #ifdef __i386__
164     if (ptr->ContextRecord->SegCs != wine_get_cs())
165         len2 = snprintf(buffer+len, size-len, " at address 0x%04x:0x%08x",
166                         ptr->ContextRecord->SegCs,
167                         (DWORD)ptr->ExceptionRecord->ExceptionAddress);
168     else
169 #endif
170         len2 = snprintf(buffer+len, size-len, " at address %p",
171                         ptr->ExceptionRecord->ExceptionAddress);
172     if ((len2<0) || (len>=size-len))
173         return -1;
174     return len+len2;
175 }
176
177
178 /******************************************************************
179  *              start_debugger
180  *
181  * Does the effective debugger startup according to 'format'
182  */
183 static BOOL     start_debugger(PEXCEPTION_POINTERS epointers, HANDLE hEvent)
184 {
185     OBJECT_ATTRIBUTES attr;
186     UNICODE_STRING nameW;
187     char *cmdline, *env, *p;
188     HANDLE              hDbgConf;
189     DWORD               bAuto = FALSE;
190     PROCESS_INFORMATION info;
191     STARTUPINFOA        startup;
192     char*               format = NULL;
193     BOOL                ret = FALSE;
194     char buffer[256];
195
196     static const WCHAR AeDebugW[] = {'M','a','c','h','i','n','e','\\',
197                                      'S','o','f','t','w','a','r','e','\\',
198                                      'M','i','c','r','o','s','o','f','t','\\',
199                                      'W','i','n','d','o','w','s',' ','N','T','\\',
200                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
201                                      'A','e','D','e','b','u','g',0};
202     static const WCHAR DebuggerW[] = {'D','e','b','u','g','g','e','r',0};
203     static const WCHAR AutoW[] = {'A','u','t','o',0};
204
205     format_exception_msg( epointers, buffer, sizeof(buffer) );
206     MESSAGE("wine: %s (thread %04x), starting debugger...\n", buffer, GetCurrentThreadId());
207
208     attr.Length = sizeof(attr);
209     attr.RootDirectory = 0;
210     attr.ObjectName = &nameW;
211     attr.Attributes = 0;
212     attr.SecurityDescriptor = NULL;
213     attr.SecurityQualityOfService = NULL;
214     RtlInitUnicodeString( &nameW, AeDebugW );
215
216     if (!NtOpenKey( &hDbgConf, KEY_ALL_ACCESS, &attr ))
217     {
218         char buffer[64];
219         KEY_VALUE_PARTIAL_INFORMATION *info;
220         DWORD format_size = 0;
221
222         RtlInitUnicodeString( &nameW, DebuggerW );
223         if (NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
224                              NULL, 0, &format_size ) == STATUS_BUFFER_OVERFLOW)
225         {
226             char *data = HeapAlloc(GetProcessHeap(), 0, format_size);
227             NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
228                              data, format_size, &format_size );
229             info = (KEY_VALUE_PARTIAL_INFORMATION *)data;
230             RtlUnicodeToMultiByteSize( &format_size, (WCHAR *)info->Data, info->DataLength );
231             format = HeapAlloc( GetProcessHeap(), 0, format_size+1 );
232             RtlUnicodeToMultiByteN( format, format_size, NULL,
233                                     (WCHAR *)info->Data, info->DataLength );
234             format[format_size] = 0;
235
236             if (info->Type == REG_EXPAND_SZ)
237             {
238                 char* tmp;
239
240                 /* Expand environment variable references */
241                 format_size=ExpandEnvironmentStringsA(format,NULL,0);
242                 tmp=HeapAlloc(GetProcessHeap(), 0, format_size);
243                 ExpandEnvironmentStringsA(format,tmp,format_size);
244                 HeapFree(GetProcessHeap(), 0, format);
245                 format=tmp;
246             }
247             HeapFree( GetProcessHeap(), 0, data );
248         }
249
250         RtlInitUnicodeString( &nameW, AutoW );
251         if (!NtQueryValueKey( hDbgConf, &nameW, KeyValuePartialInformation,
252                               buffer, sizeof(buffer)-sizeof(WCHAR), &format_size ))
253        {
254            info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
255            if (info->Type == REG_DWORD) memcpy( &bAuto, info->Data, sizeof(DWORD) );
256            else if (info->Type == REG_SZ)
257            {
258                WCHAR *str = (WCHAR *)info->Data;
259                str[info->DataLength/sizeof(WCHAR)] = 0;
260                bAuto = atoiW( str );
261            }
262        }
263        else bAuto = TRUE;
264
265        NtClose(hDbgConf);
266     }
267
268     if (format)
269     {
270         cmdline = HeapAlloc(GetProcessHeap(), 0, strlen(format) + 2*20);
271         sprintf(cmdline, format, GetCurrentProcessId(), hEvent);
272         HeapFree(GetProcessHeap(), 0, format);
273     }
274     else
275     {
276         cmdline = HeapAlloc(GetProcessHeap(), 0, 80);
277         sprintf(cmdline, "winedbg --auto %d %ld",
278                 GetCurrentProcessId(), (ULONG_PTR)hEvent);
279     }
280
281     if (!bAuto)
282     {
283         HMODULE                 mod = GetModuleHandleA( "user32.dll" );
284         MessageBoxA_funcptr     pMessageBoxA = NULL;
285
286         if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
287         if (pMessageBoxA)
288         {
289             static const char msg[] = ".\nDo you wish to debug it?";
290             char buffer[256];
291
292             format_exception_msg( epointers, buffer, sizeof(buffer)-sizeof(msg) );
293             strcat( buffer, msg );
294             if (pMessageBoxA( 0, buffer, "Exception raised", MB_YESNO | MB_ICONHAND ) == IDNO)
295             {
296                 TRACE("Killing process\n");
297                 goto EXIT;
298             }
299         }
300     }
301
302     /* make WINEDEBUG empty in the environment */
303     env = GetEnvironmentStringsA();
304     for (p = env; *p; p += strlen(p) + 1)
305     {
306         if (!memcmp( p, "WINEDEBUG=", sizeof("WINEDEBUG=")-1 ))
307         {
308             char *next = p + strlen(p);
309             char *end = next + 1;
310             while (*end) end += strlen(end) + 1;
311             memmove( p + sizeof("WINEDEBUG=") - 1, next, end + 1 - next );
312             break;
313         }
314     }
315
316     TRACE("Starting debugger %s\n", debugstr_a(cmdline));
317     memset(&startup, 0, sizeof(startup));
318     startup.cb = sizeof(startup);
319     startup.dwFlags = STARTF_USESHOWWINDOW;
320     startup.wShowWindow = SW_SHOWNORMAL;
321     ret = CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, 0, env, NULL, &startup, &info);
322     FreeEnvironmentStringsA( env );
323
324     if (ret) WaitForSingleObject(hEvent, INFINITE);  /* wait for debugger to come up... */
325     else ERR("Couldn't start debugger (%s) (%d)\n"
326              "Read the Wine Developers Guide on how to set up winedbg or another debugger\n",
327              debugstr_a(cmdline), GetLastError());
328 EXIT:
329     HeapFree(GetProcessHeap(), 0, cmdline);
330     return ret;
331 }
332
333 /******************************************************************
334  *              start_debugger_atomic
335  *
336  * starts the debugger in an atomic way:
337  *      - either the debugger is not started and it is started
338  *      - or the debugger has already been started by another thread
339  *      - or the debugger couldn't be started
340  *
341  * returns TRUE for the two first conditions, FALSE for the last
342  */
343 static  int     start_debugger_atomic(PEXCEPTION_POINTERS epointers)
344 {
345     static HANDLE       hRunOnce /* = 0 */;
346
347     if (hRunOnce == 0)
348     {
349         OBJECT_ATTRIBUTES       attr;
350         HANDLE                  hEvent;
351
352         attr.Length                   = sizeof(attr);
353         attr.RootDirectory            = 0;
354         attr.Attributes               = OBJ_INHERIT;
355         attr.ObjectName               = NULL;
356         attr.SecurityDescriptor       = NULL;
357         attr.SecurityQualityOfService = NULL;
358
359         /* ask for manual reset, so that once the debugger is started,
360          * every thread will know it */
361         NtCreateEvent( &hEvent, EVENT_ALL_ACCESS, &attr, TRUE, FALSE );
362         if (InterlockedCompareExchangePointer( (PVOID)&hRunOnce, hEvent, 0 ) == 0)
363         {
364             /* ok, our event has been set... we're the winning thread */
365             BOOL        ret = start_debugger( epointers, hRunOnce );
366             DWORD       tmp;
367
368             if (!ret)
369             {
370                 /* so that the other threads won't be stuck */
371                 NtSetEvent( hRunOnce, &tmp );
372             }
373             return ret;
374         }
375
376         /* someone beat us here... */
377         CloseHandle( hEvent );
378     }
379
380     /* and wait for the winner to have actually created the debugger */
381     WaitForSingleObject( hRunOnce, INFINITE );
382     /* in fact, here, we only know that someone has tried to start the debugger,
383      * we'll know by reposting the exception if it has actually attached
384      * to the current process */
385     return TRUE;
386 }
387
388
389 /*******************************************************************
390  *         check_resource_write
391  *
392  * Check if the exception is a write attempt to the resource data.
393  * If yes, we unprotect the resources to let broken apps continue
394  * (Windows does this too).
395  */
396 inline static BOOL check_resource_write( void *addr )
397 {
398     void *rsrc;
399     DWORD size;
400     MEMORY_BASIC_INFORMATION info;
401
402     if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
403     if (info.State == MEM_FREE || !(info.Type & MEM_IMAGE)) return FALSE;
404     if (!(rsrc = RtlImageDirectoryEntryToData( (HMODULE)info.AllocationBase, TRUE,
405                                               IMAGE_DIRECTORY_ENTRY_RESOURCE, &size )))
406         return FALSE;
407     if (addr < rsrc || (char *)addr >= (char *)rsrc + size) return FALSE;
408     TRACE( "Broken app is writing to the resource data, enabling work-around\n" );
409     VirtualProtect( rsrc, size, PAGE_WRITECOPY, NULL );
410     return TRUE;
411 }
412
413
414 /*******************************************************************
415  *         check_no_exec
416  *
417  * Check for executing a protected area.
418  */
419 inline static BOOL check_no_exec( void *addr )
420 {
421     MEMORY_BASIC_INFORMATION info;
422
423     if (!VirtualQuery( addr, &info, sizeof(info) )) return FALSE;
424     if (info.State == MEM_FREE) return FALSE;
425
426     /* prot |= PAGE_EXECUTE would be a lot easier, but MS developers
427      * apparently don't grasp the notion of protection bits */
428     switch(info.Protect)
429     {
430     case PAGE_READONLY: info.Protect = PAGE_EXECUTE_READ; break;
431     case PAGE_READWRITE: info.Protect = PAGE_EXECUTE_READWRITE; break;
432     case PAGE_WRITECOPY: info.Protect = PAGE_EXECUTE_WRITECOPY; break;
433     default: return FALSE;
434     }
435     /* FIXME: we should probably have a per-app option, and maybe a message box */
436     FIXME( "No-exec fault triggered at %p, enabling work-around\n", addr );
437     return VirtualProtect( addr, 1, info.Protect, NULL );
438 }
439
440
441 /*******************************************************************
442  *         UnhandledExceptionFilter   (KERNEL32.@)
443  */
444 LONG WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS epointers)
445 {
446     const EXCEPTION_RECORD *rec = epointers->ExceptionRecord;
447
448     if (rec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && rec->NumberParameters >= 2)
449     {
450         switch(rec->ExceptionInformation[0])
451         {
452         case EXCEPTION_WRITE_FAULT:
453             if (check_resource_write( (void *)rec->ExceptionInformation[1] ))
454                 return EXCEPTION_CONTINUE_EXECUTION;
455             break;
456         case EXCEPTION_EXECUTE_FAULT:
457             if (check_no_exec( (void *)rec->ExceptionInformation[1] ))
458                 return EXCEPTION_CONTINUE_EXECUTION;
459             break;
460         }
461     }
462
463     if (!NtCurrentTeb()->Peb->BeingDebugged)
464     {
465         if (rec->ExceptionCode == CONTROL_C_EXIT)
466         {
467             /* do not launch the debugger on ^C, simply terminate the process */
468             TerminateProcess( GetCurrentProcess(), 1 );
469         }
470
471         if (top_filter)
472         {
473             LONG ret = top_filter( epointers );
474             if (ret != EXCEPTION_CONTINUE_SEARCH) return ret;
475         }
476
477         /* FIXME: Should check the current error mode */
478
479         if (!start_debugger_atomic( epointers ) || !NtCurrentTeb()->Peb->BeingDebugged)
480             return EXCEPTION_EXECUTE_HANDLER;
481     }
482     return EXCEPTION_CONTINUE_SEARCH;
483 }
484
485
486 /***********************************************************************
487  *            SetUnhandledExceptionFilter   (KERNEL32.@)
488  */
489 LPTOP_LEVEL_EXCEPTION_FILTER WINAPI SetUnhandledExceptionFilter(
490                                           LPTOP_LEVEL_EXCEPTION_FILTER filter )
491 {
492     LPTOP_LEVEL_EXCEPTION_FILTER old = top_filter;
493     top_filter = filter;
494     return old;
495 }
496
497
498 /**************************************************************************
499  *           FatalAppExitA   (KERNEL32.@)
500  */
501 void WINAPI FatalAppExitA( UINT action, LPCSTR str )
502 {
503     HMODULE mod = GetModuleHandleA( "user32.dll" );
504     MessageBoxA_funcptr pMessageBoxA = NULL;
505
506     WARN("AppExit\n");
507
508     if (mod) pMessageBoxA = (MessageBoxA_funcptr)GetProcAddress( mod, "MessageBoxA" );
509     if (pMessageBoxA) pMessageBoxA( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
510     else ERR( "%s\n", debugstr_a(str) );
511     ExitProcess(0);
512 }
513
514
515 /**************************************************************************
516  *           FatalAppExitW   (KERNEL32.@)
517  */
518 void WINAPI FatalAppExitW( UINT action, LPCWSTR str )
519 {
520     static const WCHAR User32DllW[] = {'u','s','e','r','3','2','.','d','l','l',0};
521
522     HMODULE mod = GetModuleHandleW( User32DllW );
523     MessageBoxW_funcptr pMessageBoxW = NULL;
524
525     WARN("AppExit\n");
526
527     if (mod) pMessageBoxW = (MessageBoxW_funcptr)GetProcAddress( mod, "MessageBoxW" );
528     if (pMessageBoxW) pMessageBoxW( 0, str, NULL, MB_SYSTEMMODAL | MB_OK );
529     else ERR( "%s\n", debugstr_w(str) );
530     ExitProcess(0);
531 }
532
533
534 /**************************************************************************
535  *           FatalExit   (KERNEL32.@)
536  */
537 void WINAPI FatalExit(int ExitCode)
538 {
539     WARN("FatalExit\n");
540     ExitProcess(ExitCode);
541 }