Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / debug.cpp
blob7cc28e42805460b08020c22a0da5c85950651713
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 */
8 /** @file debug.cpp Handling of printing debug messages. */
10 #include "stdafx.h"
11 #include "console_func.h"
12 #include "debug.h"
13 #include "string_func.h"
14 #include "fileio_func.h"
15 #include "settings_type.h"
16 #include <mutex>
18 #if defined(_WIN32)
19 #include "os/windows/win32.h"
20 #endif
22 #include "3rdparty/fmt/chrono.h"
24 #include "network/network_admin.h"
26 #include "safeguards.h"
28 /** Element in the queue of debug messages that have to be passed to either NetworkAdminConsole or IConsolePrint.*/
29 struct QueuedDebugItem {
30 std::string level; ///< The used debug level.
31 std::string message; ///< The actual formatted message.
33 std::atomic<bool> _debug_remote_console; ///< Whether we need to send data to either NetworkAdminConsole or IConsolePrint.
34 std::mutex _debug_remote_console_mutex; ///< Mutex to guard the queue of debug messages for either NetworkAdminConsole or IConsolePrint.
35 std::vector<QueuedDebugItem> _debug_remote_console_queue; ///< Queue for debug messages to be passed to NetworkAdminConsole or IConsolePrint.
36 std::vector<QueuedDebugItem> _debug_remote_console_queue_spare; ///< Spare queue to swap with _debug_remote_console_queue.
38 int _debug_driver_level;
39 int _debug_grf_level;
40 int _debug_map_level;
41 int _debug_misc_level;
42 int _debug_net_level;
43 int _debug_sprite_level;
44 int _debug_oldloader_level;
45 int _debug_npf_level;
46 int _debug_yapf_level;
47 int _debug_fontcache_level;
48 int _debug_script_level;
49 int _debug_sl_level;
50 int _debug_gamelog_level;
51 int _debug_desync_level;
52 int _debug_console_level;
53 #ifdef RANDOM_DEBUG
54 int _debug_random_level;
55 #endif
57 struct DebugLevel {
58 const char *name;
59 int *level;
62 #define DEBUG_LEVEL(x) { #x, &_debug_##x##_level }
63 static const DebugLevel debug_level[] = {
64 DEBUG_LEVEL(driver),
65 DEBUG_LEVEL(grf),
66 DEBUG_LEVEL(map),
67 DEBUG_LEVEL(misc),
68 DEBUG_LEVEL(net),
69 DEBUG_LEVEL(sprite),
70 DEBUG_LEVEL(oldloader),
71 DEBUG_LEVEL(npf),
72 DEBUG_LEVEL(yapf),
73 DEBUG_LEVEL(fontcache),
74 DEBUG_LEVEL(script),
75 DEBUG_LEVEL(sl),
76 DEBUG_LEVEL(gamelog),
77 DEBUG_LEVEL(desync),
78 DEBUG_LEVEL(console),
79 #ifdef RANDOM_DEBUG
80 DEBUG_LEVEL(random),
81 #endif
83 #undef DEBUG_LEVEL
85 /**
86 * Dump the available debug facility names in the help text.
87 * @param output_iterator The iterator to write the string to.
89 void DumpDebugFacilityNames(std::back_insert_iterator<std::string> &output_iterator)
91 bool written = false;
92 for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
93 if (!written) {
94 fmt::format_to(output_iterator, "List of debug facility names:\n");
95 } else {
96 fmt::format_to(output_iterator, ", ");
98 fmt::format_to(output_iterator, "{}", i->name);
99 written = true;
101 if (written) {
102 fmt::format_to(output_iterator, "\n\n");
107 * Internal function for outputting the debug line.
108 * @param level Debug category.
109 * @param message The message to output.
111 void DebugPrint(const char *category, int level, const std::string &message)
113 if (strcmp(category, "desync") == 0) {
114 static FILE *f = FioFOpenFile("commands-out.log", "wb", AUTOSAVE_DIR);
115 if (f == nullptr) return;
117 fmt::print(f, "{}{}\n", GetLogPrefix(true), message);
118 fflush(f);
119 #ifdef RANDOM_DEBUG
120 } else if (strcmp(category, "random") == 0) {
121 static FILE *f = FioFOpenFile("random-out.log", "wb", AUTOSAVE_DIR);
122 if (f == nullptr) return;
124 fmt::print(f, "{}\n", message);
125 fflush(f);
126 #endif
127 } else {
128 fmt::print(stderr, "{}dbg: [{}:{}] {}\n", GetLogPrefix(true), category, level, message);
130 if (_debug_remote_console.load()) {
131 /* Only add to the queue when there is at least one consumer of the data. */
132 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
133 _debug_remote_console_queue.push_back({ category, message });
139 * Set debugging levels by parsing the text in \a s.
140 * For setting individual levels a string like \c "net=3,grf=6" should be used.
141 * If the string starts with a number, the number is used as global debugging level.
142 * @param s Text describing the wanted debugging levels.
143 * @param error_func The function to call if a parse error occurs.
145 void SetDebugString(const char *s, void (*error_func)(const std::string &))
147 int v;
148 char *end;
149 const char *t;
151 /* Store planned changes into map during parse */
152 std::map<const char *, int> new_levels;
154 /* Global debugging level? */
155 if (*s >= '0' && *s <= '9') {
156 const DebugLevel *i;
158 v = std::strtoul(s, &end, 0);
159 s = end;
161 for (i = debug_level; i != endof(debug_level); ++i) {
162 new_levels[i->name] = v;
166 /* Individual levels */
167 for (;;) {
168 /* skip delimiters */
169 while (*s == ' ' || *s == ',' || *s == '\t') s++;
170 if (*s == '\0') break;
172 t = s;
173 while (*s >= 'a' && *s <= 'z') s++;
175 /* check debugging levels */
176 const DebugLevel *found = nullptr;
177 for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
178 if (s == t + strlen(i->name) && strncmp(t, i->name, s - t) == 0) {
179 found = i;
180 break;
184 if (*s == '=') s++;
185 v = std::strtoul(s, &end, 0);
186 s = end;
187 if (found != nullptr) {
188 new_levels[found->name] = v;
189 } else {
190 std::string error_string = fmt::format("Unknown debug level '{}'", std::string(t, s - t));
191 error_func(error_string);
192 return;
196 /* Apply the changes after parse is successful */
197 for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
198 const auto &nl = new_levels.find(i->name);
199 if (nl != new_levels.end()) {
200 *i->level = nl->second;
206 * Print out the current debug-level.
207 * Just return a string with the values of all the debug categories.
208 * @return string with debug-levels
210 std::string GetDebugString()
212 std::string result;
213 for (const DebugLevel *i = debug_level; i != endof(debug_level); ++i) {
214 if (!result.empty()) result += ", ";
215 fmt::format_to(std::back_inserter(result), "{}={}", i->name, *i->level);
217 return result;
221 * Get the prefix for logs.
223 * If show_date_in_logs or \p force is enabled it returns
224 * the date, otherwise it returns an empty string.
226 * @return the prefix for logs.
228 std::string GetLogPrefix(bool force)
230 std::string log_prefix;
231 if (force || _settings_client.gui.show_date_in_logs) {
232 log_prefix = fmt::format("[{:%Y-%m-%d %H:%M:%S}] ", fmt::localtime(time(nullptr)));
234 return log_prefix;
238 * Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the
239 * GameLoop thread to prevent concurrent accesses to both the NetworkAdmin's packet queue
240 * as well as IConsolePrint's buffers.
242 * This is to be called from the GameLoop thread.
244 void DebugSendRemoteMessages()
246 if (!_debug_remote_console.load()) return;
249 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
250 std::swap(_debug_remote_console_queue, _debug_remote_console_queue_spare);
253 for (auto &item : _debug_remote_console_queue_spare) {
254 NetworkAdminConsole(item.level, item.message);
255 if (_settings_client.gui.developer >= 2) IConsolePrint(CC_DEBUG, "dbg: [{}] {}", item.level, item.message);
258 _debug_remote_console_queue_spare.clear();
262 * Reconsider whether we need to send debug messages to either NetworkAdminConsole
263 * or IConsolePrint. The former is when they have enabled console handling whereas
264 * the latter depends on the gui.developer setting's value.
266 * This is to be called from the GameLoop thread.
268 void DebugReconsiderSendRemoteMessages()
270 bool enable = _settings_client.gui.developer >= 2;
272 for (ServerNetworkAdminSocketHandler *as : ServerNetworkAdminSocketHandler::IterateActive()) {
273 if (as->update_frequency[ADMIN_UPDATE_CONSOLE] & ADMIN_FREQUENCY_AUTOMATIC) {
274 enable = true;
275 break;
279 _debug_remote_console.store(enable);