OpenTTD Source  13.2.1
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 
32  std::string level;
33  std::string message;
34 };
35 std::atomic<bool> _debug_remote_console;
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_fontcache_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(fontcache),
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 
164 void SetDebugString(const char *s, void (*error_func)(const char *))
165 {
166  int v;
167  char *end;
168  const char *t;
169 
170  /* Store planned changes into map during parse */
171  std::map<const char *, int> new_levels;
172 
173  /* Global debugging level? */
174  if (*s >= '0' && *s <= '9') {
175  const DebugLevel *i;
176 
177  v = strtoul(s, &end, 0);
178  s = end;
179 
180  for (i = debug_level; i != endof(debug_level); ++i) {
181  new_levels[i->name] = v;
182  }
183  }
184 
185  /* Individual levels */
186  for (;;) {
187  /* skip delimiters */
188  while (*s == ' ' || *s == ',' || *s == '\t') s++;
189  if (*s == '\0') break;
190 
191  t = s;
192  while (*s >= 'a' && *s <= 'z') s++;
193 
194  /* check debugging levels */
195  const DebugLevel *found = nullptr;
196  for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
197  if (s == t + strlen(i->name) && strncmp(t, i->name, s - t) == 0) {
198  found = i;
199  break;
200  }
201  }
202 
203  if (*s == '=') s++;
204  v = strtoul(s, &end, 0);
205  s = end;
206  if (found != nullptr) {
207  new_levels[found->name] = v;
208  } else {
209  std::string error_string = fmt::format("Unknown debug level '{}'", std::string(t, s - t));
210  error_func(error_string.c_str());
211  return;
212  }
213  }
214 
215  /* Apply the changes after parse is successful */
216  for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
217  const auto &nl = new_levels.find(i->name);
218  if (nl != new_levels.end()) {
219  *i->level = nl->second;
220  }
221  }
222 }
223 
229 const char *GetDebugString()
230 {
231  const DebugLevel *i;
232  static char dbgstr[150];
233  char dbgval[20];
234 
235  memset(dbgstr, 0, sizeof(dbgstr));
236  i = debug_level;
237  seprintf(dbgstr, lastof(dbgstr), "%s=%d", i->name, *i->level);
238 
239  for (i++; i != endof(debug_level); i++) {
240  seprintf(dbgval, lastof(dbgval), ", %s=%d", i->name, *i->level);
241  strecat(dbgstr, dbgval, lastof(dbgstr));
242  }
243 
244  return dbgstr;
245 }
246 
252 const char *GetLogPrefix()
253 {
254  static char _log_prefix[24];
256  LocalTime::Format(_log_prefix, lastof(_log_prefix), "[%Y-%m-%d %H:%M:%S] ");
257  } else {
258  *_log_prefix = '\0';
259  }
260  return _log_prefix;
261 }
262 
271 {
272  if (!_debug_remote_console.load()) return;
273 
274  {
275  std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
277  }
278 
279  for (auto &item : _debug_remote_console_queue_spare) {
280  NetworkAdminConsole(item.level, item.message);
281  if (_settings_client.gui.developer >= 2) IConsolePrint(CC_DEBUG, "dbg: [{}] {}", item.level, item.message);
282  }
283 
285 }
286 
295 {
296  bool enable = _settings_client.gui.developer >= 2;
297 
299  if (as->update_frequency[ADMIN_UPDATE_CONSOLE] & ADMIN_FREQUENCY_AUTOMATIC) {
300  enable = true;
301  break;
302  }
303  }
304 
305  _debug_remote_console.store(enable);
306 }
_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:83
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:53
SetDebugString
void SetDebugString(const char *s, void(*error_func)(const char *))
Set debugging levels by parsing the text in s.
Definition: debug.cpp:164
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:950
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:191
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:252
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:190
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:394
GetDebugString
const char * GetDebugString()
Print out the current debug-level.
Definition: debug.cpp:229
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:98
DebugSendRemoteMessages
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
Definition: debug.cpp:270
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:554
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:113
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:85
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:402
DebugReconsiderSendRemoteMessages
void DebugReconsiderSendRemoteMessages()
Reconsider whether we need to send debug messages to either NetworkAdminConsole or IConsolePrint.
Definition: debug.cpp:294
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:604
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