sync to trunk head (35945)
[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 <debug.h>
17
18 LPTOP_LEVEL_EXCEPTION_FILTER GlobalTopLevelExceptionFilter = NULL;
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 #elif defined(_M_AMD64)
143 _dump_context(PCONTEXT pc)
144 {
145 DbgPrint("CS:EIP %x:%I64x\n", pc->SegCs&0xffff, pc->Rip );
146 DbgPrint("DS %x ES %x FS %x GS %x\n", pc->SegDs&0xffff, pc->SegEs&0xffff,
147 pc->SegFs&0xffff, pc->SegGs&0xfff);
148 DbgPrint("RAX: %I64x RBX: %I64x RCX: %I64x RDI: %I64x\n", pc->Rax, pc->Rbx, pc->Rcx, pc->Rdi);
149 DbgPrint("RDX: %I64x RBP: %I64x RSI: %I64x RSP: %I64x\n", pc->Rdx, pc->Rbp, pc->Rsi, pc->Rsp);
150 DbgPrint("R8: %I64x R9: %I64x R10: %I64x R11: %I64x\n", pc->R8, pc->R9, pc->R10, pc->R11);
151 DbgPrint("R12: %I64x R13: %I64x R14: %I64x R15: %I64x\n", pc->R12, pc->R13, pc->R14, pc->R15);
152 DbgPrint("EFLAGS: %.8x\n", pc->EFlags);
153 }
154 #else
155 #warning Unknown architecture
156 static VOID
157 _dump_context(PCONTEXT pc)
158 {
159 }
160 #endif
161
162 static LONG
163 BasepCheckForReadOnlyResource(IN PVOID Ptr)
164 {
165 PVOID Data;
166 ULONG Size, OldProtect;
167 MEMORY_BASIC_INFORMATION mbi;
168 NTSTATUS Status;
169 LONG Ret = EXCEPTION_CONTINUE_SEARCH;
170
171 /* Check if it was an attempt to write to a read-only image section! */
172 Status = NtQueryVirtualMemory(NtCurrentProcess(),
173 Ptr,
174 MemoryBasicInformation,
175 &mbi,
176 sizeof(mbi),
177 NULL);
178 if (NT_SUCCESS(Status) &&
179 mbi.Protect == PAGE_READONLY && mbi.Type == MEM_IMAGE)
180 {
181 /* Attempt to treat it as a resource section. We need to
182 use SEH here because we don't know if it's actually a
183 resource mapping */
184
185 _SEH_TRY
186 {
187 Data = RtlImageDirectoryEntryToData(mbi.AllocationBase,
188 TRUE,
189 IMAGE_DIRECTORY_ENTRY_RESOURCE,
190 &Size);
191
192 if (Data != NULL &&
193 (ULONG_PTR)Ptr >= (ULONG_PTR)Data &&
194 (ULONG_PTR)Ptr < (ULONG_PTR)Data + Size)
195 {
196 /* The user tried to write into the resources. Make the page
197 writable... */
198 Size = 1;
199 Status = NtProtectVirtualMemory(NtCurrentProcess(),
200 &Ptr,
201 &Size,
202 PAGE_READWRITE,
203 &OldProtect);
204 if (NT_SUCCESS(Status))
205 {
206 Ret = EXCEPTION_CONTINUE_EXECUTION;
207 }
208 }
209 }
210 _SEH_HANDLE
211 {
212 }
213 _SEH_END;
214 }
215
216 return Ret;
217 }
218
219 /*
220 * @unimplemented
221 */
222 LONG STDCALL
223 UnhandledExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo)
224 {
225 LONG RetValue;
226 HANDLE DebugPort = NULL;
227 NTSTATUS ErrCode;
228 ULONG ErrorParameters[4];
229 ULONG ErrorResponse;
230
231 if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
232 ExceptionInfo->ExceptionRecord->NumberParameters >= 2)
233 {
234 switch(ExceptionInfo->ExceptionRecord->ExceptionInformation[0])
235 {
236 case EXCEPTION_WRITE_FAULT:
237 /* Change the protection on some write attempts, some InstallShield setups
238 have this bug */
239 RetValue = BasepCheckForReadOnlyResource(
240 (PVOID)ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
241 if (RetValue == EXCEPTION_CONTINUE_EXECUTION)
242 return EXCEPTION_CONTINUE_EXECUTION;
243 break;
244 case EXCEPTION_EXECUTE_FAULT:
245 /* FIXME */
246 break;
247 }
248 }
249
250 /* Is there a debugger running ? */
251 ErrCode = NtQueryInformationProcess(NtCurrentProcess(), ProcessDebugPort,
252 &DebugPort, sizeof(HANDLE), NULL);
253 if (!NT_SUCCESS(ErrCode) && ErrCode != STATUS_NOT_IMPLEMENTED)
254 {
255 SetLastErrorByStatus(ErrCode);
256 return EXCEPTION_EXECUTE_HANDLER;
257 }
258
259 if (DebugPort)
260 {
261 /* Pass the exception to debugger. */
262 DPRINT("Passing exception to debugger\n");
263 return EXCEPTION_CONTINUE_SEARCH;
264 }
265
266 if (GlobalTopLevelExceptionFilter)
267 {
268 LONG ret = GlobalTopLevelExceptionFilter( ExceptionInfo );
269 if (ret != EXCEPTION_CONTINUE_SEARCH)
270 return ret;
271 }
272
273 if ((GetErrorMode() & SEM_NOGPFAULTERRORBOX) == 0)
274 {
275 #ifdef __i386__
276 PULONG Frame;
277 #endif
278 PVOID StartAddr;
279 CHAR szMod[128] = "";
280
281 /* Print a stack trace. */
282 DbgPrint("Unhandled exception\n");
283 DbgPrint("ExceptionCode: %8x\n", ExceptionInfo->ExceptionRecord->ExceptionCode);
284 if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
285 ExceptionInfo->ExceptionRecord->NumberParameters == 2)
286 {
287 DbgPrint("Faulting Address: %8x\n", ExceptionInfo->ExceptionRecord->ExceptionInformation[1]);
288 }
289 DbgPrint("Address: %8x %s\n",
290 ExceptionInfo->ExceptionRecord->ExceptionAddress,
291 _module_name_from_addr(ExceptionInfo->ExceptionRecord->ExceptionAddress, &StartAddr, szMod, sizeof(szMod)));
292 _dump_context ( ExceptionInfo->ContextRecord );
293 #ifdef __i386__
294 DbgPrint("Frames:\n");
295 _SEH_TRY
296 {
297 Frame = (PULONG)ExceptionInfo->ContextRecord->Ebp;
298 while (Frame[1] != 0 && Frame[1] != 0xdeadbeef)
299 {
300 if (IsBadReadPtr((PVOID)Frame[1], 4)) {
301 DbgPrint(" %8x%9s %s\n", Frame[1], "<invalid address>"," ");
302 } else {
303 _module_name_from_addr((const void*)Frame[1], &StartAddr,
304 szMod, sizeof(szMod));
305 DbgPrint(" %8x+%-8x %s\n",
306 (PVOID)StartAddr,
307 (ULONG_PTR)Frame[1] - (ULONG_PTR)StartAddr, szMod);
308 }
309 if (IsBadReadPtr((PVOID)Frame[0], sizeof(*Frame) * 2)) {
310 break;
311 }
312 Frame = (PULONG)Frame[0];
313 }
314 }
315 _SEH_HANDLE
316 {
317 DbgPrint("<error dumping stack trace: 0x%x>\n", _SEH_GetExceptionCode());
318 }
319 _SEH_END;
320 #endif
321 }
322
323 /* Save exception code and address */
324 ErrorParameters[0] = (ULONG)ExceptionInfo->ExceptionRecord->ExceptionCode;
325 ErrorParameters[1] = (ULONG)ExceptionInfo->ExceptionRecord->ExceptionAddress;
326
327 if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION)
328 {
329 /* get the type of operation that caused the access violation */
330 ErrorParameters[2] = ExceptionInfo->ExceptionRecord->ExceptionInformation[0];
331 }
332 else
333 {
334 ErrorParameters[2] = ExceptionInfo->ExceptionRecord->ExceptionInformation[2];
335 }
336
337 /* Save faulting address */
338 ErrorParameters[3] = ExceptionInfo->ExceptionRecord->ExceptionInformation[1];
339
340 /* Raise the harderror */
341 ErrCode = NtRaiseHardError(STATUS_UNHANDLED_EXCEPTION | 0x10000000,
342 4, 0, ErrorParameters, OptionOkCancel, &ErrorResponse);
343
344 if (NT_SUCCESS(ErrCode) && (ErrorResponse == ResponseCancel))
345 {
346 /* FIXME: Check the result, if the "Cancel" button was
347 clicked run a debugger */
348 DPRINT1("Debugging is not implemented yet\n");
349 }
350
351 /*
352 * Returning EXCEPTION_EXECUTE_HANDLER means that the code in
353 * the __except block will be executed. Normally this will end up in a
354 * Terminate process.
355 */
356
357 return EXCEPTION_EXECUTE_HANDLER;
358 }
359
360 /*
361 * @implemented
362 */
363 VOID
364 WINAPI
365 RaiseException(IN DWORD dwExceptionCode,
366 IN DWORD dwExceptionFlags,
367 IN DWORD nNumberOfArguments,
368 IN CONST ULONG_PTR *lpArguments OPTIONAL)
369 {
370 EXCEPTION_RECORD ExceptionRecord;
371
372 /* Setup the exception record */
373 ExceptionRecord.ExceptionCode = dwExceptionCode;
374 ExceptionRecord.ExceptionRecord = NULL;
375 ExceptionRecord.ExceptionAddress = (PVOID)RaiseException;
376 ExceptionRecord.ExceptionFlags = dwExceptionFlags & EXCEPTION_NONCONTINUABLE;
377
378 /* Check if we have arguments */
379 if (!lpArguments)
380 {
381 /* We don't */
382 ExceptionRecord.NumberParameters = 0;
383 }
384 else
385 {
386 /* We do, normalize the count */
387 if (nNumberOfArguments > EXCEPTION_MAXIMUM_PARAMETERS)
388 {
389 nNumberOfArguments = EXCEPTION_MAXIMUM_PARAMETERS;
390 }
391
392 /* Set the count of parameters */
393 ExceptionRecord.NumberParameters = nNumberOfArguments;
394
395 /* Loop each parameter */
396 for (nNumberOfArguments = 0;
397 (nNumberOfArguments < ExceptionRecord.NumberParameters);
398 nNumberOfArguments ++)
399 {
400 /* Copy the exception information */
401 ExceptionRecord.ExceptionInformation[nNumberOfArguments] =
402 *lpArguments++;
403 }
404 }
405
406 if (dwExceptionCode == 0xeedface)
407 {
408 DPRINT1("Delphi Exception at address: %p\n", ExceptionRecord.ExceptionInformation[0]);
409 DPRINT1("Exception-Object: %p\n", ExceptionRecord.ExceptionInformation[1]);
410 DPRINT1("Exception text: %s\n", ExceptionRecord.ExceptionInformation[2]);
411 }
412
413 /* Raise the exception */
414 RtlRaiseException(&ExceptionRecord);
415 }
416
417 /* EOF */