OpenTTD Source 20261112-master-gbcbec5e63f
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
12#include "console_func.h"
13#include "debug.h"
14#include "fileio_func.h"
15#include "settings_type.h"
16#include <mutex>
17
18#if defined(_WIN32)
19#include "os/windows/win32.h"
20#endif
21
22#include "3rdparty/fmt/chrono.h"
23
25
26#include "safeguards.h"
27
31 std::string message;
32};
33std::atomic<bool> _debug_remote_console;
35std::vector<QueuedDebugItem> _debug_remote_console_queue;
36std::vector<QueuedDebugItem> _debug_remote_console_queue_spare;
37
40
43 "driver", // Facility::Driver
44 "grf", // Facility::Grf
45 "map", // Facility::Map
46 "misc", // Facility::Misc
47 "net", // Facility::Net
48 "sprite", // Facility::Sprite
49 "oldloader", // Facility::Oldloader
50 "yapf", // Facility::Yapf
51 "fontcache", // Facility::Fontcache
52 "script", // Facility::Script
53 "sl", // Facility::Sl
54 "gamelog", // Facility::Gamelog
55 "desync", // Facility::Desync
56 "console", // Facility::Console
57 "random", // Facility::Random
58};
59
64void DumpDebugFacilityNames(std::back_insert_iterator<std::string> &output_iterator)
65{
66 bool written = false;
67 for (Facility facility : EnumRange(Facility::End)) {
68 if (!written) {
69 fmt::format_to(output_iterator, "List of debug facility names:\n");
70 } else {
71 fmt::format_to(output_iterator, ", ");
72 }
73 fmt::format_to(output_iterator, "{}", _debug_facilities[facility]);
74 written = true;
75 }
76 if (written) {
77 fmt::format_to(output_iterator, "\n\n");
78 }
79}
80
87void DebugPrint(Facility facility, Severity severity, std::string &&message)
88{
89 if (facility == Facility::Desync && severity != Severity::Critical) {
90 static auto f = FioFOpenFile("commands-out.log", "wb", Subdirectory::Autosave);
91 if (!f.has_value()) return;
92
93 fmt::print(*f, "{}{}\n", GetLogPrefix(true), message);
94 fflush(*f);
95#ifdef RANDOM_DEBUG
96 } else if (facility == Facility::Random) {
97 static auto f = FioFOpenFile("random-out.log", "wb", Subdirectory::Autosave);
98 if (!f.has_value()) return;
99
100 fmt::print(*f, "{}\n", message);
101 fflush(*f);
102#endif
103 } else {
104 fmt::print(stderr, "{}dbg: [{}:{}] {}\n", GetLogPrefix(true), _debug_facilities[facility], severity, message);
105
106 if (_debug_remote_console.load()) {
107 /* Only add to the queue when there is at least one consumer of the data. */
108 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
109 _debug_remote_console_queue.emplace_back(facility, std::move(message));
110 }
111 }
112}
113
121void SetDebugString(std::string_view s, SetDebugStringErrorFunc error_func)
122{
123 StringConsumer consumer{s};
124
125 /* Store planned changes into a temporary array during parse */
126 auto new_debug_level = _debug_level;
127
128 /* Global debugging level? */
129 auto level = consumer.TryReadIntegerBase<int>(10);
130 if (level.has_value()) {
131 new_debug_level.fill(static_cast<Severity>(*level));
132 }
133
134 static const std::string_view lowercase_letters{"abcdefghijklmnopqrstuvwxyz"};
135 static const std::string_view lowercase_letters_and_digits{"abcdefghijklmnopqrstuvwxyz0123456789"};
136
137 /* Individual levels */
138 while (consumer.AnyBytesLeft()) {
139 consumer.SkipUntilCharIn(lowercase_letters);
140 if (!consumer.AnyBytesLeft()) break;
141
142 /* Find the level by name. */
143 std::string_view key = consumer.ReadUntilCharNotIn(lowercase_letters);
144 auto it = std::ranges::find(_debug_facilities, key);
145 if (it == std::end(_debug_facilities)) {
146 error_func(fmt::format("Unknown debug level '{}'", key));
147 return;
148 }
149
150 /* Do not skip lowercase letters, so 'net misc=2' won't be resolved
151 * to setting 'net=2' and leaving misc untouched. */
152 consumer.SkipUntilCharIn(lowercase_letters_and_digits);
153 level = consumer.TryReadIntegerBase<int>(10);
154 if (!level.has_value()) {
155 error_func(fmt::format("Level for '{}' must be a valid integer.", key));
156 return;
157 }
158
159 new_debug_level[static_cast<Facility>(std::distance(_debug_facilities.begin(), it))] = static_cast<Severity>(*level);
160 }
161
162 /* Apply the changes after parse is successful */
163 _debug_level = new_debug_level;
164}
165
171std::string GetDebugString()
172{
173 std::string result;
174 for (Facility facility : EnumRange(Facility::End)) {
175 if (!result.empty()) result += ", ";
176 format_append(result, "{}={}", _debug_facilities[facility], _debug_level[facility]);
177 }
178 return result;
179}
180
190std::string GetLogPrefix(bool force)
191{
192 std::string log_prefix;
193 if (force || _settings_client.gui.show_date_in_logs) {
194 log_prefix = fmt::format("[{:%Y-%m-%d %H:%M:%S}] ", fmt::localtime(time(nullptr)));
195 }
196 return log_prefix;
197}
198
207{
208 if (!_debug_remote_console.load()) return;
209
210 {
211 std::lock_guard<std::mutex> lock(_debug_remote_console_mutex);
213 }
214
215 for (auto &item : _debug_remote_console_queue_spare) {
216 NetworkAdminConsole(_debug_facilities[item.facility], item.message);
217 if (_settings_client.gui.developer >= 2) IConsolePrint(CC_DEBUG, "dbg: [{}] {}", _debug_facilities[item.facility], item.message);
218 }
219
221}
222
231{
232 bool enable = _settings_client.gui.developer >= 2;
233
235 if (as->update_frequency[AdminUpdateType::Console].Test(AdminUpdateFrequency::Automatic)) {
236 enable = true;
237 break;
238 }
239 }
240
241 _debug_remote_console.store(enable);
242}
Iterate a range of enum values.
Class for handling the server side of the game connection.
static Pool::IterateWrapperFiltered< ServerNetworkAdminSocketHandler, ServerNetworkAdminSocketHandlerFilter > IterateActive(size_t from=0)
Returns an iterable ensemble of all active admin sockets.
Parse data from a string / buffer.
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
std::string_view ReadUntilCharNotIn(std::string_view chars)
Read 8-bit chars, while they are in 'chars', until they are not; and advance reader.
void SkipUntilCharIn(std::string_view chars)
Skip 8-bit chars, while they are not in 'chars', until they are.
void IConsolePrint(ExtendedTextColour 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:91
Console functions used outside of the console code.
static const TextColour CC_DEBUG
Colour for debug output.
std::string GetLogPrefix(bool force)
Get the prefix for logs.
Definition debug.cpp:190
std::vector< QueuedDebugItem > _debug_remote_console_queue
Queue for debug messages to be passed to NetworkAdminConsole or IConsolePrint.
Definition debug.cpp:35
std::mutex _debug_remote_console_mutex
Mutex to guard the queue of debug messages for either NetworkAdminConsole or IConsolePrint.
Definition debug.cpp:34
void SetDebugString(std::string_view s, SetDebugStringErrorFunc error_func)
Set debugging levels by parsing the text in s.
Definition debug.cpp:121
void DebugReconsiderSendRemoteMessages()
Reconsider whether we need to send debug messages to either NetworkAdminConsole or IConsolePrint.
Definition debug.cpp:230
std::atomic< bool > _debug_remote_console
Whether we need to send data to either NetworkAdminConsole or IConsolePrint.
Definition debug.cpp:33
void DumpDebugFacilityNames(std::back_insert_iterator< std::string > &output_iterator)
Dump the available debug facility names in the help text.
Definition debug.cpp:64
std::vector< QueuedDebugItem > _debug_remote_console_queue_spare
Spare queue to swap with _debug_remote_console_queue.
Definition debug.cpp:36
EnumIndexArray< Severity, Facility, Facility::End > _debug_level
Severity level for each debug facility.
Definition debug.cpp:39
std::string GetDebugString()
Print out the current debug-level.
Definition debug.cpp:171
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
Definition debug.cpp:206
void DebugPrint(Facility facility, Severity severity, std::string &&message)
Internal function for outputting the debug line.
Definition debug.cpp:87
static EnumIndexArray< std::string_view, Facility, Facility::End > _debug_facilities
Name for each debug facility.
Definition debug.cpp:42
Functions related to debugging.
Facility
Debug facilities.
Definition debug_type.h:28
@ Desync
Desync message facility.
Definition debug_type.h:41
@ Random
Random message facility.
Definition debug_type.h:43
@ End
End marker.
Definition debug_type.h:44
Severity
Debug message severity levels.
Definition debug_type.h:14
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
std::optional< FileHandle > FioFOpenFile(std::string_view filename, std::string_view mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition fileio.cpp:248
Functions for standard in/out file operations.
@ Autosave
Subdirectory of save for autosaves.
Definition fileio_type.h:90
void NetworkAdminConsole(std::string_view origin, std::string_view string)
Send console to the admin network (if they did opt in for the respective update).
Server part of the admin network protocol.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Types related to global configuration settings.
Definition of base types and functions in a cross-platform compatible way.
Parse strings.
Element in the queue of debug messages that have to be passed to either NetworkAdminConsole or IConso...
Definition debug.cpp:29
Facility facility
The facility of the message.
Definition debug.cpp:30
std::string message
The actual formatted message.
Definition debug.cpp:31
@ Console
The admin would like to have console messages.
Definition tcp_admin.h:86
@ Automatic
The admin gets information about this when it changes.
Definition tcp_admin.h:101
Declarations of functions for MS windows systems.
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35