OpenTTD Source: src/debug.cpp Source File

OpenTTD Source 12.2

debug.cpp
Go to the documentation of this file.
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
10 #include "stdafx.h"
11 #include <stdarg.h>
12 #include "console_func.h"
13 #include "debug.h"
14 #include "string_func.h"
15 #include "fileio_func.h"
16 #include "settings_type.h"
17 #include <mutex>
18
19 #if defined(_WIN32)
20 #include "os/windows/win32.h"
21 #endif
22
23 #include "walltime_func.h"
24
25 #include "network/network_admin.h"
26 SOCKET _debug_socket = INVALID_SOCKET;
27
28 #include "safeguards.h"
29
31 struct QueuedDebugItem {
32 std::string level;
33 std::string message;
34 };
35 std::atomic<bool> _debug_remote_console;
36 std::mutex _debug_remote_console_mutex;
37 std::vector<QueuedDebugItem> _debug_remote_console_queue;
38 std::vector<QueuedDebugItem> _debug_remote_console_queue_spare;
39
40 int _debug_driver_level;
41 int _debug_grf_level;
42 int _debug_map_level;
43 int _debug_misc_level;
44 int _debug_net_level;
45 int _debug_sprite_level;
46 int _debug_oldloader_level;
47 int _debug_npf_level;
48 int _debug_yapf_level;
49 int _debug_freetype_level;
50 int _debug_script_level;
51 int _debug_sl_level;
52 int _debug_gamelog_level;
53 int _debug_desync_level;
54 int _debug_console_level;
55 #ifdef RANDOM_DEBUG
56 int _debug_random_level;
57 #endif
58
59 struct DebugLevel {
60 const char *name;
61 int *level;
62 };
63
64 #define DEBUG_LEVEL(x) { #x, &_debug_##x##_level }
65 static const DebugLevel debug_level[] = {
66 DEBUG_LEVEL(driver),
67 DEBUG_LEVEL(grf),
68 DEBUG_LEVEL(map),
69 DEBUG_LEVEL(misc),
70 DEBUG_LEVEL(net),
71 DEBUG_LEVEL(sprite),
72 DEBUG_LEVEL(oldloader),
73 DEBUG_LEVEL(npf),
74 DEBUG_LEVEL(yapf),
75 DEBUG_LEVEL(freetype),
76 DEBUG_LEVEL(script),
77 DEBUG_LEVEL(sl),
78 DEBUG_LEVEL(gamelog),
79 DEBUG_LEVEL(desync),
80 DEBUG_LEVEL(console),
81 #ifdef RANDOM_DEBUG
82 DEBUG_LEVEL(random),
83 #endif
84 };
85 #undef DEBUG_LEVEL
86
93 char *DumpDebugFacilityNames(char *buf, char *last)
94 {
95 size_t length = 0;
96 for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
97 if (length == 0) {
98 buf = strecpy(buf, "List of debug facility names:\n", last);
99 } else {
100 buf = strecpy(buf, ", ", last);
101 length += 2;
102 }
103 buf = strecpy(buf, i->name, last);
104 length += strlen(i->name);
105 }
106 if (length > 0) {
107 buf = strecpy(buf, "\n\n", last);
108 }
109 return buf;
110 }
111
117 void DebugPrint(const char *level, const std::string &message)
118 {
119 if (_debug_socket != INVALID_SOCKET) {
120 std::string msg = fmt::format("{}dbg: [{}] {}\n", GetLogPrefix(), level, message);
121
122 /* Prevent sending a message concurrently, as that might cause interleaved messages. */
123 static std::mutex _debug_socket_mutex;
124 std::lock_guard<std::mutex> lock(_debug_socket_mutex);
125
126 /* Sending out an error when this fails would be nice, however... the error
127 * would have to be send over this failing socket which won't work. */
128 send(_debug_socket, msg.c_str(), (int)msg.size(), 0);
129 return;
130 }
131 if (strcmp(level, "desync") == 0) {
132 static FILE *f = FioFOpenFile("commands-out.log", "wb", AUTOSAVE_DIR);
133 if (f == nullptr) return;
134
135 fprintf(f, "%s%s\n", GetLogPrefix(), message.c_str());
136 fflush(f);
137 #ifdef RANDOM_DEBUG
138 } else if (strcmp(level, "random") == 0) {
139 static FILE *f = FioFOpenFile("random-out.log", "wb", AUTOSAVE_DIR);
140 if (f == nullptr) return;
141
142 fprintf(f, "%s\n", message.c_str());
143 fflush(f);
144 #endif
145 } else {
146 std::string msg = fmt::format("{}dbg: [{}] {}\n", GetLogPrefix(), level, message);
147 fputs(msg.c_str(), stderr);
148
149 if (_debug_remote_console.load()) {
150 /* Only add to the queue when there is at least one consumer of the data. */
151 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
152 _debug_remote_console_queue.push_back({ level, message });
153 }
154 }
155 }
156
163 void SetDebugString(const char *s)
164 {
165 int v;
166 char *end;
167 const char *t;
168
169 /* global debugging level? */
170 if (*s >= '0' && *s <= '9') {
171 const DebugLevel *i;
172
173 v = strtoul(s, &end, 0);
174 s = end;
175
176 for (i = debug_level; i != endof(debug_level); ++i) *i->level = v;
177 }
178
179 /* individual levels */
180 for (;;) {
181 const DebugLevel *i;
182 int *p;
183
184 /* skip delimiters */
185 while (*s == ' ' || *s == ',' || *s == '\t') s++;
186 if (*s == '\0') break;
187
188 t = s;
189 while (*s >= 'a' && *s <= 'z') s++;
190
191 /* check debugging levels */
192 p = nullptr;
193 for (i = debug_level; i != endof(debug_level); ++i) {
194 if (s == t + strlen(i->name) && strncmp(t, i->name, s - t) == 0) {
195 p = i->level;
196 break;
197 }
198 }
199
200 if (*s == '=') s++;
201 v = strtoul(s, &end, 0);
202 s = end;
203 if (p != nullptr) {
204 *p = v;
205 } else {
206 ShowInfoF("Unknown debug level '%.*s'", (int)(s - t), t);
207 return;
208 }
209 }
210 }
211
217 const char *GetDebugString()
218 {
219 const DebugLevel *i;
220 static char dbgstr[150];
221 char dbgval[20];
222
223 memset(dbgstr, 0, sizeof(dbgstr));
224 i = debug_level;
225 seprintf(dbgstr, lastof(dbgstr), "%s=%d", i->name, *i->level);
226
227 for (i++; i != endof(debug_level); i++) {
228 seprintf(dbgval, lastof(dbgval), ", %s=%d", i->name, *i->level);
229 strecat(dbgstr, dbgval, lastof(dbgstr));
230 }
231
232 return dbgstr;
233 }
234
240 const char *GetLogPrefix()
241 {
242 static char _log_prefix[24];
243 if (_settings_client.gui.show_date_in_logs) {
244 LocalTime::Format(_log_prefix, lastof(_log_prefix), "[%Y-%m-%d %H:%M:%S] ");
245 } else {
246 *_log_prefix = '\0';
247 }
248 return _log_prefix;
249 }
250
258 void DebugSendRemoteMessages()
259 {
260 if (!_debug_remote_console.load()) return;
261
262 {
263 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
264 std::swap(_debug_remote_console_queue, _debug_remote_console_queue_spare);
265 }
266
267 for (auto &item : _debug_remote_console_queue_spare) {
268 NetworkAdminConsole(item.level, item.message);
269 if (_settings_client.gui.developer >= 2) IConsolePrint(CC_DEBUG, "dbg: [{}] {}", item.level, item.message);
270 }
271
272 _debug_remote_console_queue_spare.clear();
273 }
274
282 void DebugReconsiderSendRemoteMessages()
283 {
284 bool enable = _settings_client.gui.developer >= 2;
285
286 for (ServerNetworkAdminSocketHandler *as : ServerNetworkAdminSocketHandler::IterateActive()) {
287 if (as->update_frequency[ADMIN_UPDATE_CONSOLE] & ADMIN_FREQUENCY_AUTOMATIC) {
288 enable = true;
289 break;
290 }
291 }
292
293 _debug_remote_console.store(enable);
294 }
SetDebugString
void SetDebugString(const char *s)
Set debugging levels by parsing the text in s.
Definition: debug.cpp:163
_debug_remote_console
std::atomic< bool > _debug_remote_console
Whether we need to send data to either NetworkAdminConsole or IConsolePrint.
Definition: debug.cpp:35
win32.h
lock
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:34
ADMIN_UPDATE_CONSOLE
@ ADMIN_UPDATE_CONSOLE
The admin would like to have console messages.
Definition: tcp_admin.h:82
fileio_func.h
ServerNetworkAdminSocketHandler::IterateActive
static Pool::IterateWrapperFiltered< ServerNetworkAdminSocketHandler, ServerNetworkAdminSocketHandlerFilter > IterateActive(size_t from=0)
Returns an iterable ensemble of all active admin sockets.
Definition: network_admin.h:96
AUTOSAVE_DIR
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Definition: fileio_type.h:111
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:52
NetworkAdminConsole
void NetworkAdminConsole(const std::string_view origin, const std::string_view string)
Send console to the admin network (if they did opt in for the respective update).
Definition: network_admin.cpp:953
QueuedDebugItem::level
std::string level
The used debug level.
Definition: debug.cpp:32
GUISettings::show_date_in_logs
bool show_date_in_logs
whether to show dates in console logs
Definition: settings_type.h:187
QueuedDebugItem::message
std::string message
The actual formatted message.
Definition: debug.cpp:33
_debug_remote_console_queue_spare
std::vector< QueuedDebugItem > _debug_remote_console_queue_spare
Spare queue to swap with _debug_remote_console_queue.
Definition: debug.cpp:38
DumpDebugFacilityNames
char * DumpDebugFacilityNames(char *buf, char *last)
Dump the available debug facility names in the help text.
Definition: debug.cpp:93
walltime_func.h
GetLogPrefix
const char * GetLogPrefix()
Get the prefix for logs; if show_date_in_logs is enabled it returns the date, otherwise it returns no...
Definition: debug.cpp:240
FioFOpenFile
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:245
safeguards.h
CC_DEBUG
static const TextColour CC_DEBUG
Colour for debug output.
Definition: console_type.h:28
GUISettings::developer
uint8 developer
print non-fatal warnings in console (>= 1), copy debug output to console (== 2)
Definition: settings_type.h:186
Time::Format
static size_t Format(char *buffer, const char *last, const char *format) NOACCESS(2) WARN_TIME_FORMAT(3)
Format the current time with the given strftime format specifiers.
Definition: walltime_func.h:58
settings_type.h
stdafx.h
string_func.h
_debug_remote_console_queue
std::vector< QueuedDebugItem > _debug_remote_console_queue
Queue for debug messages to be passed to NetworkAdminConsole or IConsolePrint.
Definition: debug.cpp:37
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:386
GetDebugString
const char * GetDebugString()
Print out the current debug-level.
Definition: debug.cpp:217
ServerNetworkAdminSocketHandler
Class for handling the server side of the game connection.
Definition: network_admin.h:25
DebugPrint
void DebugPrint(const char *level, const std::string &message)
Internal function for outputting the debug line.
Definition: debug.cpp:117
ADMIN_FREQUENCY_AUTOMATIC
@ ADMIN_FREQUENCY_AUTOMATIC
The admin gets information about this when it changes.
Definition: tcp_admin.h:97
ShowInfoF
void CDECL ShowInfoF(const char *str,...)
Shows some information on the console/a popup box depending on the OS.
Definition: openttd.cpp:154
DebugSendRemoteMessages
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
Definition: debug.cpp:258
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:535
DebugLevel
Definition: debug.cpp:59
_debug_remote_console_mutex
std::mutex _debug_remote_console_mutex
Mutex to guard the queue of debug messages for either NetworkAdminConsole or IConsolePrint.
Definition: debug.cpp:36
network_admin.h
console_func.h
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:112
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:84
QueuedDebugItem
Element in the queue of debug messages that have to be passed to either NetworkAdminConsole or IConso...
Definition: debug.cpp:31
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:394
DebugReconsiderSendRemoteMessages
void DebugReconsiderSendRemoteMessages()
Reconsider whether we need to send debug messages to either NetworkAdminConsole or IConsolePrint.
Definition: debug.cpp:282
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:594
debug.h
IConsolePrint
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console.cpp:94