]> git.lizzy.rs Git - dragonfireclient.git/blob - src/debug.cpp
Fix C++11 compatibility
[dragonfireclient.git] / src / debug.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20
21 #include "porting.h"
22 #include "debug.h"
23 #include "exceptions.h"
24 #include "threads.h"
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <cstring>
28 #include <map>
29 #include <sstream>
30 #include "threading/mutex.h"
31 #include "threading/mutex_auto_lock.h"
32 #include "config.h"
33
34 #ifdef _MSC_VER
35         #include <dbghelp.h>
36         #include "version.h"
37         #include "filesys.h"
38 #endif
39
40 /*
41         Assert
42 */
43
44 void sanity_check_fn(const char *assertion, const char *file,
45                 unsigned int line, const char *function)
46 {
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;
51
52         debug_stacks_print_to(errorstream);
53
54         abort();
55 }
56
57 void fatal_error_fn(const char *msg, const char *file,
58                 unsigned int line, const char *function)
59 {
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;
64
65         debug_stacks_print_to(errorstream);
66
67         abort();
68 }
69
70 /*
71         DebugStack
72 */
73
74 struct DebugStack
75 {
76         DebugStack(threadid_t id);
77         void print(FILE *file, bool everything);
78         void print(std::ostream &os, bool everything);
79
80         threadid_t threadid;
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
84 };
85
86 DebugStack::DebugStack(threadid_t id)
87 {
88         threadid = id;
89         stack_i = 0;
90         stack_max_i = 0;
91         memset(stack, 0, DEBUG_STACK_SIZE*DEBUG_STACK_TEXT_SIZE);
92 }
93
94 void DebugStack::print(FILE *file, bool everything)
95 {
96         std::ostringstream os;
97         os << threadid;
98         fprintf(file, "DEBUG STACK FOR THREAD %s:\n",
99                 os.str().c_str());
100
101         for(int i=0; i<stack_max_i; i++)
102         {
103                 if(i == stack_i && everything == false)
104                         break;
105
106                 if(i < stack_i)
107                         fprintf(file, "#%d  %s\n", i, stack[i]);
108                 else
109                         fprintf(file, "(Leftover data: #%d  %s)\n", i, stack[i]);
110         }
111
112         if(stack_i == DEBUG_STACK_SIZE)
113                 fprintf(file, "Probably overflown.\n");
114 }
115
116 void DebugStack::print(std::ostream &os, bool everything)
117 {
118         os<<"DEBUG STACK FOR THREAD "<<threadid<<": "<<std::endl;
119
120         for(int i=0; i<stack_max_i; i++)
121         {
122                 if(i == stack_i && everything == false)
123                         break;
124
125                 if(i < stack_i)
126                         os<<"#"<<i<<"  "<<stack[i]<<std::endl;
127                 else
128                         os<<"(Leftover data: #"<<i<<"  "<<stack[i]<<")"<<std::endl;
129         }
130
131         if(stack_i == DEBUG_STACK_SIZE)
132                 os<<"Probably overflown."<<std::endl;
133 }
134
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;
144
145 void debug_stacks_init()
146 {
147 }
148
149 void debug_stacks_print_to(std::ostream &os)
150 {
151         MutexAutoLock lock(g_debug_stacks_mutex);
152
153         os<<"Debug stacks:"<<std::endl;
154
155         for(std::map<threadid_t, DebugStack*>::iterator
156                         i = g_debug_stacks.begin();
157                         i != g_debug_stacks.end(); ++i)
158         {
159                 i->second->print(os, false);
160         }
161 }
162
163 void debug_stacks_print()
164 {
165         debug_stacks_print_to(errorstream);
166 }
167
168 DebugStacker::DebugStacker(const char *text)
169 {
170         threadid_t threadid = thr_get_current_thread_id();
171
172         MutexAutoLock lock(g_debug_stacks_mutex);
173
174         std::map<threadid_t, DebugStack*>::iterator n;
175         n = g_debug_stacks.find(threadid);
176         if(n != g_debug_stacks.end())
177         {
178                 m_stack = n->second;
179         }
180         else
181         {
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;
186         }
187
188         if(m_stack->stack_i >= DEBUG_STACK_SIZE)
189         {
190                 m_overflowed = true;
191         }
192         else
193         {
194                 m_overflowed = false;
195
196                 snprintf(m_stack->stack[m_stack->stack_i],
197                                 DEBUG_STACK_TEXT_SIZE, "%s", text);
198                 m_stack->stack_i++;
199                 if(m_stack->stack_i > m_stack->stack_max_i)
200                         m_stack->stack_max_i = m_stack->stack_i;
201         }
202 }
203
204 DebugStacker::~DebugStacker()
205 {
206         MutexAutoLock lock(g_debug_stacks_mutex);
207
208         if(m_overflowed == true)
209                 return;
210
211         m_stack->stack_i--;
212
213         if(m_stack->stack_i == 0)
214         {
215                 threadid_t threadid = m_stack->threadid;
216                 /*DEBUGPRINT("Deleting debug stack for thread %x\n",
217                                 (unsigned int)threadid);*/
218                 delete m_stack;
219                 g_debug_stacks.erase(threadid);
220         }
221 }
222
223 #ifdef _MSC_VER
224
225 const char *Win32ExceptionCodeToString(DWORD exception_code)
226 {
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";
272         }
273
274         return "Unknown exception";
275 }
276
277 long WINAPI Win32ExceptionHandler(struct _EXCEPTION_POINTERS *pExceptInfo)
278 {
279         char buf[512];
280         MINIDUMP_EXCEPTION_INFORMATION mdei;
281         MINIDUMP_USER_STREAM_INFORMATION mdusi;
282         MINIDUMP_USER_STREAM mdus;
283         bool minidump_created = false;
284
285         std::string dumpfile = porting::path_user + DIR_DELIM PROJECT_NAME ".dmp";
286
287         std::string version_str(PROJECT_NAME " ");
288         version_str += g_version_hash;
289
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;
294
295         if (SetEndOfFile(hFile) == FALSE)
296                 goto minidump_failed;
297
298         mdei.ClientPointers        = NULL;
299         mdei.ExceptionPointers = pExceptInfo;
300         mdei.ThreadId              = GetCurrentThreadId();
301
302         mdus.Type       = CommentStreamA;
303         mdus.BufferSize = version_str.size();
304         mdus.Buffer     = (PVOID)version_str.c_str();
305
306         mdusi.UserStreamArray = &mdus;
307         mdusi.UserStreamCount = 1;
308
309         if (MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile,
310                         MiniDumpNormal, &mdei, &mdusi, NULL) == FALSE)
311                 goto minidump_failed;
312
313         minidump_created = true;
314
315 minidump_failed:
316
317         CloseHandle(hFile);
318
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);
325         dstream << buf;
326
327         if (minidump_created)
328                 dstream << " >> Saved dump to " << dumpfile << std::endl;
329         else
330                 dstream << " >> Failed to save dump" << std::endl;
331
332         return EXCEPTION_EXECUTE_HANDLER;
333 }
334
335 #endif
336
337 void debug_set_exception_handler()
338 {
339 #ifdef _MSC_VER
340         SetUnhandledExceptionFilter(Win32ExceptionHandler);
341 #endif
342 }
343