1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
8 /** @file crashlog_unix.cpp Unix crash log handler */
9 
10 #include "../../stdafx.h"
11 #include "../../crashlog.h"
12 #include "../../string_func.h"
13 #include "../../gamelog.h"
14 #include "../../saveload/saveload.h"
15 
16 #include <errno.h>
17 #include <signal.h>
18 #include <sys/utsname.h>
19 
20 #if defined(__GLIBC__)
21 /* Execinfo (and thus making stacktraces) is a GNU extension */
22 #	include <execinfo.h>
23 #elif defined(SUNOS)
24 #	include <ucontext.h>
25 #	include <dlfcn.h>
26 #endif
27 
28 #if defined(__NetBSD__)
29 #include <unistd.h>
30 #endif
31 
32 #include "../../safeguards.h"
33 
34 /**
35  * Unix implementation for the crash logger.
36  */
37 class CrashLogUnix : public CrashLog {
38 	/** Signal that has been thrown. */
39 	int signum;
40 
LogOSVersion(char * buffer,const char * last) const41 	char *LogOSVersion(char *buffer, const char *last) const override
42 	{
43 		struct utsname name;
44 		if (uname(&name) < 0) {
45 			return buffer + seprintf(buffer, last, "Could not get OS version: %s\n", strerror(errno));
46 		}
47 
48 		return buffer + seprintf(buffer, last,
49 				"Operating system:\n"
50 				" Name:     %s\n"
51 				" Release:  %s\n"
52 				" Version:  %s\n"
53 				" Machine:  %s\n",
54 				name.sysname,
55 				name.release,
56 				name.version,
57 				name.machine
58 		);
59 	}
60 
LogError(char * buffer,const char * last,const char * message) const61 	char *LogError(char *buffer, const char *last, const char *message) const override
62 	{
63 		return buffer + seprintf(buffer, last,
64 				"Crash reason:\n"
65 				" Signal:  %s (%d)\n"
66 				" Message: %s\n\n",
67 				strsignal(this->signum),
68 				this->signum,
69 				message == nullptr ? "<none>" : message
70 		);
71 	}
72 
73 #if defined(SUNOS)
74 	/** Data needed while walking up the stack */
75 	struct StackWalkerParams {
76 		char **bufptr;    ///< Buffer
77 		const char *last; ///< End of buffer
78 		int counter;      ///< We are at counter-th stack level
79 	};
80 
81 	/**
82 	 * Callback used while walking up the stack.
83 	 * @param pc program counter
84 	 * @param sig 'active' signal (unused)
85 	 * @param params parameters
86 	 * @return always 0, continue walking up the stack
87 	 */
SunOSStackWalker(uintptr_t pc,int sig,void * params)88 	static int SunOSStackWalker(uintptr_t pc, int sig, void *params)
89 	{
90 		StackWalkerParams *wp = (StackWalkerParams *)params;
91 
92 		/* Resolve program counter to file and nearest symbol (if possible) */
93 		Dl_info dli;
94 		if (dladdr((void *)pc, &dli) != 0) {
95 			*wp->bufptr += seprintf(*wp->bufptr, wp->last, " [%02i] %s(%s+0x%x) [0x%x]\n",
96 					wp->counter, dli.dli_fname, dli.dli_sname, (int)((byte *)pc - (byte *)dli.dli_saddr), (uint)pc);
97 		} else {
98 			*wp->bufptr += seprintf(*wp->bufptr, wp->last, " [%02i] [0x%x]\n", wp->counter, (uint)pc);
99 		}
100 		wp->counter++;
101 
102 		return 0;
103 	}
104 #endif
105 
LogStacktrace(char * buffer,const char * last) const106 	char *LogStacktrace(char *buffer, const char *last) const override
107 	{
108 		buffer += seprintf(buffer, last, "Stacktrace:\n");
109 #if defined(__GLIBC__)
110 		void *trace[64];
111 		int trace_size = backtrace(trace, lengthof(trace));
112 
113 		char **messages = backtrace_symbols(trace, trace_size);
114 		for (int i = 0; i < trace_size; i++) {
115 			buffer += seprintf(buffer, last, " [%02i] %s\n", i, messages[i]);
116 		}
117 		free(messages);
118 #elif defined(SUNOS)
119 		ucontext_t uc;
120 		if (getcontext(&uc) != 0) {
121 			buffer += seprintf(buffer, last, " getcontext() failed\n\n");
122 			return buffer;
123 		}
124 
125 		StackWalkerParams wp = { &buffer, last, 0 };
126 		walkcontext(&uc, &CrashLogUnix::SunOSStackWalker, &wp);
127 #else
128 		buffer += seprintf(buffer, last, " Not supported.\n");
129 #endif
130 		return buffer + seprintf(buffer, last, "\n");
131 	}
132 public:
133 	/**
134 	 * A crash log is always generated by signal.
135 	 * @param signum the signal that was caused by the crash.
136 	 */
CrashLogUnix(int signum)137 	CrashLogUnix(int signum) :
138 		signum(signum)
139 	{
140 	}
141 };
142 
143 /** The signals we want our crash handler to handle. */
144 static const int _signals_to_handle[] = { SIGSEGV, SIGABRT, SIGFPE, SIGBUS, SIGILL };
145 
146 /**
147  * Entry point for the crash handler.
148  * @note Not static so it shows up in the backtrace.
149  * @param signum the signal that caused us to crash.
150  */
HandleCrash(int signum)151 static void CDECL HandleCrash(int signum)
152 {
153 	/* Disable all handling of signals by us, so we don't go into infinite loops. */
154 	for (const int *i = _signals_to_handle; i != endof(_signals_to_handle); i++) {
155 		signal(*i, SIG_DFL);
156 	}
157 
158 	if (GamelogTestEmergency()) {
159 		printf("A serious fault condition occurred in the game. The game will shut down.\n");
160 		printf("As you loaded an emergency savegame no crash information will be generated.\n");
161 		abort();
162 	}
163 
164 	if (SaveloadCrashWithMissingNewGRFs()) {
165 		printf("A serious fault condition occurred in the game. The game will shut down.\n");
166 		printf("As you loaded an savegame for which you do not have the required NewGRFs\n");
167 		printf("no crash information will be generated.\n");
168 		abort();
169 	}
170 
171 	CrashLogUnix log(signum);
172 	log.MakeCrashLog();
173 
174 	CrashLog::AfterCrashLogCleanup();
175 	abort();
176 }
177 
InitialiseCrashLog()178 /* static */ void CrashLog::InitialiseCrashLog()
179 {
180 	for (const int *i = _signals_to_handle; i != endof(_signals_to_handle); i++) {
181 		signal(*i, HandleCrash);
182 	}
183 }
184 
InitThread()185 /* static */ void CrashLog::InitThread()
186 {
187 }
188