Fix constness of ArgsManager methods
[bitcoinplatinum.git] / src / util.h
blob757a6abdf615b97465dec02c47d590f2b25c16ec
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 /**
7 * Server/client environment: argument handling, config file parsing,
8 * logging, thread wrappers, startup time
9 */
10 #ifndef BITCOIN_UTIL_H
11 #define BITCOIN_UTIL_H
13 #if defined(HAVE_CONFIG_H)
14 #include "config/bitcoin-config.h"
15 #endif
17 #include "compat.h"
18 #include "fs.h"
19 #include "sync.h"
20 #include "tinyformat.h"
21 #include "utiltime.h"
23 #include <atomic>
24 #include <exception>
25 #include <map>
26 #include <stdint.h>
27 #include <string>
28 #include <vector>
30 #include <boost/signals2/signal.hpp>
32 // Application startup time (used for uptime calculation)
33 int64_t GetStartupTime();
35 static const bool DEFAULT_LOGTIMEMICROS = false;
36 static const bool DEFAULT_LOGIPS = false;
37 static const bool DEFAULT_LOGTIMESTAMPS = true;
39 /** Signals for translation. */
40 class CTranslationInterface
42 public:
43 /** Translate a message to the native language of the user. */
44 boost::signals2::signal<std::string (const char* psz)> Translate;
47 extern bool fPrintToConsole;
48 extern bool fPrintToDebugLog;
50 extern bool fLogTimestamps;
51 extern bool fLogTimeMicros;
52 extern bool fLogIPs;
53 extern std::atomic<bool> fReopenDebugLog;
54 extern CTranslationInterface translationInterface;
56 extern const char * const BITCOIN_CONF_FILENAME;
57 extern const char * const BITCOIN_PID_FILENAME;
59 extern std::atomic<uint32_t> logCategories;
61 /**
62 * Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
63 * If no translation slot is registered, nothing is returned, and simply return the input.
65 inline std::string _(const char* psz)
67 boost::optional<std::string> rv = translationInterface.Translate(psz);
68 return rv ? (*rv) : psz;
71 void SetupEnvironment();
72 bool SetupNetworking();
74 struct CLogCategoryActive
76 std::string category;
77 bool active;
80 namespace BCLog {
81 enum LogFlags : uint32_t {
82 NONE = 0,
83 NET = (1 << 0),
84 TOR = (1 << 1),
85 MEMPOOL = (1 << 2),
86 HTTP = (1 << 3),
87 BENCH = (1 << 4),
88 ZMQ = (1 << 5),
89 DB = (1 << 6),
90 RPC = (1 << 7),
91 ESTIMATEFEE = (1 << 8),
92 ADDRMAN = (1 << 9),
93 SELECTCOINS = (1 << 10),
94 REINDEX = (1 << 11),
95 CMPCTBLOCK = (1 << 12),
96 RAND = (1 << 13),
97 PRUNE = (1 << 14),
98 PROXY = (1 << 15),
99 MEMPOOLREJ = (1 << 16),
100 LIBEVENT = (1 << 17),
101 COINDB = (1 << 18),
102 QT = (1 << 19),
103 LEVELDB = (1 << 20),
104 ALL = ~(uint32_t)0,
107 /** Return true if log accepts specified category */
108 static inline bool LogAcceptCategory(uint32_t category)
110 return (logCategories.load(std::memory_order_relaxed) & category) != 0;
113 /** Returns a string with the log categories. */
114 std::string ListLogCategories();
116 /** Returns a vector of the active log categories. */
117 std::vector<CLogCategoryActive> ListActiveLogCategories();
119 /** Return true if str parses as a log category and set the flags in f */
120 bool GetLogCategory(uint32_t *f, const std::string *str);
122 /** Send a string to the log output */
123 int LogPrintStr(const std::string &str);
125 /** Get format string from VA_ARGS for error reporting */
126 template<typename... Args> std::string FormatStringFromLogArgs(const char *fmt, const Args&... args) { return fmt; }
128 static inline void MarkUsed() {}
129 template<typename T, typename... Args> static inline void MarkUsed(const T& t, const Args&... args)
131 (void)t;
132 MarkUsed(args...);
135 #ifdef USE_COVERAGE
136 #define LogPrintf(...) do { MarkUsed(__VA_ARGS__); } while(0)
137 #define LogPrint(category, ...) do { MarkUsed(__VA_ARGS__); } while(0)
138 #else
139 #define LogPrintf(...) do { \
140 std::string _log_msg_; /* Unlikely name to avoid shadowing variables */ \
141 try { \
142 _log_msg_ = tfm::format(__VA_ARGS__); \
143 } catch (tinyformat::format_error &fmterr) { \
144 /* Original format string will have newline so don't add one here */ \
145 _log_msg_ = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + FormatStringFromLogArgs(__VA_ARGS__); \
147 LogPrintStr(_log_msg_); \
148 } while(0)
150 #define LogPrint(category, ...) do { \
151 if (LogAcceptCategory((category))) { \
152 LogPrintf(__VA_ARGS__); \
154 } while(0)
155 #endif
157 template<typename... Args>
158 bool error(const char* fmt, const Args&... args)
160 LogPrintStr("ERROR: " + tfm::format(fmt, args...) + "\n");
161 return false;
164 void PrintExceptionContinue(const std::exception *pex, const char* pszThread);
165 void FileCommit(FILE *file);
166 bool TruncateFile(FILE *file, unsigned int length);
167 int RaiseFileDescriptorLimit(int nMinFD);
168 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
169 bool RenameOver(fs::path src, fs::path dest);
170 bool TryCreateDirectories(const fs::path& p);
171 fs::path GetDefaultDataDir();
172 const fs::path &GetDataDir(bool fNetSpecific = true);
173 void ClearDatadirCache();
174 fs::path GetConfigFile(const std::string& confPath);
175 #ifndef WIN32
176 fs::path GetPidFile();
177 void CreatePidFile(const fs::path &path, pid_t pid);
178 #endif
179 #ifdef WIN32
180 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
181 #endif
182 void OpenDebugLog();
183 void ShrinkDebugFile();
184 void runCommand(const std::string& strCommand);
186 inline bool IsSwitchChar(char c)
188 #ifdef WIN32
189 return c == '-' || c == '/';
190 #else
191 return c == '-';
192 #endif
195 class ArgsManager
197 protected:
198 mutable CCriticalSection cs_args;
199 std::map<std::string, std::string> mapArgs;
200 std::map<std::string, std::vector<std::string>> mapMultiArgs;
201 public:
202 void ParseParameters(int argc, const char*const argv[]);
203 void ReadConfigFile(const std::string& confPath);
206 * Return a vector of strings of the given argument
208 * @param strArg Argument to get (e.g. "-foo")
209 * @return command-line arguments
211 std::vector<std::string> GetArgs(const std::string& strArg) const;
214 * Return true if the given argument has been manually set
216 * @param strArg Argument to get (e.g. "-foo")
217 * @return true if the argument has been set
219 bool IsArgSet(const std::string& strArg) const;
222 * Return string argument or default value
224 * @param strArg Argument to get (e.g. "-foo")
225 * @param strDefault (e.g. "1")
226 * @return command-line argument or default value
228 std::string GetArg(const std::string& strArg, const std::string& strDefault) const;
231 * Return integer argument or default value
233 * @param strArg Argument to get (e.g. "-foo")
234 * @param nDefault (e.g. 1)
235 * @return command-line argument (0 if invalid number) or default value
237 int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
240 * Return boolean argument or default value
242 * @param strArg Argument to get (e.g. "-foo")
243 * @param fDefault (true or false)
244 * @return command-line argument or default value
246 bool GetBoolArg(const std::string& strArg, bool fDefault) const;
249 * Set an argument if it doesn't already have a value
251 * @param strArg Argument to set (e.g. "-foo")
252 * @param strValue Value (e.g. "1")
253 * @return true if argument gets set, false if it already had a value
255 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
258 * Set a boolean argument if it doesn't already have a value
260 * @param strArg Argument to set (e.g. "-foo")
261 * @param fValue Value (e.g. false)
262 * @return true if argument gets set, false if it already had a value
264 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
266 // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
267 // been set. Also called directly in testing.
268 void ForceSetArg(const std::string& strArg, const std::string& strValue);
271 extern ArgsManager gArgs;
273 // wrappers using the global ArgsManager:
274 static inline void ParseParameters(int argc, const char*const argv[])
276 gArgs.ParseParameters(argc, argv);
279 static inline void ReadConfigFile(const std::string& confPath)
281 gArgs.ReadConfigFile(confPath);
284 static inline bool SoftSetArg(const std::string& strArg, const std::string& strValue)
286 return gArgs.SoftSetArg(strArg, strValue);
289 static inline void ForceSetArg(const std::string& strArg, const std::string& strValue)
291 gArgs.ForceSetArg(strArg, strValue);
294 static inline bool IsArgSet(const std::string& strArg)
296 return gArgs.IsArgSet(strArg);
299 static inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
301 return gArgs.GetArg(strArg, strDefault);
304 static inline int64_t GetArg(const std::string& strArg, int64_t nDefault)
306 return gArgs.GetArg(strArg, nDefault);
309 static inline bool GetBoolArg(const std::string& strArg, bool fDefault)
311 return gArgs.GetBoolArg(strArg, fDefault);
314 static inline bool SoftSetBoolArg(const std::string& strArg, bool fValue)
316 return gArgs.SoftSetBoolArg(strArg, fValue);
320 * Format a string to be used as group of options in help messages
322 * @param message Group name (e.g. "RPC server options:")
323 * @return the formatted string
325 std::string HelpMessageGroup(const std::string& message);
328 * Format a string to be used as option description in help messages
330 * @param option Option message (e.g. "-rpcuser=<user>")
331 * @param message Option description (e.g. "Username for JSON-RPC connections")
332 * @return the formatted string
334 std::string HelpMessageOpt(const std::string& option, const std::string& message);
337 * Return the number of physical cores available on the current system.
338 * @note This does not count virtual cores, such as those provided by HyperThreading
339 * when boost is newer than 1.56.
341 int GetNumCores();
343 void RenameThread(const char* name);
346 * .. and a wrapper that just calls func once
348 template <typename Callable> void TraceThread(const char* name, Callable func)
350 std::string s = strprintf("bitcoin-%s", name);
351 RenameThread(s.c_str());
354 LogPrintf("%s thread start\n", name);
355 func();
356 LogPrintf("%s thread exit\n", name);
358 catch (const boost::thread_interrupted&)
360 LogPrintf("%s thread interrupt\n", name);
361 throw;
363 catch (const std::exception& e) {
364 PrintExceptionContinue(&e, name);
365 throw;
367 catch (...) {
368 PrintExceptionContinue(NULL, name);
369 throw;
373 std::string CopyrightHolders(const std::string& strPrefix);
375 #endif // BITCOIN_UTIL_H