Bitcoin Core  0.19.99
P2P Digital Currency
system.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 <sync.h>
23 #include <tinyformat.h>
24 #include <util/memory.h>
25 #include <util/threadnames.h>
26 #include <util/time.h>
27 
28 #include <exception>
29 #include <map>
30 #include <set>
31 #include <stdint.h>
32 #include <string>
33 #include <utility>
34 #include <vector>
35 
36 #include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted
37 
38 // Application startup time (used for uptime calculation)
39 int64_t GetStartupTime();
40 
41 extern const char * const BITCOIN_CONF_FILENAME;
42 
43 void SetupEnvironment();
44 bool SetupNetworking();
45 
46 template<typename... Args>
47 bool error(const char* fmt, const Args&... args)
48 {
49  LogPrintf("ERROR: %s\n", tfm::format(fmt, args...));
50  return false;
51 }
52 
53 void PrintExceptionContinue(const std::exception *pex, const char* pszThread);
54 bool FileCommit(FILE *file);
55 bool TruncateFile(FILE *file, unsigned int length);
56 int RaiseFileDescriptorLimit(int nMinFD);
57 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
58 bool RenameOver(fs::path src, fs::path dest);
59 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only=false);
60 void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name);
61 bool DirIsWritable(const fs::path& directory);
62 bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes = 0);
63 
68 
69 bool TryCreateDirectories(const fs::path& p);
70 fs::path GetDefaultDataDir();
71 // The blocks directory is always net specific.
72 const fs::path &GetBlocksDir();
73 const fs::path &GetDataDir(bool fNetSpecific = true);
74 // Return true if -datadir option points to a valid directory or is not specified.
75 bool CheckDataDirOption();
77 void ClearDatadirCache();
78 fs::path GetConfigFile(const std::string& confPath);
79 #ifdef WIN32
80 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
81 #endif
82 #if HAVE_SYSTEM
83 void runCommand(const std::string& strCommand);
84 #endif
85 
94 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific = true);
95 
96 inline bool IsSwitchChar(char c)
97 {
98 #ifdef WIN32
99  return c == '-' || c == '/';
100 #else
101  return c == '-';
102 #endif
103 }
104 
105 enum class OptionsCategory {
106  OPTIONS,
107  CONNECTION,
108  WALLET,
110  ZMQ,
111  DEBUG_TEST,
112  CHAINPARAMS,
113  NODE_RELAY,
115  RPC,
116  GUI,
117  COMMANDS,
119 
120  HIDDEN // Always the last option to avoid printing these in the help
121 };
122 
124 {
125  std::string m_name;
126  std::string m_file;
127  int m_line;
128 };
129 
131 {
132 public:
133  enum Flags {
134  NONE = 0x00,
135  // Boolean options can accept negation syntax -noOPTION or -noOPTION=1
136  ALLOW_BOOL = 0x01,
137  ALLOW_INT = 0x02,
138  ALLOW_STRING = 0x04,
139  ALLOW_ANY = ALLOW_BOOL | ALLOW_INT | ALLOW_STRING,
140  DEBUG_ONLY = 0x100,
141  /* Some options would cause cross-contamination if values for
142  * mainnet were used while running on regtest/testnet (or vice-versa).
143  * Setting them as NETWORK_ONLY ensures that sharing a config file
144  * between mainnet and regtest/testnet won't cause problems due to these
145  * parameters by accident. */
146  NETWORK_ONLY = 0x200,
147  };
148 
149 protected:
150  friend class ArgsManagerHelper;
151 
152  struct Arg
153  {
154  std::string m_help_param;
155  std::string m_help_text;
156  unsigned int m_flags;
157  };
158 
160  std::map<std::string, std::vector<std::string>> m_override_args GUARDED_BY(cs_args);
161  std::map<std::string, std::vector<std::string>> m_config_args GUARDED_BY(cs_args);
162  std::string m_network GUARDED_BY(cs_args);
163  std::set<std::string> m_network_only_args GUARDED_BY(cs_args);
164  std::map<OptionsCategory, std::map<std::string, Arg>> m_available_args GUARDED_BY(cs_args);
165  std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args);
166 
167  NODISCARD bool ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys = false);
168 
169 public:
170  ArgsManager();
171 
175  void SelectConfigNetwork(const std::string& network);
176 
177  NODISCARD bool ParseParameters(int argc, const char* const argv[], std::string& error);
178  NODISCARD bool ReadConfigFiles(std::string& error, bool ignore_invalid_keys = false);
179 
186  const std::set<std::string> GetUnsuitableSectionOnlyArgs() const;
187 
191  const std::list<SectionInfo> GetUnrecognizedSections() const;
192 
199  std::vector<std::string> GetArgs(const std::string& strArg) const;
200 
207  bool IsArgSet(const std::string& strArg) const;
208 
216  bool IsArgNegated(const std::string& strArg) const;
217 
225  std::string GetArg(const std::string& strArg, const std::string& strDefault) const;
226 
234  int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
235 
243  bool GetBoolArg(const std::string& strArg, bool fDefault) const;
244 
252  bool SoftSetArg(const std::string& strArg, const std::string& strValue);
253 
261  bool SoftSetBoolArg(const std::string& strArg, bool fValue);
262 
263  // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
264  // been set. Also called directly in testing.
265  void ForceSetArg(const std::string& strArg, const std::string& strValue);
266 
271  std::string GetChainName() const;
272 
276  void AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat);
277 
281  void AddHiddenArgs(const std::vector<std::string>& args);
282 
286  void ClearArgs() {
287  LOCK(cs_args);
288  m_available_args.clear();
289  m_network_only_args.clear();
290  }
291 
295  std::string GetHelpMessage() const;
296 
301  unsigned int FlagsOfKnownArg(const std::string& key) const;
302 };
303 
304 extern ArgsManager gArgs;
305 
309 bool HelpRequested(const ArgsManager& args);
310 
312 void SetupHelpOptions(ArgsManager& args);
313 
320 std::string HelpMessageGroup(const std::string& message);
321 
329 std::string HelpMessageOpt(const std::string& option, const std::string& message);
330 
335 int GetNumCores();
336 
340 template <typename Callable> void TraceThread(const char* name, Callable func)
341 {
342  util::ThreadRename(name);
343  try
344  {
345  LogPrintf("%s thread start\n", name);
346  func();
347  LogPrintf("%s thread exit\n", name);
348  }
349  catch (const boost::thread_interrupted&)
350  {
351  LogPrintf("%s thread interrupt\n", name);
352  throw;
353  }
354  catch (const std::exception& e) {
355  PrintExceptionContinue(&e, name);
356  throw;
357  }
358  catch (...) {
359  PrintExceptionContinue(nullptr, name);
360  throw;
361  }
362 }
363 
364 std::string CopyrightHolders(const std::string& strPrefix);
365 
374 
375 namespace util {
376 
378 template <typename Tdst, typename Tsrc>
379 inline void insert(Tdst& dst, const Tsrc& src) {
380  dst.insert(dst.begin(), src.begin(), src.end());
381 }
382 template <typename TsetT, typename Tsrc>
383 inline void insert(std::set<TsetT>& dst, const Tsrc& src) {
384  dst.insert(src.begin(), src.end());
385 }
386 
387 #ifdef WIN32
388 class WinCmdLineArgs
389 {
390 public:
391  WinCmdLineArgs();
392  ~WinCmdLineArgs();
393  std::pair<int, char**> get();
394 
395 private:
396  int argc;
397  char** argv;
398  std::vector<std::string> args;
399 };
400 #endif
401 
402 } // namespace util
403 
404 #endif // BITCOIN_UTIL_SYSTEM_H
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:1215
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:1034
void SetupEnvironment()
Definition: system.cpp:1143
unsigned int m_flags
Definition: system.h:156
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:787
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:58
int m_line
Definition: system.h:127
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:144
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:971
const fs::path & GetBlocksDir()
Definition: system.cpp:717
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:642
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:1069
std::string m_name
Definition: system.h:125
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:679
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:120
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1046
const fs::path & GetDataDir(bool fNetSpecific=true)
Definition: system.cpp:742
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers, startup time.
Definition: system.cpp:1210
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:71
bool FileCommit(FILE *file)
Definition: system.cpp:1001
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes=0)
Definition: system.cpp:133
#define NODISCARD
Definition: attributes.h:18
#define LOCK(cs)
Definition: sync.h:180
const char * name
Definition: rest.cpp:39
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:967
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:637
bool CheckDataDirOption()
Definition: system.cpp:772
std::string m_file
Definition: system.h:126
CCriticalSection cs_args
Definition: system.h:159
UniValue help(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:132
void ClearArgs()
Clear available arguments.
Definition: system.h:286
std::string m_help_text
Definition: system.h:155
void TraceThread(const char *name, Callable func)
Definition: system.h:340
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: system.cpp:652
int flags
Definition: bitcoin-tx.cpp:509
Internal helper functions for ArgsManager.
Definition: system.cpp:166
not actually invalid
fs::path GetDefaultDataDir()
Definition: system.cpp:686
void ClearDatadirCache()
Tests only.
Definition: system.cpp:778
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:108
int ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1223
#define GUARDED_BY(x)
Definition: threadsafety.h:38
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: system.cpp:987
bool IsSwitchChar(char c)
Definition: system.h:96
OptionsCategory
Definition: system.h:105
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1197
std::string m_help_param
Definition: system.h:154
void insert(std::set< TsetT > &dst, const Tsrc &src)
Definition: system.h:383
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:656
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only=false)
Definition: system.cpp:84
ArgsManager gArgs
Definition: system.cpp:73
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:114
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1192
bool SetupNetworking()
Definition: system.cpp:1180