3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "exceptions.h"
30 #include "threading/mutex.h"
31 #include "threading/mutex_auto_lock.h"
44 void sanity_check_fn(const char *assertion, const char *file,
45 unsigned int line, const char *function)
47 errorstream << std::endl << "In thread " << std::hex
48 << thr_get_current_thread_id() << ":" << std::endl;
49 errorstream << file << ":" << line << ": " << function
50 << ": An engine assumption '" << assertion << "' failed." << std::endl;
52 debug_stacks_print_to(errorstream);
57 void fatal_error_fn(const char *msg, const char *file,
58 unsigned int line, const char *function)
60 errorstream << std::endl << "In thread " << std::hex
61 << thr_get_current_thread_id() << ":" << std::endl;
62 errorstream << file << ":" << line << ": " << function
63 << ": A fatal error occured: " << msg << std::endl;
65 debug_stacks_print_to(errorstream);
76 DebugStack(threadid_t id);
77 void print(FILE *file, bool everything);
78 void print(std::ostream &os, bool everything);
81 char stack[DEBUG_STACK_SIZE][DEBUG_STACK_TEXT_SIZE];
82 int stack_i; // Points to the lowest empty position
83 int stack_max_i; // Highest i that was seen
86 DebugStack::DebugStack(threadid_t id)
91 memset(stack, 0, DEBUG_STACK_SIZE*DEBUG_STACK_TEXT_SIZE);
94 void DebugStack::print(FILE *file, bool everything)
96 std::ostringstream os;
98 fprintf(file, "DEBUG STACK FOR THREAD %s:\n",
101 for(int i=0; i<stack_max_i; i++)
103 if(i == stack_i && everything == false)
107 fprintf(file, "#%d %s\n", i, stack[i]);
109 fprintf(file, "(Leftover data: #%d %s)\n", i, stack[i]);
112 if(stack_i == DEBUG_STACK_SIZE)
113 fprintf(file, "Probably overflown.\n");
116 void DebugStack::print(std::ostream &os, bool everything)
118 os<<"DEBUG STACK FOR THREAD "<<threadid<<": "<<std::endl;
120 for(int i=0; i<stack_max_i; i++)
122 if(i == stack_i && everything == false)
126 os<<"#"<<i<<" "<<stack[i]<<std::endl;
128 os<<"(Leftover data: #"<<i<<" "<<stack[i]<<")"<<std::endl;
131 if(stack_i == DEBUG_STACK_SIZE)
132 os<<"Probably overflown."<<std::endl;
135 // Note: Using pthread_t (that is, threadid_t on POSIX platforms) as the key to
136 // a std::map is naughty. Formally, a pthread_t may only be compared using
137 // pthread_equal() - pthread_t lacks the well-ordered property needed for
138 // comparisons in binary searches. This should be fixed at some point by
139 // defining a custom comparator with an arbitrary but stable ordering of
140 // pthread_t, but it isn't too important since none of our supported platforms
141 // implement pthread_t as a non-ordinal type.
142 std::map<threadid_t, DebugStack*> g_debug_stacks;
143 Mutex g_debug_stacks_mutex;
145 void debug_stacks_init()
149 void debug_stacks_print_to(std::ostream &os)
151 MutexAutoLock lock(g_debug_stacks_mutex);
153 os<<"Debug stacks:"<<std::endl;
155 for(std::map<threadid_t, DebugStack*>::iterator
156 i = g_debug_stacks.begin();
157 i != g_debug_stacks.end(); ++i)
159 i->second->print(os, false);
163 void debug_stacks_print()
165 debug_stacks_print_to(errorstream);
168 DebugStacker::DebugStacker(const char *text)
170 threadid_t threadid = thr_get_current_thread_id();
172 MutexAutoLock lock(g_debug_stacks_mutex);
174 std::map<threadid_t, DebugStack*>::iterator n;
175 n = g_debug_stacks.find(threadid);
176 if(n != g_debug_stacks.end())
182 /*DEBUGPRINT("Creating new debug stack for thread %x\n",
183 (unsigned int)threadid);*/
184 m_stack = new DebugStack(threadid);
185 g_debug_stacks[threadid] = m_stack;
188 if(m_stack->stack_i >= DEBUG_STACK_SIZE)
194 m_overflowed = false;
196 snprintf(m_stack->stack[m_stack->stack_i],
197 DEBUG_STACK_TEXT_SIZE, "%s", text);
199 if(m_stack->stack_i > m_stack->stack_max_i)
200 m_stack->stack_max_i = m_stack->stack_i;
204 DebugStacker::~DebugStacker()
206 MutexAutoLock lock(g_debug_stacks_mutex);
208 if(m_overflowed == true)
213 if(m_stack->stack_i == 0)
215 threadid_t threadid = m_stack->threadid;
216 /*DEBUGPRINT("Deleting debug stack for thread %x\n",
217 (unsigned int)threadid);*/
219 g_debug_stacks.erase(threadid);
225 const char *Win32ExceptionCodeToString(DWORD exception_code)
227 switch (exception_code) {
228 case EXCEPTION_ACCESS_VIOLATION:
229 return "Access violation";
230 case EXCEPTION_DATATYPE_MISALIGNMENT:
231 return "Misaligned data access";
232 case EXCEPTION_BREAKPOINT:
233 return "Breakpoint reached";
234 case EXCEPTION_SINGLE_STEP:
235 return "Single debug step";
236 case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
237 return "Array access out of bounds";
238 case EXCEPTION_FLT_DENORMAL_OPERAND:
239 return "Denormal floating point operand";
240 case EXCEPTION_FLT_DIVIDE_BY_ZERO:
241 return "Floating point division by zero";
242 case EXCEPTION_FLT_INEXACT_RESULT:
243 return "Inaccurate floating point result";
244 case EXCEPTION_FLT_INVALID_OPERATION:
245 return "Invalid floating point operation";
246 case EXCEPTION_FLT_OVERFLOW:
247 return "Floating point exponent overflow";
248 case EXCEPTION_FLT_STACK_CHECK:
249 return "Floating point stack overflow or underflow";
250 case EXCEPTION_FLT_UNDERFLOW:
251 return "Floating point exponent underflow";
252 case EXCEPTION_INT_DIVIDE_BY_ZERO:
253 return "Integer division by zero";
254 case EXCEPTION_INT_OVERFLOW:
255 return "Integer overflow";
256 case EXCEPTION_PRIV_INSTRUCTION:
257 return "Privileged instruction executed";
258 case EXCEPTION_IN_PAGE_ERROR:
259 return "Could not access or load page";
260 case EXCEPTION_ILLEGAL_INSTRUCTION:
261 return "Illegal instruction encountered";
262 case EXCEPTION_NONCONTINUABLE_EXCEPTION:
263 return "Attempted to continue after fatal exception";
264 case EXCEPTION_STACK_OVERFLOW:
265 return "Stack overflow";
266 case EXCEPTION_INVALID_DISPOSITION:
267 return "Invalid disposition returned to the exception dispatcher";
268 case EXCEPTION_GUARD_PAGE:
269 return "Attempted guard page access";
270 case EXCEPTION_INVALID_HANDLE:
271 return "Invalid handle";
274 return "Unknown exception";
277 long WINAPI Win32ExceptionHandler(struct _EXCEPTION_POINTERS *pExceptInfo)
280 MINIDUMP_EXCEPTION_INFORMATION mdei;
281 MINIDUMP_USER_STREAM_INFORMATION mdusi;
282 MINIDUMP_USER_STREAM mdus;
283 bool minidump_created = false;
285 std::string dumpfile = porting::path_user + DIR_DELIM PROJECT_NAME ".dmp";
287 std::string version_str(PROJECT_NAME " ");
288 version_str += g_version_hash;
290 HANDLE hFile = CreateFileA(dumpfile.c_str(), GENERIC_WRITE,
291 FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
292 if (hFile == INVALID_HANDLE_VALUE)
293 goto minidump_failed;
295 if (SetEndOfFile(hFile) == FALSE)
296 goto minidump_failed;
298 mdei.ClientPointers = NULL;
299 mdei.ExceptionPointers = pExceptInfo;
300 mdei.ThreadId = GetCurrentThreadId();
302 mdus.Type = CommentStreamA;
303 mdus.BufferSize = version_str.size();
304 mdus.Buffer = (PVOID)version_str.c_str();
306 mdusi.UserStreamArray = &mdus;
307 mdusi.UserStreamCount = 1;
309 if (MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile,
310 MiniDumpNormal, &mdei, &mdusi, NULL) == FALSE)
311 goto minidump_failed;
313 minidump_created = true;
319 DWORD excode = pExceptInfo->ExceptionRecord->ExceptionCode;
320 _snprintf(buf, sizeof(buf),
321 " >> === FATAL ERROR ===\n"
322 " >> %s (Exception 0x%08X) at 0x%p\n",
323 Win32ExceptionCodeToString(excode), excode,
324 pExceptInfo->ExceptionRecord->ExceptionAddress);
327 if (minidump_created)
328 dstream << " >> Saved dump to " << dumpfile << std::endl;
330 dstream << " >> Failed to save dump" << std::endl;
332 return EXCEPTION_EXECUTE_HANDLER;
337 void debug_set_exception_handler()
340 SetUnhandledExceptionFilter(Win32ExceptionHandler);