LCOV - code coverage report
Current view: top level - src/util - system.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 757 839 90.2 %
Date: 2022-04-21 14:51:19 Functions: 78 81 96.3 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 316 376 84.0 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2009-2010 Satoshi Nakamoto
#       2                 :            : // Copyright (c) 2009-2021 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                 :            : 
#       6                 :            : #include <util/system.h>
#       7                 :            : 
#       8                 :            : #ifdef ENABLE_EXTERNAL_SIGNER
#       9                 :            : #if defined(__GNUC__)
#      10                 :            : // Boost 1.78 requires the following workaround.
#      11                 :            : // See: https://github.com/boostorg/process/issues/235
#      12                 :            : #pragma GCC diagnostic push
#      13                 :            : #pragma GCC diagnostic ignored "-Wnarrowing"
#      14                 :            : #endif
#      15                 :            : #include <boost/process.hpp>
#      16                 :            : #if defined(__GNUC__)
#      17                 :            : #pragma GCC diagnostic pop
#      18                 :            : #endif
#      19                 :            : #endif // ENABLE_EXTERNAL_SIGNER
#      20                 :            : 
#      21                 :            : #include <chainparamsbase.h>
#      22                 :            : #include <fs.h>
#      23                 :            : #include <sync.h>
#      24                 :            : #include <util/check.h>
#      25                 :            : #include <util/getuniquepath.h>
#      26                 :            : #include <util/strencodings.h>
#      27                 :            : #include <util/string.h>
#      28                 :            : #include <util/translation.h>
#      29                 :            : 
#      30                 :            : 
#      31                 :            : #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
#      32                 :            : #include <pthread.h>
#      33                 :            : #include <pthread_np.h>
#      34                 :            : #endif
#      35                 :            : 
#      36                 :            : #ifndef WIN32
#      37                 :            : // for posix_fallocate, in configure.ac we check if it is present after this
#      38                 :            : #ifdef __linux__
#      39                 :            : 
#      40                 :            : #ifdef _POSIX_C_SOURCE
#      41                 :            : #undef _POSIX_C_SOURCE
#      42                 :            : #endif
#      43                 :            : 
#      44                 :            : #define _POSIX_C_SOURCE 200112L
#      45                 :            : 
#      46                 :            : #endif // __linux__
#      47                 :            : 
#      48                 :            : #include <algorithm>
#      49                 :            : #include <cassert>
#      50                 :            : #include <fcntl.h>
#      51                 :            : #include <sched.h>
#      52                 :            : #include <sys/resource.h>
#      53                 :            : #include <sys/stat.h>
#      54                 :            : 
#      55                 :            : #else
#      56                 :            : 
#      57                 :            : #ifdef _MSC_VER
#      58                 :            : #pragma warning(disable:4786)
#      59                 :            : #pragma warning(disable:4804)
#      60                 :            : #pragma warning(disable:4805)
#      61                 :            : #pragma warning(disable:4717)
#      62                 :            : #endif
#      63                 :            : 
#      64                 :            : #ifndef NOMINMAX
#      65                 :            : #define NOMINMAX
#      66                 :            : #endif
#      67                 :            : #include <codecvt>
#      68                 :            : 
#      69                 :            : #include <io.h> /* for _commit */
#      70                 :            : #include <shellapi.h>
#      71                 :            : #include <shlobj.h>
#      72                 :            : #endif
#      73                 :            : 
#      74                 :            : #ifdef HAVE_MALLOPT_ARENA_MAX
#      75                 :            : #include <malloc.h>
#      76                 :            : #endif
#      77                 :            : 
#      78                 :            : #include <boost/algorithm/string/replace.hpp>
#      79                 :            : #include <univalue.h>
#      80                 :            : 
#      81                 :            : #include <fstream>
#      82                 :            : #include <map>
#      83                 :            : #include <memory>
#      84                 :            : #include <optional>
#      85                 :            : #include <string>
#      86                 :            : #include <system_error>
#      87                 :            : #include <thread>
#      88                 :            : #include <typeinfo>
#      89                 :            : 
#      90                 :            : // Application startup time (used for uptime calculation)
#      91                 :            : const int64_t nStartupTime = GetTime();
#      92                 :            : 
#      93                 :            : const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
#      94                 :            : const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
#      95                 :            : 
#      96                 :            : ArgsManager gArgs;
#      97                 :            : 
#      98                 :            : /** Mutex to protect dir_locks. */
#      99                 :            : static Mutex cs_dir_locks;
#     100                 :            : /** A map that contains all the currently held directory locks. After
#     101                 :            :  * successful locking, these will be held here until the global destructor
#     102                 :            :  * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
#     103                 :            :  * is called.
#     104                 :            :  */
#     105                 :            : static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
#     106                 :            : 
#     107                 :            : bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
#     108                 :       2192 : {
#     109                 :       2192 :     LOCK(cs_dir_locks);
#     110                 :       2192 :     fs::path pathLockFile = directory / lockfile_name;
#     111                 :            : 
#     112                 :            :     // If a lock for this directory already exists in the map, don't try to re-lock it
#     113         [ +  + ]:       2192 :     if (dir_locks.count(fs::PathToString(pathLockFile))) {
#     114                 :          2 :         return true;
#     115                 :          2 :     }
#     116                 :            : 
#     117                 :            :     // Create empty lock file if it doesn't exist.
#     118                 :       2190 :     FILE* file = fsbridge::fopen(pathLockFile, "a");
#     119         [ +  + ]:       2190 :     if (file) fclose(file);
#     120                 :       2190 :     auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
#     121         [ +  + ]:       2190 :     if (!lock->TryLock()) {
#     122                 :         10 :         return error("Error while attempting to lock directory %s: %s", fs::PathToString(directory), lock->GetReason());
#     123                 :         10 :     }
#     124         [ +  + ]:       2180 :     if (!probe_only) {
#     125                 :            :         // Lock successful and we're not just probing, put it into the map
#     126                 :       1382 :         dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
#     127                 :       1382 :     }
#     128                 :       2180 :     return true;
#     129                 :       2190 : }
#     130                 :            : 
#     131                 :            : void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
#     132                 :        585 : {
#     133                 :        585 :     LOCK(cs_dir_locks);
#     134                 :        585 :     dir_locks.erase(fs::PathToString(directory / lockfile_name));
#     135                 :        585 : }
#     136                 :            : 
#     137                 :            : void ReleaseDirectoryLocks()
#     138                 :          3 : {
#     139                 :          3 :     LOCK(cs_dir_locks);
#     140                 :          3 :     dir_locks.clear();
#     141                 :          3 : }
#     142                 :            : 
#     143                 :            : bool DirIsWritable(const fs::path& directory)
#     144                 :       1592 : {
#     145                 :       1592 :     fs::path tmpFile = GetUniquePath(directory);
#     146                 :            : 
#     147                 :       1592 :     FILE* file = fsbridge::fopen(tmpFile, "a");
#     148         [ +  + ]:       1592 :     if (!file) return false;
#     149                 :            : 
#     150                 :       1591 :     fclose(file);
#     151                 :       1591 :     remove(tmpFile);
#     152                 :            : 
#     153                 :       1591 :     return true;
#     154                 :       1592 : }
#     155                 :            : 
#     156                 :            : bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
#     157                 :       5567 : {
#     158                 :       5567 :     constexpr uint64_t min_disk_space = 52428800; // 50 MiB
#     159                 :            : 
#     160                 :       5567 :     uint64_t free_bytes_available = fs::space(dir).available;
#     161                 :       5567 :     return free_bytes_available >= min_disk_space + additional_bytes;
#     162                 :       5567 : }
#     163                 :            : 
#     164                 :          0 : std::streampos GetFileSize(const char* path, std::streamsize max) {
#     165                 :          0 :     std::ifstream file{path, std::ios::binary};
#     166                 :          0 :     file.ignore(max);
#     167                 :          0 :     return file.gcount();
#     168                 :          0 : }
#     169                 :            : 
#     170                 :            : /**
#     171                 :            :  * Interpret a string argument as a boolean.
#     172                 :            :  *
#     173                 :            :  * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values
#     174                 :            :  * like "foo", return 0. This means that if a user unintentionally supplies a
#     175                 :            :  * non-integer argument here, the return value is always false. This means that
#     176                 :            :  * -foo=false does what the user probably expects, but -foo=true is well defined
#     177                 :            :  * but does not do what they probably expected.
#     178                 :            :  *
#     179                 :            :  * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not
#     180                 :            :  * representable as an int.
#     181                 :            :  *
#     182                 :            :  * For a more extensive discussion of this topic (and a wide range of opinions
#     183                 :            :  * on the Right Way to change this code), see PR12713.
#     184                 :            :  */
#     185                 :            : static bool InterpretBool(const std::string& strValue)
#     186                 :     153108 : {
#     187         [ +  + ]:     153108 :     if (strValue.empty())
#     188                 :      11673 :         return true;
#     189                 :     141435 :     return (LocaleIndependentAtoi<int>(strValue) != 0);
#     190                 :     153108 : }
#     191                 :            : 
#     192                 :            : static std::string SettingName(const std::string& arg)
#     193                 :    2337606 : {
#     194 [ +  - ][ +  + ]:    2337606 :     return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
#     195                 :    2337606 : }
#     196                 :            : 
#     197                 :            : struct KeyInfo {
#     198                 :            :     std::string name;
#     199                 :            :     std::string section;
#     200                 :            :     bool negated{false};
#     201                 :            : };
#     202                 :            : 
#     203                 :            : /**
#     204                 :            :  * Parse "name", "section.name", "noname", "section.noname" settings keys.
#     205                 :            :  *
#     206                 :            :  * @note Where an option was negated can be later checked using the
#     207                 :            :  * IsArgNegated() method. One use case for this is to have a way to disable
#     208                 :            :  * options that are not normally boolean (e.g. using -nodebuglogfile to request
#     209                 :            :  * that debug log output is not sent to any file at all).
#     210                 :            :  */
#     211                 :            : KeyInfo InterpretKey(std::string key)
#     212                 :     408041 : {
#     213                 :     408041 :     KeyInfo result;
#     214                 :            :     // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
#     215                 :     408041 :     size_t option_index = key.find('.');
#     216         [ +  + ]:     408041 :     if (option_index != std::string::npos) {
#     217                 :     140046 :         result.section = key.substr(0, option_index);
#     218                 :     140046 :         key.erase(0, option_index + 1);
#     219                 :     140046 :     }
#     220         [ +  + ]:     408041 :     if (key.substr(0, 2) == "no") {
#     221                 :     117707 :         key.erase(0, 2);
#     222                 :     117707 :         result.negated = true;
#     223                 :     117707 :     }
#     224                 :     408041 :     result.name = key;
#     225                 :     408041 :     return result;
#     226                 :     408041 : }
#     227                 :            : 
#     228                 :            : /**
#     229                 :            :  * Interpret settings value based on registered flags.
#     230                 :            :  *
#     231                 :            :  * @param[in]   key      key information to know if key was negated
#     232                 :            :  * @param[in]   value    string value of setting to be parsed
#     233                 :            :  * @param[in]   flags    ArgsManager registered argument flags
#     234                 :            :  * @param[out]  error    Error description if settings value is not valid
#     235                 :            :  *
#     236                 :            :  * @return parsed settings value if it is valid, otherwise nullopt accompanied
#     237                 :            :  * by a descriptive error string
#     238                 :            :  */
#     239                 :            : static std::optional<util::SettingsValue> InterpretValue(const KeyInfo& key, const std::string& value,
#     240                 :            :                                                          unsigned int flags, std::string& error)
#     241                 :     385883 : {
#     242                 :            :     // Return negated settings as false values.
#     243         [ +  + ]:     385883 :     if (key.negated) {
#     244         [ -  + ]:     117707 :         if (flags & ArgsManager::DISALLOW_NEGATION) {
#     245                 :          0 :             error = strprintf("Negating of -%s is meaningless and therefore forbidden", key.name);
#     246                 :          0 :             return std::nullopt;
#     247                 :          0 :         }
#     248                 :            :         // Double negatives like -nofoo=0 are supported (but discouraged)
#     249         [ +  + ]:     117707 :         if (!InterpretBool(value)) {
#     250                 :         16 :             LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key.name, value);
#     251                 :         16 :             return true;
#     252                 :         16 :         }
#     253                 :     117691 :         return false;
#     254                 :     117707 :     }
#     255                 :     268176 :     return value;
#     256                 :     385883 : }
#     257                 :            : 
#     258                 :            : // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
#     259                 :            : // #include class definitions for all members.
#     260                 :            : // For example, m_settings has an internal dependency on univalue.
#     261                 :      59402 : ArgsManager::ArgsManager() {}
#     262                 :      57131 : ArgsManager::~ArgsManager() {}
#     263                 :            : 
#     264                 :            : const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
#     265                 :      55064 : {
#     266                 :      55064 :     std::set<std::string> unsuitables;
#     267                 :            : 
#     268                 :      55064 :     LOCK(cs_args);
#     269                 :            : 
#     270                 :            :     // if there's no section selected, don't worry
#     271         [ -  + ]:      55064 :     if (m_network.empty()) return std::set<std::string> {};
#     272                 :            : 
#     273                 :            :     // if it's okay to use the default section for this network, don't worry
#     274         [ +  + ]:      55064 :     if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
#     275                 :            : 
#     276         [ +  + ]:      36519 :     for (const auto& arg : m_network_only_args) {
#     277         [ +  + ]:      25016 :         if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
#     278                 :       1693 :             unsuitables.insert(arg);
#     279                 :       1693 :         }
#     280                 :      25016 :     }
#     281                 :      36519 :     return unsuitables;
#     282                 :      55064 : }
#     283                 :            : 
#     284                 :            : const std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
#     285                 :       1639 : {
#     286                 :            :     // Section names to be recognized in the config file.
#     287                 :       1639 :     static const std::set<std::string> available_sections{
#     288                 :       1639 :         CBaseChainParams::REGTEST,
#     289                 :       1639 :         CBaseChainParams::SIGNET,
#     290                 :       1639 :         CBaseChainParams::TESTNET,
#     291                 :       1639 :         CBaseChainParams::MAIN
#     292                 :       1639 :     };
#     293                 :            : 
#     294                 :       1639 :     LOCK(cs_args);
#     295                 :       1639 :     std::list<SectionInfo> unrecognized = m_config_sections;
#     296                 :       1639 :     unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
#     297                 :       1639 :     return unrecognized;
#     298                 :       1639 : }
#     299                 :            : 
#     300                 :            : void ArgsManager::SelectConfigNetwork(const std::string& network)
#     301                 :       3934 : {
#     302                 :       3934 :     LOCK(cs_args);
#     303                 :       3934 :     m_network = network;
#     304                 :       3934 : }
#     305                 :            : 
#     306                 :            : bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
#     307                 :      59518 : {
#     308                 :      59518 :     LOCK(cs_args);
#     309                 :      59518 :     m_settings.command_line_options.clear();
#     310                 :            : 
#     311         [ +  + ]:     217340 :     for (int i = 1; i < argc; i++) {
#     312                 :     159237 :         std::string key(argv[i]);
#     313                 :            : 
#     314                 :            : #ifdef MAC_OSX
#     315                 :            :         // At the first time when a user gets the "App downloaded from the
#     316                 :            :         // internet" warning, and clicks the Open button, macOS passes
#     317                 :            :         // a unique process serial number (PSN) as -psn_... command-line
#     318                 :            :         // argument, which we filter out.
#     319                 :            :         if (key.substr(0, 5) == "-psn_") continue;
#     320                 :            : #endif
#     321                 :            : 
#     322         [ -  + ]:     159237 :         if (key == "-") break; //bitcoin-tx using stdin
#     323                 :     159237 :         std::string val;
#     324                 :     159237 :         size_t is_index = key.find('=');
#     325         [ +  + ]:     159237 :         if (is_index != std::string::npos) {
#     326                 :     150812 :             val = key.substr(is_index + 1);
#     327                 :     150812 :             key.erase(is_index);
#     328                 :     150812 :         }
#     329                 :            : #ifdef WIN32
#     330                 :            :         key = ToLower(key);
#     331                 :            :         if (key[0] == '/')
#     332                 :            :             key[0] = '-';
#     333                 :            : #endif
#     334                 :            : 
#     335         [ +  + ]:     159237 :         if (key[0] != '-') {
#     336 [ +  + ][ +  - ]:       1404 :             if (!m_accept_any_command && m_command.empty()) {
#     337                 :            :                 // The first non-dash arg is a registered command
#     338                 :         63 :                 std::optional<unsigned int> flags = GetArgFlags(key);
#     339 [ +  + ][ -  + ]:         63 :                 if (!flags || !(*flags & ArgsManager::COMMAND)) {
#     340                 :          4 :                     error = strprintf("Invalid command '%s'", argv[i]);
#     341                 :          4 :                     return false;
#     342                 :          4 :                 }
#     343                 :         63 :             }
#     344                 :       1400 :             m_command.push_back(key);
#     345         [ +  + ]:       2048 :             while (++i < argc) {
#     346                 :            :                 // The remaining args are command args
#     347                 :        648 :                 m_command.push_back(argv[i]);
#     348                 :        648 :             }
#     349                 :       1400 :             break;
#     350                 :       1404 :         }
#     351                 :            : 
#     352                 :            :         // Transform --foo to -foo
#     353 [ +  - ][ +  + ]:     157833 :         if (key.length() > 1 && key[1] == '-')
#     354                 :         12 :             key.erase(0, 1);
#     355                 :            : 
#     356                 :            :         // Transform -foo to foo
#     357                 :     157833 :         key.erase(0, 1);
#     358                 :     157833 :         KeyInfo keyinfo = InterpretKey(key);
#     359                 :     157833 :         std::optional<unsigned int> flags = GetArgFlags('-' + keyinfo.name);
#     360                 :            : 
#     361                 :            :         // Unknown command line options and command line options with dot
#     362                 :            :         // characters (which are returned from InterpretKey with nonempty
#     363                 :            :         // section strings) are not valid.
#     364 [ +  + ][ +  + ]:     157833 :         if (!flags || !keyinfo.section.empty()) {
#     365                 :         11 :             error = strprintf("Invalid parameter %s", argv[i]);
#     366                 :         11 :             return false;
#     367                 :         11 :         }
#     368                 :            : 
#     369                 :     157822 :         std::optional<util::SettingsValue> value = InterpretValue(keyinfo, val, *flags, error);
#     370         [ -  + ]:     157822 :         if (!value) return false;
#     371                 :            : 
#     372                 :     157822 :         m_settings.command_line_options[keyinfo.name].push_back(*value);
#     373                 :     157822 :     }
#     374                 :            : 
#     375                 :            :     // we do not allow -includeconf from command line, only -noincludeconf
#     376         [ +  + ]:      59503 :     if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
#     377                 :          8 :         const util::SettingsSpan values{*includes};
#     378                 :            :         // Range may be empty if -noincludeconf was passed
#     379         [ +  + ]:          8 :         if (!values.empty()) {
#     380                 :          6 :             error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write();
#     381                 :          6 :             return false; // pick first value as example
#     382                 :          6 :         }
#     383                 :          8 :     }
#     384                 :      59497 :     return true;
#     385                 :      59503 : }
#     386                 :            : 
#     387                 :            : std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
#     388                 :     429544 : {
#     389                 :     429544 :     LOCK(cs_args);
#     390         [ +  + ]:     657915 :     for (const auto& arg_map : m_available_args) {
#     391                 :     657915 :         const auto search = arg_map.second.find(name);
#     392         [ +  + ]:     657915 :         if (search != arg_map.second.end()) {
#     393                 :     407547 :             return search->second.m_flags;
#     394                 :     407547 :         }
#     395                 :     657915 :     }
#     396                 :      21997 :     return std::nullopt;
#     397                 :     429544 : }
#     398                 :            : 
#     399                 :            : fs::path ArgsManager::GetPathArg(std::string arg, const fs::path& default_value) const
#     400                 :      19440 : {
#     401         [ +  + ]:      19440 :     if (IsArgNegated(arg)) return fs::path{};
#     402                 :      19435 :     std::string path_str = GetArg(arg, "");
#     403         [ +  + ]:      19435 :     if (path_str.empty()) return default_value;
#     404                 :      12497 :     fs::path result = fs::PathFromString(path_str).lexically_normal();
#     405                 :            :     // Remove trailing slash, if present.
#     406         [ +  + ]:      12497 :     return result.has_filename() ? result : result.parent_path();
#     407                 :      19435 : }
#     408                 :            : 
#     409                 :            : const fs::path& ArgsManager::GetBlocksDirPath() const
#     410                 :     409842 : {
#     411                 :     409842 :     LOCK(cs_args);
#     412                 :     409842 :     fs::path& path = m_cached_blocks_path;
#     413                 :            : 
#     414                 :            :     // Cache the path to avoid calling fs::create_directories on every call of
#     415                 :            :     // this function
#     416         [ +  + ]:     409842 :     if (!path.empty()) return path;
#     417                 :            : 
#     418         [ +  + ]:       1638 :     if (IsArgSet("-blocksdir")) {
#     419                 :          2 :         path = fs::absolute(GetPathArg("-blocksdir"));
#     420         [ +  + ]:          2 :         if (!fs::is_directory(path)) {
#     421                 :          1 :             path = "";
#     422                 :          1 :             return path;
#     423                 :          1 :         }
#     424                 :       1636 :     } else {
#     425                 :       1636 :         path = GetDataDirBase();
#     426                 :       1636 :     }
#     427                 :            : 
#     428                 :       1637 :     path /= fs::PathFromString(BaseParams().DataDir());
#     429                 :       1637 :     path /= "blocks";
#     430                 :       1637 :     fs::create_directories(path);
#     431                 :       1637 :     return path;
#     432                 :       1638 : }
#     433                 :            : 
#     434                 :            : const fs::path& ArgsManager::GetDataDir(bool net_specific) const
#     435                 :      32728 : {
#     436                 :      32728 :     LOCK(cs_args);
#     437         [ +  + ]:      32728 :     fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path;
#     438                 :            : 
#     439                 :            :     // Cache the path to avoid calling fs::create_directories on every call of
#     440                 :            :     // this function
#     441         [ +  + ]:      32728 :     if (!path.empty()) return path;
#     442                 :            : 
#     443                 :       7155 :     const fs::path datadir{GetPathArg("-datadir")};
#     444         [ +  - ]:       7155 :     if (!datadir.empty()) {
#     445                 :       7155 :         path = fs::absolute(datadir);
#     446         [ -  + ]:       7155 :         if (!fs::is_directory(path)) {
#     447                 :          0 :             path = "";
#     448                 :          0 :             return path;
#     449                 :          0 :         }
#     450                 :       7155 :     } else {
#     451                 :          0 :         path = GetDefaultDataDir();
#     452                 :          0 :     }
#     453                 :            : 
#     454         [ -  + ]:       7155 :     if (!fs::exists(path)) {
#     455                 :          0 :         fs::create_directories(path / "wallets");
#     456                 :          0 :     }
#     457                 :            : 
#     458 [ +  + ][ +  + ]:       7155 :     if (net_specific && !BaseParams().DataDir().empty()) {
#     459                 :       2324 :         path /= fs::PathFromString(BaseParams().DataDir());
#     460         [ +  + ]:       2324 :         if (!fs::exists(path)) {
#     461                 :        352 :             fs::create_directories(path / "wallets");
#     462                 :        352 :         }
#     463                 :       2324 :     }
#     464                 :            : 
#     465                 :       7155 :     return path;
#     466                 :       7155 : }
#     467                 :            : 
#     468                 :            : void ArgsManager::ClearPathCache()
#     469                 :       3030 : {
#     470                 :       3030 :     LOCK(cs_args);
#     471                 :            : 
#     472                 :       3030 :     m_cached_datadir_path = fs::path();
#     473                 :       3030 :     m_cached_network_datadir_path = fs::path();
#     474                 :       3030 :     m_cached_blocks_path = fs::path();
#     475                 :       3030 : }
#     476                 :            : 
#     477                 :            : std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const
#     478                 :         61 : {
#     479                 :         61 :     Command ret;
#     480                 :         61 :     LOCK(cs_args);
#     481                 :         61 :     auto it = m_command.begin();
#     482         [ +  + ]:         61 :     if (it == m_command.end()) {
#     483                 :            :         // No command was passed
#     484                 :          2 :         return std::nullopt;
#     485                 :          2 :     }
#     486         [ +  - ]:         59 :     if (!m_accept_any_command) {
#     487                 :            :         // The registered command
#     488                 :         59 :         ret.command = *(it++);
#     489                 :         59 :     }
#     490         [ +  + ]:         63 :     while (it != m_command.end()) {
#     491                 :            :         // The unregistered command and args (if any)
#     492                 :          4 :         ret.args.push_back(*(it++));
#     493                 :          4 :     }
#     494                 :         59 :     return ret;
#     495                 :         61 : }
#     496                 :            : 
#     497                 :            : std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
#     498                 :      76581 : {
#     499                 :      76581 :     std::vector<std::string> result;
#     500         [ +  + ]:      99967 :     for (const util::SettingsValue& value : GetSettingsList(strArg)) {
#     501 [ -  + ][ +  + ]:      99967 :         result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
#     502                 :      99967 :     }
#     503                 :      76581 :     return result;
#     504                 :      76581 : }
#     505                 :            : 
#     506                 :            : bool ArgsManager::IsArgSet(const std::string& strArg) const
#     507                 :     207735 : {
#     508                 :     207735 :     return !GetSetting(strArg).isNull();
#     509                 :     207735 : }
#     510                 :            : 
#     511                 :            : bool ArgsManager::InitSettings(std::string& error)
#     512                 :        804 : {
#     513         [ +  + ]:        804 :     if (!GetSettingsPath()) {
#     514                 :          2 :         return true; // Do nothing if settings file disabled.
#     515                 :          2 :     }
#     516                 :            : 
#     517                 :        802 :     std::vector<std::string> errors;
#     518         [ +  + ]:        802 :     if (!ReadSettingsFile(&errors)) {
#     519                 :          3 :         error = strprintf("Failed loading settings file:\n%s\n", MakeUnorderedList(errors));
#     520                 :          3 :         return false;
#     521                 :          3 :     }
#     522         [ -  + ]:        799 :     if (!WriteSettingsFile(&errors)) {
#     523                 :          0 :         error = strprintf("Failed saving settings file:\n%s\n", MakeUnorderedList(errors));
#     524                 :          0 :         return false;
#     525                 :          0 :     }
#     526                 :        799 :     return true;
#     527                 :        799 : }
#     528                 :            : 
#     529                 :            : bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp) const
#     530                 :       3708 : {
#     531                 :       3708 :     fs::path settings = GetPathArg("-settings", fs::path{BITCOIN_SETTINGS_FILENAME});
#     532         [ +  + ]:       3708 :     if (settings.empty()) {
#     533                 :          2 :         return false;
#     534                 :          2 :     }
#     535         [ +  + ]:       3706 :     if (filepath) {
#     536         [ +  + ]:       2904 :         *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings);
#     537                 :       2904 :     }
#     538                 :       3706 :     return true;
#     539                 :       3708 : }
#     540                 :            : 
#     541                 :            : static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
#     542                 :          5 : {
#     543         [ +  + ]:          5 :     for (const auto& error : errors) {
#     544         [ +  + ]:          5 :         if (error_out) {
#     545                 :          3 :             error_out->emplace_back(error);
#     546                 :          3 :         } else {
#     547                 :          2 :             LogPrintf("%s\n", error);
#     548                 :          2 :         }
#     549                 :          5 :     }
#     550                 :          5 : }
#     551                 :            : 
#     552                 :            : bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
#     553                 :        804 : {
#     554                 :        804 :     fs::path path;
#     555         [ -  + ]:        804 :     if (!GetSettingsPath(&path, /* temp= */ false)) {
#     556                 :          0 :         return true; // Do nothing if settings file disabled.
#     557                 :          0 :     }
#     558                 :            : 
#     559                 :        804 :     LOCK(cs_args);
#     560                 :        804 :     m_settings.rw_settings.clear();
#     561                 :        804 :     std::vector<std::string> read_errors;
#     562         [ +  + ]:        804 :     if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) {
#     563                 :          3 :         SaveErrors(read_errors, errors);
#     564                 :          3 :         return false;
#     565                 :          3 :     }
#     566         [ +  + ]:        801 :     for (const auto& setting : m_settings.rw_settings) {
#     567                 :        178 :         KeyInfo key = InterpretKey(setting.first); // Split setting key into section and argname
#     568         [ +  + ]:        178 :         if (!GetArgFlags('-' + key.name)) {
#     569                 :          8 :             LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
#     570                 :          8 :         }
#     571                 :        178 :     }
#     572                 :        801 :     return true;
#     573                 :        804 : }
#     574                 :            : 
#     575                 :            : bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors) const
#     576                 :       1050 : {
#     577                 :       1050 :     fs::path path, path_tmp;
#     578 [ -  + ][ -  + ]:       1050 :     if (!GetSettingsPath(&path, /* temp= */ false) || !GetSettingsPath(&path_tmp, /* temp= */ true)) {
#     579                 :          0 :         throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
#     580                 :          0 :     }
#     581                 :            : 
#     582                 :       1050 :     LOCK(cs_args);
#     583                 :       1050 :     std::vector<std::string> write_errors;
#     584         [ -  + ]:       1050 :     if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
#     585                 :          0 :         SaveErrors(write_errors, errors);
#     586                 :          0 :         return false;
#     587                 :          0 :     }
#     588         [ +  + ]:       1050 :     if (!RenameOver(path_tmp, path)) {
#     589                 :          2 :         SaveErrors({strprintf("Failed renaming settings file %s to %s\n", fs::PathToString(path_tmp), fs::PathToString(path))}, errors);
#     590                 :          2 :         return false;
#     591                 :          2 :     }
#     592                 :       1048 :     return true;
#     593                 :       1050 : }
#     594                 :            : 
#     595                 :            : util::SettingsValue ArgsManager::GetPersistentSetting(const std::string& name) const
#     596                 :        120 : {
#     597                 :        120 :     LOCK(cs_args);
#     598                 :        120 :     return util::GetSetting(m_settings, m_network, name, !UseDefaultSection("-" + name),
#     599                 :        120 :         /*ignore_nonpersistent=*/true, /*get_chain_name=*/false);
#     600                 :        120 : }
#     601                 :            : 
#     602                 :            : bool ArgsManager::IsArgNegated(const std::string& strArg) const
#     603                 :      74537 : {
#     604                 :      74537 :     return GetSetting(strArg).isFalse();
#     605                 :      74537 : }
#     606                 :            : 
#     607                 :            : std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
#     608                 :     153816 : {
#     609                 :     153816 :     const util::SettingsValue value = GetSetting(strArg);
#     610                 :     153816 :     return SettingToString(value, strDefault);
#     611                 :     153816 : }
#     612                 :            : 
#     613                 :            : std::string SettingToString(const util::SettingsValue& value, const std::string& strDefault)
#     614                 :     153864 : {
#     615 [ +  + ][ +  + ]:     153864 :     return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.isNum() ? value.getValStr() : value.get_str();
#         [ +  + ][ +  + ]
#     616                 :     153864 : }
#     617                 :            : 
#     618                 :            : int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const
#     619                 :    1050689 : {
#     620                 :    1050689 :     const util::SettingsValue value = GetSetting(strArg);
#     621                 :    1050689 :     return SettingToInt(value, nDefault);
#     622                 :    1050689 : }
#     623                 :            : 
#     624                 :            : int64_t SettingToInt(const util::SettingsValue& value, int64_t nDefault)
#     625                 :    1050717 : {
#     626 [ +  + ][ +  + ]:    1050717 :     return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : LocaleIndependentAtoi<int64_t>(value.get_str());
#         [ +  + ][ +  + ]
#     627                 :    1050717 : }
#     628                 :            : 
#     629                 :            : bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
#     630                 :     657858 : {
#     631                 :     657858 :     const util::SettingsValue value = GetSetting(strArg);
#     632                 :     657858 :     return SettingToBool(value, fDefault);
#     633                 :     657858 : }
#     634                 :            : 
#     635                 :            : bool SettingToBool(const util::SettingsValue& value, bool fDefault)
#     636                 :     657891 : {
#     637 [ +  + ][ +  + ]:     657891 :     return value.isNull() ? fDefault : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
#     638                 :     657891 : }
#     639                 :            : 
#     640                 :            : bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
#     641                 :      56690 : {
#     642                 :      56690 :     LOCK(cs_args);
#     643         [ +  + ]:      56690 :     if (IsArgSet(strArg)) return false;
#     644                 :       1570 :     ForceSetArg(strArg, strValue);
#     645                 :       1570 :     return true;
#     646                 :      56690 : }
#     647                 :            : 
#     648                 :            : bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
#     649                 :       3264 : {
#     650         [ +  + ]:       3264 :     if (fValue)
#     651                 :       1603 :         return SoftSetArg(strArg, std::string("1"));
#     652                 :       1661 :     else
#     653                 :       1661 :         return SoftSetArg(strArg, std::string("0"));
#     654                 :       3264 : }
#     655                 :            : 
#     656                 :            : void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
#     657                 :      56736 : {
#     658                 :      56736 :     LOCK(cs_args);
#     659                 :      56736 :     m_settings.forced_settings[SettingName(strArg)] = strValue;
#     660                 :      56736 : }
#     661                 :            : 
#     662                 :            : void ArgsManager::AddCommand(const std::string& cmd, const std::string& help)
#     663                 :        327 : {
#     664                 :        327 :     Assert(cmd.find('=') == std::string::npos);
#     665                 :        327 :     Assert(cmd.at(0) != '-');
#     666                 :            : 
#     667                 :        327 :     LOCK(cs_args);
#     668                 :        327 :     m_accept_any_command = false; // latch to false
#     669                 :        327 :     std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS];
#     670                 :        327 :     auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND});
#     671                 :        327 :     Assert(ret.second); // Fail on duplicate commands
#     672                 :        327 : }
#     673                 :            : 
#     674                 :            : void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
#     675                 :     410206 : {
#     676                 :     410206 :     Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand
#     677                 :            : 
#     678                 :            :     // Split arg name from its help param
#     679                 :     410206 :     size_t eq_index = name.find('=');
#     680         [ +  + ]:     410206 :     if (eq_index == std::string::npos) {
#     681                 :     219244 :         eq_index = name.size();
#     682                 :     219244 :     }
#     683                 :     410206 :     std::string arg_name = name.substr(0, eq_index);
#     684                 :            : 
#     685                 :     410206 :     LOCK(cs_args);
#     686                 :     410206 :     std::map<std::string, Arg>& arg_map = m_available_args[cat];
#     687                 :     410206 :     auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
#     688                 :     410206 :     assert(ret.second); // Make sure an insertion actually happened
#     689                 :            : 
#     690         [ +  + ]:     410206 :     if (flags & ArgsManager::NETWORK_ONLY) {
#     691                 :      14736 :         m_network_only_args.emplace(arg_name);
#     692                 :      14736 :     }
#     693                 :     410206 : }
#     694                 :            : 
#     695                 :            : void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
#     696                 :       8090 : {
#     697         [ +  + ]:      39448 :     for (const std::string& name : names) {
#     698                 :      39448 :         AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
#     699                 :      39448 :     }
#     700                 :       8090 : }
#     701                 :            : 
#     702                 :            : std::string ArgsManager::GetHelpMessage() const
#     703                 :          2 : {
#     704                 :          2 :     const bool show_debug = GetBoolArg("-help-debug", false);
#     705                 :            : 
#     706                 :          2 :     std::string usage = "";
#     707                 :          2 :     LOCK(cs_args);
#     708         [ +  + ]:         10 :     for (const auto& arg_map : m_available_args) {
#     709                 :         10 :         switch(arg_map.first) {
#     710         [ +  + ]:          1 :             case OptionsCategory::OPTIONS:
#     711                 :          1 :                 usage += HelpMessageGroup("Options:");
#     712                 :          1 :                 break;
#     713         [ +  + ]:          1 :             case OptionsCategory::CONNECTION:
#     714                 :          1 :                 usage += HelpMessageGroup("Connection options:");
#     715                 :          1 :                 break;
#     716         [ -  + ]:          0 :             case OptionsCategory::ZMQ:
#     717                 :          0 :                 usage += HelpMessageGroup("ZeroMQ notification options:");
#     718                 :          0 :                 break;
#     719         [ +  + ]:          1 :             case OptionsCategory::DEBUG_TEST:
#     720                 :          1 :                 usage += HelpMessageGroup("Debugging/Testing options:");
#     721                 :          1 :                 break;
#     722         [ +  + ]:          1 :             case OptionsCategory::NODE_RELAY:
#     723                 :          1 :                 usage += HelpMessageGroup("Node relay options:");
#     724                 :          1 :                 break;
#     725         [ +  + ]:          1 :             case OptionsCategory::BLOCK_CREATION:
#     726                 :          1 :                 usage += HelpMessageGroup("Block creation options:");
#     727                 :          1 :                 break;
#     728         [ +  + ]:          1 :             case OptionsCategory::RPC:
#     729                 :          1 :                 usage += HelpMessageGroup("RPC server options:");
#     730                 :          1 :                 break;
#     731         [ +  + ]:          1 :             case OptionsCategory::WALLET:
#     732                 :          1 :                 usage += HelpMessageGroup("Wallet options:");
#     733                 :          1 :                 break;
#     734         [ +  + ]:          1 :             case OptionsCategory::WALLET_DEBUG_TEST:
#     735         [ -  + ]:          1 :                 if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
#     736                 :          1 :                 break;
#     737         [ +  + ]:          1 :             case OptionsCategory::CHAINPARAMS:
#     738                 :          1 :                 usage += HelpMessageGroup("Chain selection options:");
#     739                 :          1 :                 break;
#     740         [ -  + ]:          0 :             case OptionsCategory::GUI:
#     741                 :          0 :                 usage += HelpMessageGroup("UI Options:");
#     742                 :          0 :                 break;
#     743         [ -  + ]:          0 :             case OptionsCategory::COMMANDS:
#     744                 :          0 :                 usage += HelpMessageGroup("Commands:");
#     745                 :          0 :                 break;
#     746         [ -  + ]:          0 :             case OptionsCategory::REGISTER_COMMANDS:
#     747                 :          0 :                 usage += HelpMessageGroup("Register Commands:");
#     748                 :          0 :                 break;
#     749         [ +  + ]:          1 :             default:
#     750                 :          1 :                 break;
#     751                 :         10 :         }
#     752                 :            : 
#     753                 :            :         // When we get to the hidden options, stop
#     754         [ +  + ]:         10 :         if (arg_map.first == OptionsCategory::HIDDEN) break;
#     755                 :            : 
#     756         [ +  + ]:        162 :         for (const auto& arg : arg_map.second) {
#     757 [ -  + ][ +  + ]:        162 :             if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
#     758                 :        124 :                 std::string name;
#     759         [ +  + ]:        124 :                 if (arg.second.m_help_param.empty()) {
#     760                 :         54 :                     name = arg.first;
#     761                 :         70 :                 } else {
#     762                 :         70 :                     name = arg.first + arg.second.m_help_param;
#     763                 :         70 :                 }
#     764                 :        124 :                 usage += HelpMessageOpt(name, arg.second.m_help_text);
#     765                 :        124 :             }
#     766                 :        162 :         }
#     767                 :          9 :     }
#     768                 :          2 :     return usage;
#     769                 :          2 : }
#     770                 :            : 
#     771                 :            : bool HelpRequested(const ArgsManager& args)
#     772                 :       2254 : {
#     773 [ -  + ][ +  + ]:       2254 :     return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
#         [ -  + ][ -  + ]
#     774                 :       2254 : }
#     775                 :            : 
#     776                 :            : void SetupHelpOptions(ArgsManager& args)
#     777                 :       3104 : {
#     778                 :       3104 :     args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#     779                 :       3104 :     args.AddHiddenArgs({"-h", "-help"});
#     780                 :       3104 : }
#     781                 :            : 
#     782                 :            : static const int screenWidth = 79;
#     783                 :            : static const int optIndent = 2;
#     784                 :            : static const int msgIndent = 7;
#     785                 :            : 
#     786                 :          8 : std::string HelpMessageGroup(const std::string &message) {
#     787                 :          8 :     return std::string(message) + std::string("\n\n");
#     788                 :          8 : }
#     789                 :            : 
#     790                 :        124 : std::string HelpMessageOpt(const std::string &option, const std::string &message) {
#     791                 :        124 :     return std::string(optIndent,' ') + std::string(option) +
#     792                 :        124 :            std::string("\n") + std::string(msgIndent,' ') +
#     793                 :        124 :            FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
#     794                 :        124 :            std::string("\n\n");
#     795                 :        124 : }
#     796                 :            : 
#     797                 :            : static std::string FormatException(const std::exception* pex, const char* pszThread)
#     798                 :          0 : {
#     799                 :            : #ifdef WIN32
#     800                 :            :     char pszModule[MAX_PATH] = "";
#     801                 :            :     GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
#     802                 :            : #else
#     803                 :          0 :     const char* pszModule = "bitcoin";
#     804                 :          0 : #endif
#     805         [ #  # ]:          0 :     if (pex)
#     806                 :          0 :         return strprintf(
#     807                 :          0 :             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
#     808                 :          0 :     else
#     809                 :          0 :         return strprintf(
#     810                 :          0 :             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
#     811                 :          0 : }
#     812                 :            : 
#     813                 :            : void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
#     814                 :          0 : {
#     815                 :          0 :     std::string message = FormatException(pex, pszThread);
#     816                 :          0 :     LogPrintf("\n\n************************\n%s\n", message);
#     817                 :          0 :     tfm::format(std::cerr, "\n\n************************\n%s\n", message);
#     818                 :          0 : }
#     819                 :            : 
#     820                 :            : fs::path GetDefaultDataDir()
#     821                 :        793 : {
#     822                 :            :     // Windows: C:\Users\Username\AppData\Roaming\Bitcoin
#     823                 :            :     // macOS: ~/Library/Application Support/Bitcoin
#     824                 :            :     // Unix-like: ~/.bitcoin
#     825                 :            : #ifdef WIN32
#     826                 :            :     // Windows
#     827                 :            :     return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
#     828                 :            : #else
#     829                 :        793 :     fs::path pathRet;
#     830                 :        793 :     char* pszHome = getenv("HOME");
#     831 [ -  + ][ -  + ]:        793 :     if (pszHome == nullptr || strlen(pszHome) == 0)
#     832                 :          0 :         pathRet = fs::path("/");
#     833                 :        793 :     else
#     834                 :        793 :         pathRet = fs::path(pszHome);
#     835                 :            : #ifdef MAC_OSX
#     836                 :            :     // macOS
#     837                 :            :     return pathRet / "Library/Application Support/Bitcoin";
#     838                 :            : #else
#     839                 :            :     // Unix-like
#     840                 :        793 :     return pathRet / ".bitcoin";
#     841                 :        793 : #endif
#     842                 :        793 : #endif
#     843                 :        793 : }
#     844                 :            : 
#     845                 :            : bool CheckDataDirOption()
#     846                 :       4429 : {
#     847                 :       4429 :     const fs::path datadir{gArgs.GetPathArg("-datadir")};
#     848 [ +  + ][ +  + ]:       4429 :     return datadir.empty() || fs::is_directory(fs::absolute(datadir));
#     849                 :       4429 : }
#     850                 :            : 
#     851                 :            : fs::path GetConfigFile(const std::string& confPath)
#     852                 :       3005 : {
#     853                 :       3005 :     return AbsPathForConfigVal(fs::PathFromString(confPath), false);
#     854                 :       3005 : }
#     855                 :            : 
#     856                 :            : static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
#     857                 :      58397 : {
#     858                 :      58397 :     std::string str, prefix;
#     859                 :      58397 :     std::string::size_type pos;
#     860                 :      58397 :     int linenr = 1;
#     861         [ +  + ]:     310648 :     while (std::getline(stream, str)) {
#     862                 :     252256 :         bool used_hash = false;
#     863         [ +  + ]:     252256 :         if ((pos = str.find('#')) != std::string::npos) {
#     864                 :          3 :             str = str.substr(0, pos);
#     865                 :          3 :             used_hash = true;
#     866                 :          3 :         }
#     867                 :     252256 :         const static std::string pattern = " \t\r\n";
#     868                 :     252256 :         str = TrimString(str, pattern);
#     869         [ +  + ]:     252256 :         if (!str.empty()) {
#     870 [ +  + ][ +  + ]:     252253 :             if (*str.begin() == '[' && *str.rbegin() == ']') {
#                 [ +  - ]
#     871                 :       2212 :                 const std::string section = str.substr(1, str.size() - 2);
#     872                 :       2212 :                 sections.emplace_back(SectionInfo{section, filepath, linenr});
#     873                 :       2212 :                 prefix = section + '.';
#     874         [ +  + ]:     250041 :             } else if (*str.begin() == '-') {
#     875                 :          1 :                 error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
#     876                 :          1 :                 return false;
#     877         [ +  + ]:     250040 :             } else if ((pos = str.find('=')) != std::string::npos) {
#     878                 :     250039 :                 std::string name = prefix + TrimString(str.substr(0, pos), pattern);
#     879                 :     250039 :                 std::string value = TrimString(str.substr(pos + 1), pattern);
#     880 [ +  + ][ +  - ]:     250039 :                 if (used_hash && name.find("rpcpassword") != std::string::npos) {
#     881                 :          3 :                     error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
#     882                 :          3 :                     return false;
#     883                 :          3 :                 }
#     884                 :     250036 :                 options.emplace_back(name, value);
#     885 [ +  + ][ +  + ]:     250036 :                 if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) {
#     886                 :     102819 :                     sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr});
#     887                 :     102819 :                 }
#     888                 :     250036 :             } else {
#     889                 :          1 :                 error = strprintf("parse error on line %i: %s", linenr, str);
#     890 [ +  - ][ +  - ]:          1 :                 if (str.size() >= 2 && str.substr(0, 2) == "no") {
#                 [ +  - ]
#     891                 :          1 :                     error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
#     892                 :          1 :                 }
#     893                 :          1 :                 return false;
#     894                 :          1 :             }
#     895                 :     252253 :         }
#     896                 :     252251 :         ++linenr;
#     897                 :     252251 :     }
#     898                 :      58392 :     return true;
#     899                 :      58397 : }
#     900                 :            : 
#     901                 :            : bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys)
#     902                 :      58397 : {
#     903                 :      58397 :     LOCK(cs_args);
#     904                 :      58397 :     std::vector<std::pair<std::string, std::string>> options;
#     905         [ +  + ]:      58397 :     if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) {
#     906                 :          5 :         return false;
#     907                 :          5 :     }
#     908         [ +  + ]:     250030 :     for (const std::pair<std::string, std::string>& option : options) {
#     909                 :     250030 :         KeyInfo key = InterpretKey(option.first);
#     910                 :     250030 :         std::optional<unsigned int> flags = GetArgFlags('-' + key.name);
#     911         [ +  + ]:     250030 :         if (flags) {
#     912                 :     228061 :             std::optional<util::SettingsValue> value = InterpretValue(key, option.second, *flags, error);
#     913         [ -  + ]:     228061 :             if (!value) {
#     914                 :          0 :                 return false;
#     915                 :          0 :             }
#     916                 :     228061 :             m_settings.ro_config[key.section][key.name].push_back(*value);
#     917                 :     228061 :         } else {
#     918         [ +  - ]:      21969 :             if (ignore_invalid_keys) {
#     919                 :      21969 :                 LogPrintf("Ignoring unknown configuration value %s\n", option.first);
#     920                 :      21969 :             } else {
#     921                 :          0 :                 error = strprintf("Invalid configuration value %s", option.first);
#     922                 :          0 :                 return false;
#     923                 :          0 :             }
#     924                 :      21969 :         }
#     925                 :     250030 :     }
#     926                 :      58392 :     return true;
#     927                 :      58392 : }
#     928                 :            : 
#     929                 :            : bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
#     930                 :       2188 : {
#     931                 :       2188 :     {
#     932                 :       2188 :         LOCK(cs_args);
#     933                 :       2188 :         m_settings.ro_config.clear();
#     934                 :       2188 :         m_config_sections.clear();
#     935                 :       2188 :     }
#     936                 :            : 
#     937                 :       2188 :     const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
#     938                 :       2188 :     std::ifstream stream{GetConfigFile(confPath)};
#     939                 :            : 
#     940                 :            :     // not ok to have a config file specified that cannot be opened
#     941 [ +  + ][ +  + ]:       2188 :     if (IsArgSet("-conf") && !stream.good()) {
#                 [ +  + ]
#     942                 :          1 :         error = strprintf("specified config file \"%s\" could not be opened.", confPath);
#     943                 :          1 :         return false;
#     944                 :          1 :     }
#     945                 :            :     // ok to not have a config file
#     946         [ +  - ]:       2187 :     if (stream.good()) {
#     947         [ -  + ]:       2187 :         if (!ReadConfigStream(stream, confPath, error, ignore_invalid_keys)) {
#     948                 :          0 :             return false;
#     949                 :          0 :         }
#     950                 :            :         // `-includeconf` cannot be included in the command line arguments except
#     951                 :            :         // as `-noincludeconf` (which indicates that no included conf file should be used).
#     952                 :       2187 :         bool use_conf_file{true};
#     953                 :       2187 :         {
#     954                 :       2187 :             LOCK(cs_args);
#     955         [ -  + ]:       2187 :             if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
#     956                 :            :                 // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
#     957                 :          0 :                 assert(util::SettingsSpan(*includes).last_negated());
#     958                 :          0 :                 use_conf_file = false;
#     959                 :          0 :             }
#     960                 :       2187 :         }
#     961         [ +  - ]:       2187 :         if (use_conf_file) {
#     962                 :       2187 :             std::string chain_id = GetChainName();
#     963                 :       2187 :             std::vector<std::string> conf_file_names;
#     964                 :            : 
#     965                 :       8736 :             auto add_includes = [&](const std::string& network, size_t skip = 0) {
#     966                 :       8736 :                 size_t num_values = 0;
#     967                 :       8736 :                 LOCK(cs_args);
#     968         [ +  + ]:       8736 :                 if (auto* section = util::FindKey(m_settings.ro_config, network)) {
#     969         [ +  + ]:       8734 :                     if (auto* values = util::FindKey(*section, "includeconf")) {
#     970         [ +  + ]:         53 :                         for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) {
#     971                 :         24 :                             conf_file_names.push_back((*values)[i].get_str());
#     972                 :         24 :                         }
#     973                 :         29 :                         num_values = values->size();
#     974                 :         29 :                     }
#     975                 :       8734 :                 }
#     976                 :       8736 :                 return num_values;
#     977                 :       8736 :             };
#     978                 :            : 
#     979                 :            :             // We haven't set m_network yet (that happens in SelectParams()), so manually check
#     980                 :            :             // for network.includeconf args.
#     981                 :       2187 :             const size_t chain_includes = add_includes(chain_id);
#     982                 :       2187 :             const size_t default_includes = add_includes({});
#     983                 :            : 
#     984         [ +  + ]:       2187 :             for (const std::string& conf_file_name : conf_file_names) {
#     985                 :         23 :                 std::ifstream conf_file_stream{GetConfigFile(conf_file_name)};
#     986         [ +  + ]:         23 :                 if (conf_file_stream.good()) {
#     987         [ +  + ]:         22 :                     if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
#     988                 :          5 :                         return false;
#     989                 :          5 :                     }
#     990                 :         17 :                     LogPrintf("Included configuration file %s\n", conf_file_name);
#     991                 :         17 :                 } else {
#     992                 :          1 :                     error = "Failed to include configuration file " + conf_file_name;
#     993                 :          1 :                     return false;
#     994                 :          1 :                 }
#     995                 :         23 :             }
#     996                 :            : 
#     997                 :            :             // Warn about recursive -includeconf
#     998                 :       2181 :             conf_file_names.clear();
#     999                 :       2181 :             add_includes(chain_id, /* skip= */ chain_includes);
#    1000                 :       2181 :             add_includes({}, /* skip= */ default_includes);
#    1001                 :       2181 :             std::string chain_id_final = GetChainName();
#    1002         [ -  + ]:       2181 :             if (chain_id_final != chain_id) {
#    1003                 :            :                 // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
#    1004                 :          0 :                 add_includes(chain_id_final);
#    1005                 :          0 :             }
#    1006         [ +  + ]:       2181 :             for (const std::string& conf_file_name : conf_file_names) {
#    1007                 :          1 :                 tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
#    1008                 :          1 :             }
#    1009                 :       2181 :         }
#    1010                 :       2187 :     }
#    1011                 :            : 
#    1012                 :            :     // If datadir is changed in .conf file:
#    1013                 :       2181 :     gArgs.ClearPathCache();
#    1014         [ +  + ]:       2181 :     if (!CheckDataDirOption()) {
#    1015                 :          1 :         error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
#    1016                 :          1 :         return false;
#    1017                 :          1 :     }
#    1018                 :       2180 :     return true;
#    1019                 :       2181 : }
#    1020                 :            : 
#    1021                 :            : std::string ArgsManager::GetChainName() const
#    1022                 :      11021 : {
#    1023                 :      33063 :     auto get_net = [&](const std::string& arg) {
#    1024                 :      33063 :         LOCK(cs_args);
#    1025                 :      33063 :         util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
#    1026                 :      33063 :             /* ignore_default_section_config= */ false,
#    1027                 :      33063 :             /*ignore_nonpersistent=*/false,
#    1028                 :      33063 :             /* get_chain_name= */ true);
#    1029 [ +  + ][ -  + ]:      33063 :         return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
#    1030                 :      33063 :     };
#    1031                 :            : 
#    1032                 :      11021 :     const bool fRegTest = get_net("-regtest");
#    1033                 :      11021 :     const bool fSigNet  = get_net("-signet");
#    1034                 :      11021 :     const bool fTestNet = get_net("-testnet");
#    1035                 :      11021 :     const bool is_chain_arg_set = IsArgSet("-chain");
#    1036                 :            : 
#    1037         [ +  + ]:      11021 :     if ((int)is_chain_arg_set + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
#    1038                 :        374 :         throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
#    1039                 :        374 :     }
#    1040         [ +  + ]:      10647 :     if (fRegTest)
#    1041                 :       7911 :         return CBaseChainParams::REGTEST;
#    1042         [ +  + ]:       2736 :     if (fSigNet) {
#    1043                 :         72 :         return CBaseChainParams::SIGNET;
#    1044                 :         72 :     }
#    1045         [ +  + ]:       2664 :     if (fTestNet)
#    1046                 :        672 :         return CBaseChainParams::TESTNET;
#    1047                 :            : 
#    1048                 :       1992 :     return GetArg("-chain", CBaseChainParams::MAIN);
#    1049                 :       2664 : }
#    1050                 :            : 
#    1051                 :            : bool ArgsManager::UseDefaultSection(const std::string& arg) const
#    1052                 :    2222911 : {
#    1053 [ +  + ][ +  + ]:    2222911 :     return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0;
#    1054                 :    2222911 : }
#    1055                 :            : 
#    1056                 :            : util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
#    1057                 :    2144684 : {
#    1058                 :    2144684 :     LOCK(cs_args);
#    1059                 :    2144684 :     return util::GetSetting(
#    1060                 :    2144684 :         m_settings, m_network, SettingName(arg), !UseDefaultSection(arg),
#    1061                 :    2144684 :         /*ignore_nonpersistent=*/false, /*get_chain_name=*/false);
#    1062                 :    2144684 : }
#    1063                 :            : 
#    1064                 :            : std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
#    1065                 :      78104 : {
#    1066                 :      78104 :     LOCK(cs_args);
#    1067                 :      78104 :     return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
#    1068                 :      78104 : }
#    1069                 :            : 
#    1070                 :            : void ArgsManager::logArgsPrefix(
#    1071                 :            :     const std::string& prefix,
#    1072                 :            :     const std::string& section,
#    1073                 :            :     const std::map<std::string, std::vector<util::SettingsValue>>& args) const
#    1074                 :       2377 : {
#    1075         [ +  + ]:       2377 :     std::string section_str = section.empty() ? "" : "[" + section + "] ";
#    1076         [ +  + ]:      20600 :     for (const auto& arg : args) {
#    1077         [ +  + ]:      21440 :         for (const auto& value : arg.second) {
#    1078                 :      21440 :             std::optional<unsigned int> flags = GetArgFlags('-' + arg.first);
#    1079         [ +  + ]:      21440 :             if (flags) {
#    1080         [ +  + ]:      21433 :                 std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
#    1081                 :      21433 :                 LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
#    1082                 :      21433 :             }
#    1083                 :      21440 :         }
#    1084                 :      20600 :     }
#    1085                 :       2377 : }
#    1086                 :            : 
#    1087                 :            : void ArgsManager::LogArgs() const
#    1088                 :        794 : {
#    1089                 :        794 :     LOCK(cs_args);
#    1090         [ +  + ]:       1583 :     for (const auto& section : m_settings.ro_config) {
#    1091                 :       1583 :         logArgsPrefix("Config file arg:", section.first, section.second);
#    1092                 :       1583 :     }
#    1093         [ +  + ]:        794 :     for (const auto& setting : m_settings.rw_settings) {
#    1094                 :        176 :         LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
#    1095                 :        176 :     }
#    1096                 :        794 :     logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
#    1097                 :        794 : }
#    1098                 :            : 
#    1099                 :            : bool RenameOver(fs::path src, fs::path dest)
#    1100                 :       3721 : {
#    1101                 :            : #ifdef __MINGW64__
#    1102                 :            :     // This is a workaround for a bug in libstdc++ which
#    1103                 :            :     // implements std::filesystem::rename with _wrename function.
#    1104                 :            :     // This bug has been fixed in upstream:
#    1105                 :            :     //  - GCC 10.3: 8dd1c1085587c9f8a21bb5e588dfe1e8cdbba79e
#    1106                 :            :     //  - GCC 11.1: 1dfd95f0a0ca1d9e6cbc00e6cbfd1fa20a98f312
#    1107                 :            :     // For more details see the commits mentioned above.
#    1108                 :            :     return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
#    1109                 :            :                        MOVEFILE_REPLACE_EXISTING) != 0;
#    1110                 :            : #else
#    1111                 :       3721 :     std::error_code error;
#    1112                 :       3721 :     fs::rename(src, dest, error);
#    1113                 :       3721 :     return !error;
#    1114                 :       3721 : #endif
#    1115                 :       3721 : }
#    1116                 :            : 
#    1117                 :            : /**
#    1118                 :            :  * Ignores exceptions thrown by create_directories if the requested directory exists.
#    1119                 :            :  * Specifically handles case where path p exists, but it wasn't possible for the user to
#    1120                 :            :  * write to the parent directory.
#    1121                 :            :  */
#    1122                 :            : bool TryCreateDirectories(const fs::path& p)
#    1123                 :       3102 : {
#    1124                 :       3102 :     try
#    1125                 :       3102 :     {
#    1126                 :       3102 :         return fs::create_directories(p);
#    1127                 :       3102 :     } catch (const fs::filesystem_error&) {
#    1128 [ +  - ][ #  # ]:          3 :         if (!fs::exists(p) || !fs::is_directory(p))
#    1129                 :          3 :             throw;
#    1130                 :          3 :     }
#    1131                 :            : 
#    1132                 :            :     // create_directories didn't create the directory, it had to have existed already
#    1133                 :          0 :     return false;
#    1134                 :       3102 : }
#    1135                 :            : 
#    1136                 :            : bool FileCommit(FILE *file)
#    1137                 :       5211 : {
#    1138         [ -  + ]:       5211 :     if (fflush(file) != 0) { // harmless if redundantly called
#    1139                 :          0 :         LogPrintf("%s: fflush failed: %d\n", __func__, errno);
#    1140                 :          0 :         return false;
#    1141                 :          0 :     }
#    1142                 :            : #ifdef WIN32
#    1143                 :            :     HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
#    1144                 :            :     if (FlushFileBuffers(hFile) == 0) {
#    1145                 :            :         LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
#    1146                 :            :         return false;
#    1147                 :            :     }
#    1148                 :            : #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
#    1149                 :            :     if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
#    1150                 :            :         LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
#    1151                 :            :         return false;
#    1152                 :            :     }
#    1153                 :            : #elif HAVE_FDATASYNC
#    1154 [ -  + ][ #  # ]:       5211 :     if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
#    1155                 :          0 :         LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
#    1156                 :          0 :         return false;
#    1157                 :          0 :     }
#    1158                 :            : #else
#    1159                 :            :     if (fsync(fileno(file)) != 0 && errno != EINVAL) {
#    1160                 :            :         LogPrintf("%s: fsync failed: %d\n", __func__, errno);
#    1161                 :            :         return false;
#    1162                 :            :     }
#    1163                 :            : #endif
#    1164                 :       5211 :     return true;
#    1165                 :       5211 : }
#    1166                 :            : 
#    1167                 :            : void DirectoryCommit(const fs::path &dirname)
#    1168                 :       3288 : {
#    1169                 :       3288 : #ifndef WIN32
#    1170                 :       3288 :     FILE* file = fsbridge::fopen(dirname, "r");
#    1171         [ +  - ]:       3288 :     if (file) {
#    1172                 :       3288 :         fsync(fileno(file));
#    1173                 :       3288 :         fclose(file);
#    1174                 :       3288 :     }
#    1175                 :       3288 : #endif
#    1176                 :       3288 : }
#    1177                 :            : 
#    1178                 :         40 : bool TruncateFile(FILE *file, unsigned int length) {
#    1179                 :            : #if defined(WIN32)
#    1180                 :            :     return _chsize(_fileno(file), length) == 0;
#    1181                 :            : #else
#    1182                 :         40 :     return ftruncate(fileno(file), length) == 0;
#    1183                 :         40 : #endif
#    1184                 :         40 : }
#    1185                 :            : 
#    1186                 :            : /**
#    1187                 :            :  * this function tries to raise the file descriptor limit to the requested number.
#    1188                 :            :  * It returns the actual file descriptor limit (which may be more or less than nMinFD)
#    1189                 :            :  */
#    1190                 :       1635 : int RaiseFileDescriptorLimit(int nMinFD) {
#    1191                 :            : #if defined(WIN32)
#    1192                 :            :     return 2048;
#    1193                 :            : #else
#    1194                 :       1635 :     struct rlimit limitFD;
#    1195         [ +  - ]:       1635 :     if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
#    1196         [ -  + ]:       1635 :         if (limitFD.rlim_cur < (rlim_t)nMinFD) {
#    1197                 :          0 :             limitFD.rlim_cur = nMinFD;
#    1198         [ #  # ]:          0 :             if (limitFD.rlim_cur > limitFD.rlim_max)
#    1199                 :          0 :                 limitFD.rlim_cur = limitFD.rlim_max;
#    1200                 :          0 :             setrlimit(RLIMIT_NOFILE, &limitFD);
#    1201                 :          0 :             getrlimit(RLIMIT_NOFILE, &limitFD);
#    1202                 :          0 :         }
#    1203                 :       1635 :         return limitFD.rlim_cur;
#    1204                 :       1635 :     }
#    1205                 :          0 :     return nMinFD; // getrlimit failed, assume it's fine
#    1206                 :       1635 : #endif
#    1207                 :       1635 : }
#    1208                 :            : 
#    1209                 :            : /**
#    1210                 :            :  * this function tries to make a particular range of a file allocated (corresponding to disk space)
#    1211                 :            :  * it is advisory, and the range specified in the arguments will never contain live data
#    1212                 :            :  */
#    1213                 :        881 : void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
#    1214                 :            : #if defined(WIN32)
#    1215                 :            :     // Windows-specific version
#    1216                 :            :     HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
#    1217                 :            :     LARGE_INTEGER nFileSize;
#    1218                 :            :     int64_t nEndPos = (int64_t)offset + length;
#    1219                 :            :     nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
#    1220                 :            :     nFileSize.u.HighPart = nEndPos >> 32;
#    1221                 :            :     SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
#    1222                 :            :     SetEndOfFile(hFile);
#    1223                 :            : #elif defined(MAC_OSX)
#    1224                 :            :     // OSX specific version
#    1225                 :            :     // NOTE: Contrary to other OS versions, the OSX version assumes that
#    1226                 :            :     // NOTE: offset is the size of the file.
#    1227                 :            :     fstore_t fst;
#    1228                 :            :     fst.fst_flags = F_ALLOCATECONTIG;
#    1229                 :            :     fst.fst_posmode = F_PEOFPOSMODE;
#    1230                 :            :     fst.fst_offset = 0;
#    1231                 :            :     fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
#    1232                 :            :     fst.fst_bytesalloc = 0;
#    1233                 :            :     if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
#    1234                 :            :         fst.fst_flags = F_ALLOCATEALL;
#    1235                 :            :         fcntl(fileno(file), F_PREALLOCATE, &fst);
#    1236                 :            :     }
#    1237                 :            :     ftruncate(fileno(file), static_cast<off_t>(offset) + length);
#    1238                 :            : #else
#    1239                 :        881 :     #if defined(HAVE_POSIX_FALLOCATE)
#    1240                 :            :     // Version using posix_fallocate
#    1241                 :        881 :     off_t nEndPos = (off_t)offset + length;
#    1242         [ -  + ]:        881 :     if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
#    1243                 :        881 :     #endif
#    1244                 :            :     // Fallback version
#    1245                 :            :     // TODO: just write one byte per block
#    1246                 :        881 :     static const char buf[65536] = {};
#    1247         [ -  + ]:        881 :     if (fseek(file, offset, SEEK_SET)) {
#    1248                 :          0 :         return;
#    1249                 :          0 :     }
#    1250         [ +  + ]:     142996 :     while (length > 0) {
#    1251                 :     142115 :         unsigned int now = 65536;
#    1252         [ +  + ]:     142115 :         if (length < now)
#    1253                 :        107 :             now = length;
#    1254                 :     142115 :         fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
#    1255                 :     142115 :         length -= now;
#    1256                 :     142115 :     }
#    1257                 :        881 : #endif
#    1258                 :        881 : }
#    1259                 :            : 
#    1260                 :            : #ifdef WIN32
#    1261                 :            : fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
#    1262                 :            : {
#    1263                 :            :     WCHAR pszPath[MAX_PATH] = L"";
#    1264                 :            : 
#    1265                 :            :     if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
#    1266                 :            :     {
#    1267                 :            :         return fs::path(pszPath);
#    1268                 :            :     }
#    1269                 :            : 
#    1270                 :            :     LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
#    1271                 :            :     return fs::path("");
#    1272                 :            : }
#    1273                 :            : #endif
#    1274                 :            : 
#    1275                 :            : #ifndef WIN32
#    1276                 :            : std::string ShellEscape(const std::string& arg)
#    1277                 :         26 : {
#    1278                 :         26 :     std::string escaped = arg;
#    1279                 :         26 :     boost::replace_all(escaped, "'", "'\"'\"'");
#    1280                 :         26 :     return "'" + escaped + "'";
#    1281                 :         26 : }
#    1282                 :            : #endif
#    1283                 :            : 
#    1284                 :            : #if HAVE_SYSTEM
#    1285                 :            : void runCommand(const std::string& strCommand)
#    1286                 :        141 : {
#    1287         [ -  + ]:        141 :     if (strCommand.empty()) return;
#    1288                 :        141 : #ifndef WIN32
#    1289                 :        141 :     int nErr = ::system(strCommand.c_str());
#    1290                 :            : #else
#    1291                 :            :     int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
#    1292                 :            : #endif
#    1293         [ -  + ]:        141 :     if (nErr)
#    1294                 :          0 :         LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
#    1295                 :        141 : }
#    1296                 :            : #endif
#    1297                 :            : 
#    1298                 :            : UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
#    1299                 :         29 : {
#    1300                 :         29 : #ifdef ENABLE_EXTERNAL_SIGNER
#    1301                 :         29 :     namespace bp = boost::process;
#    1302                 :            : 
#    1303                 :         29 :     UniValue result_json;
#    1304                 :         29 :     bp::opstream stdin_stream;
#    1305                 :         29 :     bp::ipstream stdout_stream;
#    1306                 :         29 :     bp::ipstream stderr_stream;
#    1307                 :            : 
#    1308         [ +  + ]:         29 :     if (str_command.empty()) return UniValue::VNULL;
#    1309                 :            : 
#    1310                 :         27 :     bp::child c(
#    1311                 :         27 :         str_command,
#    1312                 :         27 :         bp::std_out > stdout_stream,
#    1313                 :         27 :         bp::std_err > stderr_stream,
#    1314                 :         27 :         bp::std_in < stdin_stream
#    1315                 :         27 :     );
#    1316         [ +  + ]:         27 :     if (!str_std_in.empty()) {
#    1317                 :          4 :         stdin_stream << str_std_in << std::endl;
#    1318                 :          4 :     }
#    1319                 :         27 :     stdin_stream.pipe().close();
#    1320                 :            : 
#    1321                 :         27 :     std::string result;
#    1322                 :         27 :     std::string error;
#    1323                 :         27 :     std::getline(stdout_stream, result);
#    1324                 :         27 :     std::getline(stderr_stream, error);
#    1325                 :            : 
#    1326                 :         27 :     c.wait();
#    1327                 :         27 :     const int n_error = c.exit_code();
#    1328         [ +  + ]:         27 :     if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
#    1329         [ +  + ]:         21 :     if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
#    1330                 :            : 
#    1331                 :         19 :     return result_json;
#    1332                 :            : #else
#    1333                 :            :     throw std::runtime_error("Compiled without external signing support (required for external signing).");
#    1334                 :            : #endif // ENABLE_EXTERNAL_SIGNER
#    1335                 :         21 : }
#    1336                 :            : 
#    1337                 :            : void SetupEnvironment()
#    1338                 :       3104 : {
#    1339                 :            : #ifdef HAVE_MALLOPT_ARENA_MAX
#    1340                 :            :     // glibc-specific: On 32-bit systems set the number of arenas to 1.
#    1341                 :            :     // By default, since glibc 2.10, the C library will create up to two heap
#    1342                 :            :     // arenas per core. This is known to cause excessive virtual address space
#    1343                 :            :     // usage in our usage. Work around it by setting the maximum number of
#    1344                 :            :     // arenas to 1.
#    1345                 :            :     if (sizeof(void*) == 4) {
#    1346                 :            :         mallopt(M_ARENA_MAX, 1);
#    1347                 :            :     }
#    1348                 :            : #endif
#    1349                 :            :     // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
#    1350                 :            :     // may be invalid, in which case the "C.UTF-8" locale is used as fallback.
#    1351                 :            : #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
#    1352                 :            :     try {
#    1353                 :            :         std::locale(""); // Raises a runtime error if current locale is invalid
#    1354                 :            :     } catch (const std::runtime_error&) {
#    1355                 :            :         setenv("LC_ALL", "C.UTF-8", 1);
#    1356                 :            :     }
#    1357                 :            : #elif defined(WIN32)
#    1358                 :            :     // Set the default input/output charset is utf-8
#    1359                 :            :     SetConsoleCP(CP_UTF8);
#    1360                 :            :     SetConsoleOutputCP(CP_UTF8);
#    1361                 :            : #endif
#    1362                 :       3104 : }
#    1363                 :            : 
#    1364                 :            : bool SetupNetworking()
#    1365                 :       3014 : {
#    1366                 :            : #ifdef WIN32
#    1367                 :            :     // Initialize Windows Sockets
#    1368                 :            :     WSADATA wsadata;
#    1369                 :            :     int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
#    1370                 :            :     if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
#    1371                 :            :         return false;
#    1372                 :            : #endif
#    1373                 :       3014 :     return true;
#    1374                 :       3014 : }
#    1375                 :            : 
#    1376                 :            : int GetNumCores()
#    1377                 :       2446 : {
#    1378                 :       2446 :     return std::thread::hardware_concurrency();
#    1379                 :       2446 : }
#    1380                 :            : 
#    1381                 :            : // Obtain the application startup time (used for uptime calculation)
#    1382                 :            : int64_t GetStartupTime()
#    1383                 :          2 : {
#    1384                 :          2 :     return nStartupTime;
#    1385                 :          2 : }
#    1386                 :            : 
#    1387                 :            : fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
#    1388                 :      10011 : {
#    1389         [ +  + ]:      10011 :     if (path.is_absolute()) {
#    1390                 :         29 :         return path;
#    1391                 :         29 :     }
#    1392         [ +  + ]:       9982 :     return fsbridge::AbsPathJoin(net_specific ? gArgs.GetDataDirNet() : gArgs.GetDataDirBase(), path);
#    1393                 :      10011 : }
#    1394                 :            : 
#    1395                 :            : void ScheduleBatchPriority()
#    1396                 :        725 : {
#    1397                 :            : #ifdef SCHED_BATCH
#    1398                 :            :     const static sched_param param{};
#    1399                 :            :     const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param);
#    1400                 :            :     if (rc != 0) {
#    1401                 :            :         LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(rc));
#    1402                 :            :     }
#    1403                 :            : #endif
#    1404                 :        725 : }
#    1405                 :            : 
#    1406                 :            : namespace util {
#    1407                 :            : #ifdef WIN32
#    1408                 :            : WinCmdLineArgs::WinCmdLineArgs()
#    1409                 :            : {
#    1410                 :            :     wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
#    1411                 :            :     std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
#    1412                 :            :     argv = new char*[argc];
#    1413                 :            :     args.resize(argc);
#    1414                 :            :     for (int i = 0; i < argc; i++) {
#    1415                 :            :         args[i] = utf8_cvt.to_bytes(wargv[i]);
#    1416                 :            :         argv[i] = &*args[i].begin();
#    1417                 :            :     }
#    1418                 :            :     LocalFree(wargv);
#    1419                 :            : }
#    1420                 :            : 
#    1421                 :            : WinCmdLineArgs::~WinCmdLineArgs()
#    1422                 :            : {
#    1423                 :            :     delete[] argv;
#    1424                 :            : }
#    1425                 :            : 
#    1426                 :            : std::pair<int, char**> WinCmdLineArgs::get()
#    1427                 :            : {
#    1428                 :            :     return std::make_pair(argc, argv);
#    1429                 :            : }
#    1430                 :            : #endif
#    1431                 :            : } // namespace util

Generated by: LCOV version 0-eol-96201-ge66f56f4af6a