File: Logger.cpp

package info (click to toggle)
spring 103.0%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,720 kB
  • ctags: 63,685
  • sloc: cpp: 368,283; ansic: 33,988; python: 12,417; java: 12,203; awk: 5,879; sh: 1,846; xml: 655; perl: 405; php: 211; objc: 194; makefile: 77; sed: 2
file content (279 lines) | stat: -rw-r--r-- 7,254 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */


#ifdef SYNCDEBUG

#include <assert.h>
#include <errno.h>
#include <stdarg.h>
#include <string.h>
#include <sstream>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "Logger.h"
#include "System/Util.h"
#include "System/SafeCStrings.h"

#ifdef _MSC_VER
#include <Windows.h>
#include <imagehlp.h>
#include "System/Platform/CrashHandler.h"
#endif

#ifdef WIN32
// msvcrt doesn't have thread safe ctime_r
# define ctime_r(tm, buf) ctime(tm)
#endif


extern "C" void get_executable_name(char *output, int size);


/**
 * @brief name of the addr2line binary
 */
#define ADDR2LINE "addr2line"


/**
 * @brief name of the c++filt binary
 *
 * Only used on MinGW to work around an addr2line bug.
 */
#define CPPFILT "c++filt"


/**
 * @brief log function
 *
 * Write a printf-style formatted message to the temporary logfile buffer.
 * (which is later to be filtered through addr2line)
 *
 * The filtering is done by taking everything between { and } as being a
 * hexadecimal address into the executable. This address is literally passed
 * to addr2line, which converts it to a function, filename & line number.
 * The "{...}" string is then fully replaced by "function [filename:lineno]".
 */
void CLogger::AddLine(const char* fmt, ...)
{
	boost::recursive_mutex::scoped_lock scoped_lock(logmutex);
	char buf[500]; // same size as buffer in infolog

	va_list argp;
	va_start(argp, fmt);
	VSNPRINTF(buf, sizeof(buf), fmt, argp);
	buf[sizeof(buf) - 1] = 0;
	va_end(argp);

	buffer.push_back(buf);

	// Buffer size is 2900 because that makes about the largest commandline
	// we can pass to addr2line on systems limiting the commandline to 32k
	// characters. (11 bytes per hexadecimal address gives 2900*11 = 31900)
	if (buffer.size() >= 2900)
		FlushBuffer();
}


/**
 * @brief close one logging session
 *
 * Writes the buffered data to file after filtering it through addr2line.
 */
void CLogger::CloseSession()
{
	boost::recursive_mutex::scoped_lock scoped_lock(logmutex);

	if (logfile || !buffer.empty()) {
		FlushBuffer();
		fclose(logfile);
		logfile = NULL;
	}
}


/**
 * @brief flushes the buffer
 *
 * This is the actual worker function. It opens the log file if it wasn't yet
 * open, composes the addr2line commandline, pipes the buffer through it and
 * writes the output of that - after some formatting - to the real logfile.
 */
void CLogger::FlushBuffer()
{
	boost::recursive_mutex::scoped_lock scoped_lock(logmutex);

	char buf1[4096], buf2[4096];
	char* nl;

	// Open logfile if it's not open.

	if (!logfile) {
		assert(filename);
		if (!(logfile = fopen(filename, "a")))
			return;

		time_t t;
		time(&t);
		char* ct = ctime_r(&t, buf1);
		if ((nl = strchr(ct, '\n'))) *nl = 0;
		fprintf(logfile, "\n===> %s <===\n", ct);
	}

	// Get executable name if we didn't have it yet.

	if (exename.empty()) {
		get_executable_name(buf1, sizeof(buf1));
		int len = strlen(buf1);
		strncpy(buf2, buf1, sizeof(buf2));
		buf2[sizeof(buf2)-1] = '\0'; // make sure the string is terminated
		if (len > 4 && buf2[len-4] == '.')
			buf2[len-4] = 0;
		// NOTE STRCAT_T: will always terminate destination with '/0'
		//   2nd param: destination buffer size
		STRCAT_T(buf2, sizeof(buf2), ".dbg");

		fprintf(logfile, "trying debug symbols file: '%s'\n", buf2);

		struct stat tmp;
		if (stat(buf2, &tmp) == 0) {
			exename = buf2;
		} else {
			exename = buf1;
		}

		if (exename.empty())
			return;
		fprintf(logfile, "executable name: '%s'\n", exename.c_str());
	}

#ifdef _MSC_VER
	for (auto it = buffer.begin(); it != buffer.end(); ++it) {
		const int open = it->find('{');
		const int close = it->find('}', open + 1);
		std::stringstream ss;
		if (open != std::string::npos && close != std::string::npos) {
			void* p;
			ss << std::hex << it->substr(open + 1, close - open - 1) << std::dec;
			ss >> p;

			const int SYMLENGTH = 4096;
			char symbuf[sizeof(SYMBOL_INFO) + SYMLENGTH];
			PSYMBOL_INFO pSym = reinterpret_cast<SYMBOL_INFO*>(symbuf);
			pSym->SizeOfStruct = sizeof(SYMBOL_INFO);
			pSym->MaxNameLen = SYMLENGTH;

			if (CrashHandler::InitImageHlpDll() &&
				SymFromAddr(GetCurrentProcess(), (DWORD64)p, nullptr, pSym)) {

				IMAGEHLP_LINE64 line;
				DWORD displacement;
				line.SizeOfStruct = sizeof(line);
				SymGetLineFromAddr64(GetCurrentProcess(), (DWORD64) p, &displacement, &line);

				fprintf(logfile, "%s%s:%d [%p]%s\n", it->substr(0, open).c_str(), pSym->Name, line.LineNumber, p, it->substr(close + 1).c_str());
			}
		} else {
			fprintf(logfile, "%s\n", it->c_str());
		}
	}
#else
	// Compose addr2line command.

	std::stringstream command;
	std::vector<std::string>::iterator it;
	bool runTheCommand = false;

	command << ADDR2LINE << " \"--exe=" << exename << "\" --functions --demangle --inline";

	for (it = buffer.begin(); it != buffer.end(); ++it) {
		const int open = it->find('{');
		const int close = it->find('}', open + 1);
		if (open != std::string::npos && close != std::string::npos) {
			command << " " << it->substr(open + 1, close - open - 1);
			runTheCommand = true;
		}
	}

	if (runTheCommand) {
		// We got some addresses, so run the addr2line command.
		// (This is usually the branch taken by the host)

		fprintf(logfile, "addr2line command : '%s'\n", command.str().c_str());

		// Open pipe to the addr2line command.

		FILE* p = popen(command.str().c_str(), "r");

		if (!p) {
			fprintf(logfile, "  %s\n", strerror(errno));
			runTheCommand = false;
		} else {
			// Pipe the buffer through the addr2line command.
			for (it = buffer.begin(); it != buffer.end(); ++it) {
				const int open = it->find('{');
				const int close = it->find('}', open + 1);
				if (open != std::string::npos && close != std::string::npos) {
					fgets(buf1, sizeof(buf1), p);
					fgets(buf2, sizeof(buf2), p);
					CppFilt(buf1, sizeof(buf1));
					if ((nl = strchr(buf1, '\n'))) *nl = 0;
					if ((nl = strchr(buf2, '\n'))) *nl = 0;
					fprintf(logfile, "%s%s [%s]%s\n", it->substr(0, open).c_str(), buf1, buf2, it->substr(close + 1).c_str());
				} else {
					fprintf(logfile, "%s\n", it->c_str());
				}
			}

			// Close pipe & clear buffer.
			pclose(p);
		}
	}

	if (!runTheCommand) {
		// Just dump the buffer to the file.
		// (this is usually the branch taken by the clients)
		for (it = buffer.begin(); it != buffer.end(); ++it) {
			fprintf(logfile, "%s\n", it->c_str());
		}
	}
#endif

	buffer.clear();
}


/**
 * @brief demangles sym
 *
 * On MinGW, checks if sym needs demangling by some very simple heuristic and
 * filters it through c++filt if it needs to be demangled.
 *
 * It's a workaround for MinGW GNU addr2line 2.15.91, which somehow strips
 * underscores from the symbol before trying to demangle them, resulting
 * no demangling ever happening.
 */
void CLogger::CppFilt(char* sym, int size)
{
#ifdef __MINGW32__

	// The heuristic :-)
	if (sym[0] != 'Z')
		return;

	// Compose command & add the missing underscore
	std::stringstream command;
	command << CPPFILT << " \"_" << sym << '"';

	// Do the filtering. Silently ignore any errors.
	FILE* p = popen(command.str().c_str(), "r");
	if (p) {
		fgets(sym, size, p);
		pclose(p);
	}

#endif // __MINGW32__
}

#endif // SYNCDEBUG