Make some i386 code conditional
[reactos.git] / reactos / dll / win32 / kernel32 / except / except.c
1 /* $Id$
2 *
3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS system libraries
5 * FILE: lib/kernel32/misc/except.c
6 * PURPOSE: Exception functions
7 * PROGRAMMER: Ariadne ( ariadne@xs4all.nl)
8 * modified from WINE [ Onno Hovers, (onno@stack.urc.tue.nl) ]
9 * UPDATE HISTORY:
10 * Created 01/11/98
11 */
12
13 #include <k32.h>
14
15 #define NDEBUG
16 #include "../include/debug.h"
17
18 LPTOP_LEVEL_EXCEPTION_FILTER GlobalTopLevelExceptionFilter = UnhandledExceptionFilter;
19
20 UINT
21 WINAPI
22 GetErrorMode(VOID)
23 {
24 NTSTATUS Status;
25 UINT ErrMode;
26
27 /* Query the current setting */
28 Status = NtQueryInformationProcess(NtCurrentProcess(),
29 ProcessDefaultHardErrorMode,
30 (PVOID)&ErrMode,
31 sizeof(ErrMode),
32 NULL);
33 if (!NT_SUCCESS(Status))
34 {
35 /* Fail if we couldn't query */
36 SetLastErrorByStatus(Status);
37 return 0;
38 }
39
40 /* Check if NOT failing critical errors was requested */
41 if (ErrMode & SEM_FAILCRITICALERRORS)
42 {
43 /* Mask it out, since the native API works differently */
44 ErrMode &= ~SEM_FAILCRITICALERRORS;
45 }
46 else
47 {
48 /* OR it if the caller didn't, due to different native semantics */
49 ErrMode |= SEM_FAILCRITICALERRORS;
50 }
51
52 /* Return the mode */
53 return ErrMode;
54 }
55
56 /*
57 * @implemented
58 */
59 UINT
60 WINAPI
61 SetErrorMode(IN UINT uMode)
62 {
63 UINT PrevErrMode, NewMode;
64 NTSTATUS Status;
65
66 /* Get the previous mode */
67 PrevErrMode = GetErrorMode();
68 NewMode = uMode;
69
70 /* Check if failing critical errors was requested */
71 if (NewMode & SEM_FAILCRITICALERRORS)
72 {
73 /* Mask it out, since the native API works differently */
74 NewMode &= ~SEM_FAILCRITICALERRORS;
75 }
76 else
77 {
78 /* OR it if the caller didn't, due to different native semantics */
79 NewMode |= SEM_FAILCRITICALERRORS;
80 }
81
82 /* Set the new mode */
83 Status = NtSetInformationProcess(NtCurrentProcess(),
84 ProcessDefaultHardErrorMode,
85 (PVOID)&NewMode,
86 sizeof(NewMode));
87 if(!NT_SUCCESS(Status)) SetLastErrorByStatus(Status);
88
89 /* Return the previous mode */
90 return PrevErrMode;
91 }
92
93 /*
94 * @implemented
95 */
96 LPTOP_LEVEL_EXCEPTION_FILTER
97 WINAPI
98 SetUnhandledExceptionFilter(
99 IN LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter)
100 {
101 return InterlockedExchangePointer(&GlobalTopLevelExceptionFilter,
102 lpTopLevelExceptionFilter);
103 }
104
105 /*
106 * Private helper function to lookup the module name from a given address.
107 * The address can point to anywhere within the module.
108 */
109 static const char*
110 _module_name_from_addr(const void* addr, void **module_start_addr,
111 char* psz, size_t nChars)
112 {
113 MEMORY_BASIC_INFORMATION mbi;
114 if (VirtualQuery(addr, &mbi, sizeof(mbi)) != sizeof(mbi) ||
115 !GetModuleFileNameA((HMODULE)mbi.AllocationBase, psz, nChars))
116 {
117 psz[0] = '\0';
118 *module_start_addr = 0;
119 }
120 else
121 {
122 *module_start_addr = (void *)mbi.AllocationBase;
123 }
124 return psz;
125 }
126
127 #ifdef _M_IX86
128 static VOID
129 _dump_context(PCONTEXT pc)
130 {
131 /*
132 * Print out the CPU registers
133 */
134 DbgPrint("CS:EIP %x:%x\n", pc->SegCs&0xffff, pc->Eip );
135 DbgPrint("DS %x ES %x FS %x GS %x\n", pc->SegDs&0xffff, pc->SegEs&0xffff,
136 pc->SegFs&0xffff, pc->SegGs&0xfff);
137 DbgPrint("EAX: %.8x EBX: %.8x ECX: %.8x\n", pc->Eax, pc->Ebx, pc->Ecx);
138 DbgPrint("EDX: %.8x EBP: %.8x ESI: %.8x ESP: %.8x\n", pc->Edx,
139 pc->Ebp, pc->Esi, pc->Esp);
140 DbgPrint("EDI: %.8x EFLAGS: %.8x\n", pc->Edi, pc->EFlags);
141 }
142 #else
143 #warning Unknown architecture
144 static VOID
145 _dump_context(PCONTEXT pc)
146 {
147 }
148 #endif
149
150 static LONG
151 BasepCheckForReadOnlyResource(IN PVOID Ptr)
152 {
153 PVOID Data;
154 ULONG Size, OldProtect;
155 MEMORY_BASIC_INFORMATION mbi;
156 NTSTATUS Status;
157 LONG Ret = EXCEPTION_CONTINUE_SEARCH;
158
159 /* Check if it was an attempt to write to a read-only image section! */
160 Status = NtQueryVirtualMemory(NtCurrentProcess(),
161 Ptr,
162 MemoryBasicInformation,
163 &mbi,
164 sizeof(mbi),
165 NULL);
166 if (NT_SUCCESS(Status) &&
167 mbi.Protect == PAGE_READONLY && mbi.Type == MEM_IMAGE)
168 {
169 /* Attempt to treat it as a resource section. We need to
170 use SEH here because we don't know if it's actually a
171 resource mapping */
172
173 _SEH_TRY
174 {
175 Data = RtlImageDirectoryEntryToData(mbi.AllocationBase,
176 TRUE,
177 IMAGE_DIRECTORY_ENTRY_RESOURCE,
178 &Size);
179
180 if (Data != NULL &&
181 (ULONG_PTR)Ptr >= (ULONG_PTR)Data &&
182 (ULONG_PTR)Ptr < (ULONG_PTR)Data + Size)
183 {
184 /* The user tried to write into the resources. Make the page
185 writable... */
186 Size = 1;
187 Status = NtProtectVirtualMemory(NtCurrentProcess(),
188 &Ptr,
189 &Size,
190 PAGE_READWRITE,
191 &OldProtect);
192 if (NT_SUCCESS(Status))
193 {
194 Ret = EXCEPTION_CONTINUE_EXECUTION;
195 }
196 }
197 }
198 _SEH_HANDLE
199 {
200 }
201 _SEH_END;
202 }
203
204 return Ret;
205 }
206
207 /*
208 * @unimplemented
209 */
210 LONG STDCALL
211 UnhandledExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo)
212 {
213 LONG RetValue;
214 HANDLE DebugPort = NULL;
215 NTSTATUS ErrCode;
216
217 if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
218 ExceptionInfo->ExceptionRecord->ExceptionInformation[0])
219 {
220 /* Change the protection on some write attempts, some InstallShield setups
221 have this bug */
222 RetValue = BasepCheckForReadOnlyResource(
223 (PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
224 if (RetValue == EXCEPTION_CONTINUE_EXECUTION)
225 return EXCEPTION_CONTINUE_EXECUTION;
226 }
227
228 /* Is there a debugger running ? */
229 ErrCode = NtQueryInformationProcess(NtCurrentProcess(), ProcessDebugPort,
230 &DebugPort, sizeof(HANDLE), NULL);
231 if (!NT_SUCCESS(ErrCode) && ErrCode != STATUS_NOT_IMPLEMENTED)
232 {
233 SetLastErrorByStatus(ErrCode);
234 return EXCEPTION_EXECUTE_HANDLER;
235 }
236
237 if (DebugPort)
238 {
239 /* Pass the exception to debugger. */
240 DPRINT("Passing exception to debugger\n");
241 return EXCEPTION_CONTINUE_SEARCH;
242 }
243
244 if ((GetErrorMode() & SEM_NOGPFAULTERRORBOX) == 0)
245 {
246 #ifdef _X86_
247 PULONG Frame;
248 #endif
249 PVOID StartAddr;
250 CHAR szMod[128] = "";
251
252 /* Print a stack trace. */
253 DbgPrint("Unhandled exception\n");
254 DbgPrint("ExceptionCode: %8x\n", ExceptionInfo->ExceptionRecord->ExceptionCode);
255 if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
256 ExceptionInfo->ExceptionRecord->NumberParameters == 2)
257 {
258 DbgPrint("Faulting Address: %8x\n", ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
259 }
260 DbgPrint("Address: %8x %s\n",
261 ExceptionInfo->ExceptionRecord->ExceptionAddress,
262 _module_name_from_addr(ExceptionInfo->ExceptionRecord->ExceptionAddress, &StartAddr, szMod, sizeof(szMod)));
263 _dump_context ( ExceptionInfo->ContextRecord );
264 #ifdef _X86_
265 DbgPrint("Frames:\n");
266 _SEH_TRY
267 {
268 Frame = (PULONG)ExceptionInfo->ContextRecord->Ebp;
269 while (Frame[1] != 0 && Frame[1] != 0xdeadbeef)
270 {
271 if (IsBadReadPtr((PVOID)Frame[1], 4)) {
272 DbgPrint(" %8x%9s %s\n", Frame[1], "<invalid address>"," ");
273 } else {
274 _module_name_from_addr((const void*)Frame[1], &StartAddr,
275 szMod, sizeof(szMod));
276 DbgPrint(" %8x+%-8x %s\n",
277 (PVOID)StartAddr,
278 (ULONG_PTR)Frame[1] - (ULONG_PTR)StartAddr, szMod);
279 }
280 if (IsBadReadPtr((PVOID)Frame[0], sizeof(*Frame) * 2)) {
281 break;
282 }
283 Frame = (PULONG)Frame[0];
284 }
285 }
286 _SEH_HANDLE
287 {
288 DbgPrint("<error dumping stack trace: 0x%x>\n", _SEH_GetExceptionCode());
289 }
290 _SEH_END;
291 #endif
292 }
293
294 /*
295 * Returning EXCEPTION_EXECUTE_HANDLER means that the code in
296 * the __except block will be executed. Normally this will end up in a
297 * Terminate process.
298 */
299
300 return EXCEPTION_EXECUTE_HANDLER;
301 }
302
303 /*
304 * @implemented
305 */
306 VOID
307 WINAPI
308 RaiseException(IN DWORD dwExceptionCode,
309 IN DWORD dwExceptionFlags,
310 IN DWORD nNumberOfArguments,
311 IN CONST ULONG_PTR *lpArguments OPTIONAL)
312 {
313 EXCEPTION_RECORD ExceptionRecord;
314
315 /* Setup the exception record */
316 ExceptionRecord.ExceptionCode = dwExceptionCode;
317 ExceptionRecord.ExceptionRecord = NULL;
318 ExceptionRecord.ExceptionAddress = (PVOID)RaiseException;
319 ExceptionRecord.ExceptionFlags = dwExceptionFlags & EXCEPTION_NONCONTINUABLE;
320
321 /* Check if we have arguments */
322 if (!lpArguments)
323 {
324 /* We don't */
325 ExceptionRecord.NumberParameters = 0;
326 }
327 else
328 {
329 /* We do, normalize the count */
330 if (nNumberOfArguments > EXCEPTION_MAXIMUM_PARAMETERS)
331 {
332 nNumberOfArguments = EXCEPTION_MAXIMUM_PARAMETERS;
333 }
334
335 /* Set the count of parameters */
336 ExceptionRecord.NumberParameters = nNumberOfArguments;
337
338 /* Loop each parameter */
339 for (nNumberOfArguments = 0;
340 (nNumberOfArguments < ExceptionRecord.NumberParameters);
341 nNumberOfArguments ++)
342 {
343 /* Copy the exception information */
344 ExceptionRecord.ExceptionInformation[nNumberOfArguments] =
345 *lpArguments++;
346 }
347 }
348
349 /* Raise the exception */
350 RtlRaiseException(&ExceptionRecord);
351 }
352
353 /* EOF */