Bitcoin Core  0.20.99
P2P Digital Currency
system.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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.
5 
10 #ifndef BITCOIN_UTIL_SYSTEM_H
11 #define BITCOIN_UTIL_SYSTEM_H
12 
13 #if defined(HAVE_CONFIG_H)
14 #include <config/bitcoin-config.h>
15 #endif
16 
17 #include <attributes.h>
18 #include <compat.h>
19 #include <compat/assumptions.h>
20 #include <fs.h>
21 #include <logging.h>
22 #include <optional.h>
23 #include <sync.h>
24 #include <tinyformat.h>
25 #include <util/memory.h>
26 #include <util/settings.h>
27 #include <util/threadnames.h>
28 #include <util/time.h>
29 
30 #include <exception>
31 #include <map>
32 #include <set>
33 #include <stdint.h>
34 #include <string>
35 #include <utility>
36 #include <vector>
37 
38 #include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted
39 
40 // Application startup time (used for uptime calculation)
41 int64_t GetStartupTime();
42 
43 extern const char * const BITCOIN_CONF_FILENAME;
44 
45 void SetupEnvironment();
46 bool SetupNetworking();
47 
48 template<typename... Args>
49 bool error(const char* fmt, const Args&... args)
50 {
51  LogPrintf("ERROR: %s\n", tfm::format(fmt, args...));
52  return false;
53 }
54 
55 void PrintExceptionContinue(const std::exception *pex, const char* pszThread);
56 bool FileCommit(FILE *file);
57 bool TruncateFile(FILE *file, unsigned int length);
58 int RaiseFileDescriptorLimit(int nMinFD);
59 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
60 bool RenameOver(fs::path src, fs::path dest);
61 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only=false);
62 void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name);
63 bool DirIsWritable(const fs::path& directory);
64 bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes = 0);
65 
72 std::streampos GetFileSize(const char* path, std::streamsize max = std::numeric_limits<std::streamsize>::max());
73 
78 
79 bool TryCreateDirectories(const fs::path& p);
80 fs::path GetDefaultDataDir();
81 // The blocks directory is always net specific.
82 const fs::path &GetBlocksDir();
83 const fs::path &GetDataDir(bool fNetSpecific = true);
84 // Return true if -datadir option points to a valid directory or is not specified.
85 bool CheckDataDirOption();
87 void ClearDatadirCache();
88 fs::path GetConfigFile(const std::string& confPath);
89 #ifdef WIN32
90 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
91 #endif
92 #ifndef WIN32
93 std::string ShellEscape(const std::string& arg);
94 #endif
95 #if HAVE_SYSTEM
96 void runCommand(const std::string& strCommand);
97 #endif
98 
107 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific = true);
108 
109 inline bool IsSwitchChar(char c)
110 {
111 #ifdef WIN32
112  return c == '-' || c == '/';
113 #else
114  return c == '-';
115 #endif
116 }
117 
118 enum class OptionsCategory {
119  OPTIONS,
120  CONNECTION,
121  WALLET,
123  ZMQ,
124  DEBUG_TEST,
125  CHAINPARAMS,
126  NODE_RELAY,
128  RPC,
129  GUI,
130  COMMANDS,
132 
133  HIDDEN // Always the last option to avoid printing these in the help
134 };
135 
137 {
138  std::string m_name;
139  std::string m_file;
140  int m_line;
141 };
142 
144 {
145 public:
146  enum Flags {
147  // Boolean options can accept negation syntax -noOPTION or -noOPTION=1
148  ALLOW_BOOL = 0x01,
149  ALLOW_INT = 0x02,
150  ALLOW_STRING = 0x04,
151  ALLOW_ANY = ALLOW_BOOL | ALLOW_INT | ALLOW_STRING,
152  DEBUG_ONLY = 0x100,
153  /* Some options would cause cross-contamination if values for
154  * mainnet were used while running on regtest/testnet (or vice-versa).
155  * Setting them as NETWORK_ONLY ensures that sharing a config file
156  * between mainnet and regtest/testnet won't cause problems due to these
157  * parameters by accident. */
158  NETWORK_ONLY = 0x200,
159  // This argument's value is sensitive (such as a password).
160  SENSITIVE = 0x400,
161  };
162 
163 protected:
164  struct Arg
165  {
166  std::string m_help_param;
167  std::string m_help_text;
168  unsigned int m_flags;
169  };
170 
172  util::Settings m_settings GUARDED_BY(cs_args);
173  std::string m_network GUARDED_BY(cs_args);
174  std::set<std::string> m_network_only_args GUARDED_BY(cs_args);
175  std::map<OptionsCategory, std::map<std::string, Arg>> m_available_args GUARDED_BY(cs_args);
176  std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args);
177 
178  NODISCARD bool ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys = false);
179 
185  bool UseDefaultSection(const std::string& arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
186 
194  util::SettingsValue GetSetting(const std::string& arg) const;
195 
199  std::vector<util::SettingsValue> GetSettingsList(const std::string& arg) const;
200 
201 public:
202  ArgsManager();
203  ~ArgsManager();
204 
208  void SelectConfigNetwork(const std::string& network);
209 
210  NODISCARD bool ParseParameters(int argc, const char* const argv[], std::string& error);
211  NODISCARD bool ReadConfigFiles(std::string& error, bool ignore_invalid_keys = false);
212 
219  const std::set<std::string> GetUnsuitableSectionOnlyArgs() const;
220 
224  const std::list<SectionInfo> GetUnrecognizedSections() const;
225 
232  std::vector<std::string> GetArgs(const std::string& strArg) const;
233 
240  bool IsArgSet(const std::string& strArg) const;
241 
249  bool IsArgNegated(const std::string& strArg) const;
250 
258  std::string GetArg(const std::string& strArg, const std::string& strDefault) const;
259 
267  int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
268 
276  bool GetBoolArg(const std::string& strArg, bool fDefault) const;
277 
285  bool SoftSetArg(const std::string& strArg, const std::string& strValue);
286 
294  bool SoftSetBoolArg(const std::string& strArg, bool fValue);
295 
296  // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
297  // been set. Also called directly in testing.
298  void ForceSetArg(const std::string& strArg, const std::string& strValue);
299 
304  std::string GetChainName() const;
305 
309  void AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat);
310 
314  void AddHiddenArgs(const std::vector<std::string>& args);
315 
319  void ClearArgs() {
320  LOCK(cs_args);
321  m_available_args.clear();
322  m_network_only_args.clear();
323  }
324 
328  std::string GetHelpMessage() const;
329 
334  Optional<unsigned int> GetArgFlags(const std::string& name) const;
335 
340  void LogArgs() const;
341 
342 private:
343  // Helper function for LogArgs().
344  void logArgsPrefix(
345  const std::string& prefix,
346  const std::string& section,
347  const std::map<std::string, std::vector<util::SettingsValue>>& args) const;
348 };
349 
350 extern ArgsManager gArgs;
351 
355 bool HelpRequested(const ArgsManager& args);
356 
358 void SetupHelpOptions(ArgsManager& args);
359 
366 std::string HelpMessageGroup(const std::string& message);
367 
375 std::string HelpMessageOpt(const std::string& option, const std::string& message);
376 
381 int GetNumCores();
382 
386 template <typename Callable> void TraceThread(const char* name, Callable func)
387 {
388  util::ThreadRename(name);
389  try
390  {
391  LogPrintf("%s thread start\n", name);
392  func();
393  LogPrintf("%s thread exit\n", name);
394  }
395  catch (const boost::thread_interrupted&)
396  {
397  LogPrintf("%s thread interrupt\n", name);
398  throw;
399  }
400  catch (const std::exception& e) {
401  PrintExceptionContinue(&e, name);
402  throw;
403  }
404  catch (...) {
405  PrintExceptionContinue(nullptr, name);
406  throw;
407  }
408 }
409 
410 std::string CopyrightHolders(const std::string& strPrefix);
411 
417 void ScheduleBatchPriority();
418 
419 namespace util {
420 
422 template <typename Tdst, typename Tsrc>
423 inline void insert(Tdst& dst, const Tsrc& src) {
424  dst.insert(dst.begin(), src.begin(), src.end());
425 }
426 template <typename TsetT, typename Tsrc>
427 inline void insert(std::set<TsetT>& dst, const Tsrc& src) {
428  dst.insert(src.begin(), src.end());
429 }
430 
431 #ifdef WIN32
432 class WinCmdLineArgs
433 {
434 public:
435  WinCmdLineArgs();
436  ~WinCmdLineArgs();
437  std::pair<int, char**> get();
438 
439 private:
440  int argc;
441  char** argv;
442  std::vector<std::string> args;
443 };
444 #endif
445 
446 } // namespace util
447 
448 #endif // BITCOIN_UTIL_SYSTEM_H
Stored bitcoin settings.
Definition: settings.h:29
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: system.cpp:1154
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:962
Definition: httprpc.h:8
void SetupEnvironment()
Definition: system.cpp:1082
unsigned int m_flags
Definition: system.h:168
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:665
const char * prefix
Definition: rest.cpp:648
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool get_chain_name)
Get settings value from combined sources: forced settings, command line arguments and the read-only c...
Definition: settings.cpp:52
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
Definition: threadnames.cpp:57
int m_line
Definition: system.h:140
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1162
RecursiveMutex cs_args
Definition: system.h:171
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:899
const fs::path & GetBlocksDir()
Definition: system.cpp:595
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:520
std::streampos GetFileSize(const char *path, std::streamsize max=std::numeric_limits< std::streamsize >::max())
Get the size of a file by scanning it.
Definition: system.cpp:145
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: system.cpp:997
std::string m_name
Definition: system.h:138
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:557
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:124
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:974
const fs::path & GetDataDir(bool fNetSpecific=true)
Definition: system.cpp:620
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers, startup time.
Definition: system.cpp:1149
std::vector< SettingsValue > GetSettingsList(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config)
Get combined setting value similar to GetSetting(), except if setting was specified multiple times...
Definition: settings.cpp:105
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:75
bool FileCommit(FILE *file)
Definition: system.cpp:929
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes=0)
Definition: system.cpp:137
#define NODISCARD
Definition: attributes.h:18
#define LOCK(cs)
Definition: sync.h:226
const char * name
Definition: rest.cpp:41
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1062
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:515
bool CheckDataDirOption()
Definition: system.cpp:650
std::string m_file
Definition: system.h:139
UniValue help(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:133
void ClearArgs()
Clear available arguments.
Definition: system.h:319
std::string m_help_text
Definition: system.h:167
void TraceThread(const char *name, Callable func)
Definition: system.h:386
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: system.cpp:530
int flags
Definition: bitcoin-tx.cpp:509
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:53
fs::path GetDefaultDataDir()
Definition: system.cpp:564
void ClearDatadirCache()
Tests only.
Definition: system.cpp:656
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:112
#define GUARDED_BY(x)
Definition: threadsafety.h:40
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: system.cpp:915
bool IsSwitchChar(char c)
Definition: system.h:109
OptionsCategory
Definition: system.h:118
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1136
std::string m_help_param
Definition: system.h:166
void insert(std::set< TsetT > &dst, const Tsrc &src)
Definition: system.h:427
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: system.cpp:534
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only=false)
Definition: system.cpp:88
ArgsManager gArgs
Definition: system.cpp:77
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:118
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1060
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1131
bool SetupNetworking()
Definition: system.cpp:1119