1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 #include <chainparamsbase.h>
9 #include <random.h>
10 #include <serialize.h>
11 #include <util/strencodings.h>
12 
13 #include <stdarg.h>
14 
15 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
16 #include <pthread.h>
17 #include <pthread_np.h>
18 #endif
19 
20 #ifndef WIN32
21 // for posix_fallocate
22 #ifdef __linux__
23 
24 #ifdef _POSIX_C_SOURCE
25 #undef _POSIX_C_SOURCE
26 #endif
27 
28 #define _POSIX_C_SOURCE 200112L
29 
30 #endif // __linux__
31 
32 #include <algorithm>
33 #include <fcntl.h>
34 #include <sched.h>
35 #include <sys/resource.h>
36 #include <sys/stat.h>
37 
38 #else
39 
40 #ifdef _MSC_VER
41 #pragma warning(disable:4786)
42 #pragma warning(disable:4804)
43 #pragma warning(disable:4805)
44 #pragma warning(disable:4717)
45 #endif
46 
47 #ifdef _WIN32_IE
48 #undef _WIN32_IE
49 #endif
50 #define _WIN32_IE 0x0501
51 
52 #define WIN32_LEAN_AND_MEAN 1
53 #ifndef NOMINMAX
54 #define NOMINMAX
55 #endif
56 #include <codecvt>
57 
58 #include <io.h> /* for _commit */
59 #include <shellapi.h>
60 #include <shlobj.h>
61 #endif
62 
63 #ifdef HAVE_SYS_PRCTL_H
64 #include <sys/prctl.h>
65 #endif
66 
67 #ifdef HAVE_MALLOPT_ARENA_MAX
68 #include <malloc.h>
69 #endif
70 
71 #include <thread>
72 
73 // Application startup time (used for uptime calculation)
74 const int64_t nStartupTime = GetTime();
75 
76 const char * const BITCOIN_CONF_FILENAME = "litecoin.conf";
77 
78 ArgsManager gArgs;
79 
80 /** A map that contains all the currently held directory locks. After
81  * successful locking, these will be held here until the global destructor
82  * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
83  * is called.
84  */
85 static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks;
86 /** Mutex to protect dir_locks. */
87 static std::mutex cs_dir_locks;
88 
LockDirectory(const fs::path & directory,const std::string lockfile_name,bool probe_only)89 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
90 {
91     std::lock_guard<std::mutex> ulock(cs_dir_locks);
92     fs::path pathLockFile = directory / lockfile_name;
93 
94     // If a lock for this directory already exists in the map, don't try to re-lock it
95     if (dir_locks.count(pathLockFile.string())) {
96         return true;
97     }
98 
99     // Create empty lock file if it doesn't exist.
100     FILE* file = fsbridge::fopen(pathLockFile, "a");
101     if (file) fclose(file);
102     auto lock = MakeUnique<fsbridge::FileLock>(pathLockFile);
103     if (!lock->TryLock()) {
104         return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
105     }
106     if (!probe_only) {
107         // Lock successful and we're not just probing, put it into the map
108         dir_locks.emplace(pathLockFile.string(), std::move(lock));
109     }
110     return true;
111 }
112 
UnlockDirectory(const fs::path & directory,const std::string & lockfile_name)113 void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
114 {
115     std::lock_guard<std::mutex> lock(cs_dir_locks);
116     dir_locks.erase((directory / lockfile_name).string());
117 }
118 
ReleaseDirectoryLocks()119 void ReleaseDirectoryLocks()
120 {
121     std::lock_guard<std::mutex> ulock(cs_dir_locks);
122     dir_locks.clear();
123 }
124 
DirIsWritable(const fs::path & directory)125 bool DirIsWritable(const fs::path& directory)
126 {
127     fs::path tmpFile = directory / fs::unique_path();
128 
129     FILE* file = fsbridge::fopen(tmpFile, "a");
130     if (!file) return false;
131 
132     fclose(file);
133     remove(tmpFile);
134 
135     return true;
136 }
137 
138 /**
139  * Interpret a string argument as a boolean.
140  *
141  * The definition of atoi() requires that non-numeric string values like "foo",
142  * return 0. This means that if a user unintentionally supplies a non-integer
143  * argument here, the return value is always false. This means that -foo=false
144  * does what the user probably expects, but -foo=true is well defined but does
145  * not do what they probably expected.
146  *
147  * The return value of atoi() is undefined when given input not representable as
148  * an int. On most systems this means string value between "-2147483648" and
149  * "2147483647" are well defined (this method will return true). Setting
150  * -txindex=2147483648 on most systems, however, is probably undefined.
151  *
152  * For a more extensive discussion of this topic (and a wide range of opinions
153  * on the Right Way to change this code), see PR12713.
154  */
InterpretBool(const std::string & strValue)155 static bool InterpretBool(const std::string& strValue)
156 {
157     if (strValue.empty())
158         return true;
159     return (atoi(strValue) != 0);
160 }
161 
162 /** Internal helper functions for ArgsManager */
163 class ArgsManagerHelper {
164 public:
165     typedef std::map<std::string, std::vector<std::string>> MapArgs;
166 
167     /** Determine whether to use config settings in the default section,
168      *  See also comments around ArgsManager::ArgsManager() below. */
UseDefaultSection(const ArgsManager & am,const std::string & arg)169     static inline bool UseDefaultSection(const ArgsManager& am, const std::string& arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
170     {
171         return (am.m_network == CBaseChainParams::MAIN || am.m_network_only_args.count(arg) == 0);
172     }
173 
174     /** Convert regular argument into the network-specific setting */
NetworkArg(const ArgsManager & am,const std::string & arg)175     static inline std::string NetworkArg(const ArgsManager& am, const std::string& arg)
176     {
177         assert(arg.length() > 1 && arg[0] == '-');
178         return "-" + am.m_network + "." + arg.substr(1);
179     }
180 
181     /** Find arguments in a map and add them to a vector */
AddArgs(std::vector<std::string> & res,const MapArgs & map_args,const std::string & arg)182     static inline void AddArgs(std::vector<std::string>& res, const MapArgs& map_args, const std::string& arg)
183     {
184         auto it = map_args.find(arg);
185         if (it != map_args.end()) {
186             res.insert(res.end(), it->second.begin(), it->second.end());
187         }
188     }
189 
190     /** Return true/false if an argument is set in a map, and also
191      *  return the first (or last) of the possibly multiple values it has
192      */
GetArgHelper(const MapArgs & map_args,const std::string & arg,bool getLast=false)193     static inline std::pair<bool,std::string> GetArgHelper(const MapArgs& map_args, const std::string& arg, bool getLast = false)
194     {
195         auto it = map_args.find(arg);
196 
197         if (it == map_args.end() || it->second.empty()) {
198             return std::make_pair(false, std::string());
199         }
200 
201         if (getLast) {
202             return std::make_pair(true, it->second.back());
203         } else {
204             return std::make_pair(true, it->second.front());
205         }
206     }
207 
208     /* Get the string value of an argument, returning a pair of a boolean
209      * indicating the argument was found, and the value for the argument
210      * if it was found (or the empty string if not found).
211      */
GetArg(const ArgsManager & am,const std::string & arg)212     static inline std::pair<bool,std::string> GetArg(const ArgsManager &am, const std::string& arg)
213     {
214         LOCK(am.cs_args);
215         std::pair<bool,std::string> found_result(false, std::string());
216 
217         // We pass "true" to GetArgHelper in order to return the last
218         // argument value seen from the command line (so "bitcoind -foo=bar
219         // -foo=baz" gives GetArg(am,"foo")=={true,"baz"}
220         found_result = GetArgHelper(am.m_override_args, arg, true);
221         if (found_result.first) {
222             return found_result;
223         }
224 
225         // But in contrast we return the first argument seen in a config file,
226         // so "foo=bar \n foo=baz" in the config file gives
227         // GetArg(am,"foo")={true,"bar"}
228         if (!am.m_network.empty()) {
229             found_result = GetArgHelper(am.m_config_args, NetworkArg(am, arg));
230             if (found_result.first) {
231                 return found_result;
232             }
233         }
234 
235         if (UseDefaultSection(am, arg)) {
236             found_result = GetArgHelper(am.m_config_args, arg);
237             if (found_result.first) {
238                 return found_result;
239             }
240         }
241 
242         return found_result;
243     }
244 
245     /* Special test for -testnet and -regtest args, because we
246      * don't want to be confused by craziness like "[regtest] testnet=1"
247      */
GetNetBoolArg(const ArgsManager & am,const std::string & net_arg)248     static inline bool GetNetBoolArg(const ArgsManager &am, const std::string& net_arg) EXCLUSIVE_LOCKS_REQUIRED(am.cs_args)
249     {
250         std::pair<bool,std::string> found_result(false,std::string());
251         found_result = GetArgHelper(am.m_override_args, net_arg, true);
252         if (!found_result.first) {
253             found_result = GetArgHelper(am.m_config_args, net_arg, true);
254             if (!found_result.first) {
255                 return false; // not set
256             }
257         }
258         return InterpretBool(found_result.second); // is set, so evaluate
259     }
260 };
261 
262 /**
263  * Interpret -nofoo as if the user supplied -foo=0.
264  *
265  * This method also tracks when the -no form was supplied, and if so,
266  * checks whether there was a double-negative (-nofoo=0 -> -foo=1).
267  *
268  * If there was not a double negative, it removes the "no" from the key,
269  * and returns true, indicating the caller should clear the args vector
270  * to indicate a negated option.
271  *
272  * If there was a double negative, it removes "no" from the key, sets the
273  * value to "1" and returns false.
274  *
275  * If there was no "no", it leaves key and value untouched and returns
276  * false.
277  *
278  * Where an option was negated can be later checked using the
279  * IsArgNegated() method. One use case for this is to have a way to disable
280  * options that are not normally boolean (e.g. using -nodebuglogfile to request
281  * that debug log output is not sent to any file at all).
282  */
InterpretNegatedOption(std::string & key,std::string & val)283 static bool InterpretNegatedOption(std::string& key, std::string& val)
284 {
285     assert(key[0] == '-');
286 
287     size_t option_index = key.find('.');
288     if (option_index == std::string::npos) {
289         option_index = 1;
290     } else {
291         ++option_index;
292     }
293     if (key.substr(option_index, 2) == "no") {
294         bool bool_val = InterpretBool(val);
295         key.erase(option_index, 2);
296         if (!bool_val ) {
297             // Double negatives like -nofoo=0 are supported (but discouraged)
298             LogPrintf("Warning: parsed potentially confusing double-negative %s=%s\n", key, val);
299             val = "1";
300         } else {
301             return true;
302         }
303     }
304     return false;
305 }
306 
ArgsManager()307 ArgsManager::ArgsManager() :
308     /* These options would cause cross-contamination if values for
309      * mainnet were used while running on regtest/testnet (or vice-versa).
310      * Setting them as section_only_args ensures that sharing a config file
311      * between mainnet and regtest/testnet won't cause problems due to these
312      * parameters by accident. */
313     m_network_only_args{
314       "-addnode", "-connect",
315       "-port", "-bind",
316       "-rpcport", "-rpcbind",
317       "-wallet",
318     }
319 {
320     // nothing to do
321 }
322 
GetUnsuitableSectionOnlyArgs() const323 const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
324 {
325     std::set<std::string> unsuitables;
326 
327     LOCK(cs_args);
328 
329     // if there's no section selected, don't worry
330     if (m_network.empty()) return std::set<std::string> {};
331 
332     // if it's okay to use the default section for this network, don't worry
333     if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
334 
335     for (const auto& arg : m_network_only_args) {
336         std::pair<bool, std::string> found_result;
337 
338         // if this option is overridden it's fine
339         found_result = ArgsManagerHelper::GetArgHelper(m_override_args, arg);
340         if (found_result.first) continue;
341 
342         // if there's a network-specific value for this option, it's fine
343         found_result = ArgsManagerHelper::GetArgHelper(m_config_args, ArgsManagerHelper::NetworkArg(*this, arg));
344         if (found_result.first) continue;
345 
346         // if there isn't a default value for this option, it's fine
347         found_result = ArgsManagerHelper::GetArgHelper(m_config_args, arg);
348         if (!found_result.first) continue;
349 
350         // otherwise, issue a warning
351         unsuitables.insert(arg);
352     }
353     return unsuitables;
354 }
355 
356 
GetUnrecognizedSections() const357 const std::set<std::string> ArgsManager::GetUnrecognizedSections() const
358 {
359     // Section names to be recognized in the config file.
360     static const std::set<std::string> available_sections{
361         CBaseChainParams::REGTEST,
362         CBaseChainParams::TESTNET,
363         CBaseChainParams::MAIN
364     };
365     std::set<std::string> diff;
366 
367     LOCK(cs_args);
368     std::set_difference(
369         m_config_sections.begin(), m_config_sections.end(),
370         available_sections.begin(), available_sections.end(),
371         std::inserter(diff, diff.end()));
372     return diff;
373 }
374 
SelectConfigNetwork(const std::string & network)375 void ArgsManager::SelectConfigNetwork(const std::string& network)
376 {
377     LOCK(cs_args);
378     m_network = network;
379 }
380 
ParseParameters(int argc,const char * const argv[],std::string & error)381 bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
382 {
383     LOCK(cs_args);
384     m_override_args.clear();
385 
386     for (int i = 1; i < argc; i++) {
387         std::string key(argv[i]);
388         std::string val;
389         size_t is_index = key.find('=');
390         if (is_index != std::string::npos) {
391             val = key.substr(is_index + 1);
392             key.erase(is_index);
393         }
394 #ifdef WIN32
395         std::transform(key.begin(), key.end(), key.begin(), ToLower);
396         if (key[0] == '/')
397             key[0] = '-';
398 #endif
399 
400         if (key[0] != '-')
401             break;
402 
403         // Transform --foo to -foo
404         if (key.length() > 1 && key[1] == '-')
405             key.erase(0, 1);
406 
407         // Check for -nofoo
408         if (InterpretNegatedOption(key, val)) {
409             m_override_args[key].clear();
410         } else {
411             m_override_args[key].push_back(val);
412         }
413 
414         // Check that the arg is known
415         if (!(IsSwitchChar(key[0]) && key.size() == 1)) {
416             if (!IsArgKnown(key)) {
417                 error = strprintf("Invalid parameter %s", key.c_str());
418                 return false;
419             }
420         }
421     }
422 
423     // we do not allow -includeconf from command line, so we clear it here
424     auto it = m_override_args.find("-includeconf");
425     if (it != m_override_args.end()) {
426         if (it->second.size() > 0) {
427             for (const auto& ic : it->second) {
428                 error += "-includeconf cannot be used from commandline; -includeconf=" + ic + "\n";
429             }
430             return false;
431         }
432     }
433     return true;
434 }
435 
IsArgKnown(const std::string & key) const436 bool ArgsManager::IsArgKnown(const std::string& key) const
437 {
438     size_t option_index = key.find('.');
439     std::string arg_no_net;
440     if (option_index == std::string::npos) {
441         arg_no_net = key;
442     } else {
443         arg_no_net = std::string("-") + key.substr(option_index + 1, std::string::npos);
444     }
445 
446     LOCK(cs_args);
447     for (const auto& arg_map : m_available_args) {
448         if (arg_map.second.count(arg_no_net)) return true;
449     }
450     return false;
451 }
452 
GetArgs(const std::string & strArg) const453 std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
454 {
455     std::vector<std::string> result = {};
456     if (IsArgNegated(strArg)) return result; // special case
457 
458     LOCK(cs_args);
459 
460     ArgsManagerHelper::AddArgs(result, m_override_args, strArg);
461     if (!m_network.empty()) {
462         ArgsManagerHelper::AddArgs(result, m_config_args, ArgsManagerHelper::NetworkArg(*this, strArg));
463     }
464 
465     if (ArgsManagerHelper::UseDefaultSection(*this, strArg)) {
466         ArgsManagerHelper::AddArgs(result, m_config_args, strArg);
467     }
468 
469     return result;
470 }
471 
IsArgSet(const std::string & strArg) const472 bool ArgsManager::IsArgSet(const std::string& strArg) const
473 {
474     if (IsArgNegated(strArg)) return true; // special case
475     return ArgsManagerHelper::GetArg(*this, strArg).first;
476 }
477 
IsArgNegated(const std::string & strArg) const478 bool ArgsManager::IsArgNegated(const std::string& strArg) const
479 {
480     LOCK(cs_args);
481 
482     const auto& ov = m_override_args.find(strArg);
483     if (ov != m_override_args.end()) return ov->second.empty();
484 
485     if (!m_network.empty()) {
486         const auto& cfs = m_config_args.find(ArgsManagerHelper::NetworkArg(*this, strArg));
487         if (cfs != m_config_args.end()) return cfs->second.empty();
488     }
489 
490     const auto& cf = m_config_args.find(strArg);
491     if (cf != m_config_args.end()) return cf->second.empty();
492 
493     return false;
494 }
495 
GetArg(const std::string & strArg,const std::string & strDefault) const496 std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
497 {
498     if (IsArgNegated(strArg)) return "0";
499     std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
500     if (found_res.first) return found_res.second;
501     return strDefault;
502 }
503 
GetArg(const std::string & strArg,int64_t nDefault) const504 int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
505 {
506     if (IsArgNegated(strArg)) return 0;
507     std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
508     if (found_res.first) return atoi64(found_res.second);
509     return nDefault;
510 }
511 
GetBoolArg(const std::string & strArg,bool fDefault) const512 bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
513 {
514     if (IsArgNegated(strArg)) return false;
515     std::pair<bool,std::string> found_res = ArgsManagerHelper::GetArg(*this, strArg);
516     if (found_res.first) return InterpretBool(found_res.second);
517     return fDefault;
518 }
519 
SoftSetArg(const std::string & strArg,const std::string & strValue)520 bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
521 {
522     LOCK(cs_args);
523     if (IsArgSet(strArg)) return false;
524     ForceSetArg(strArg, strValue);
525     return true;
526 }
527 
SoftSetBoolArg(const std::string & strArg,bool fValue)528 bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
529 {
530     if (fValue)
531         return SoftSetArg(strArg, std::string("1"));
532     else
533         return SoftSetArg(strArg, std::string("0"));
534 }
535 
ForceSetArg(const std::string & strArg,const std::string & strValue)536 void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
537 {
538     LOCK(cs_args);
539     m_override_args[strArg] = {strValue};
540 }
541 
AddArg(const std::string & name,const std::string & help,const bool debug_only,const OptionsCategory & cat)542 void ArgsManager::AddArg(const std::string& name, const std::string& help, const bool debug_only, const OptionsCategory& cat)
543 {
544     // Split arg name from its help param
545     size_t eq_index = name.find('=');
546     if (eq_index == std::string::npos) {
547         eq_index = name.size();
548     }
549 
550     LOCK(cs_args);
551     std::map<std::string, Arg>& arg_map = m_available_args[cat];
552     auto ret = arg_map.emplace(name.substr(0, eq_index), Arg(name.substr(eq_index, name.size() - eq_index), help, debug_only));
553     assert(ret.second); // Make sure an insertion actually happened
554 }
555 
AddHiddenArgs(const std::vector<std::string> & names)556 void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
557 {
558     for (const std::string& name : names) {
559         AddArg(name, "", false, OptionsCategory::HIDDEN);
560     }
561 }
562 
GetHelpMessage() const563 std::string ArgsManager::GetHelpMessage() const
564 {
565     const bool show_debug = gArgs.GetBoolArg("-help-debug", false);
566 
567     std::string usage = "";
568     LOCK(cs_args);
569     for (const auto& arg_map : m_available_args) {
570         switch(arg_map.first) {
571             case OptionsCategory::OPTIONS:
572                 usage += HelpMessageGroup("Options:");
573                 break;
574             case OptionsCategory::CONNECTION:
575                 usage += HelpMessageGroup("Connection options:");
576                 break;
577             case OptionsCategory::ZMQ:
578                 usage += HelpMessageGroup("ZeroMQ notification options:");
579                 break;
580             case OptionsCategory::DEBUG_TEST:
581                 usage += HelpMessageGroup("Debugging/Testing options:");
582                 break;
583             case OptionsCategory::NODE_RELAY:
584                 usage += HelpMessageGroup("Node relay options:");
585                 break;
586             case OptionsCategory::BLOCK_CREATION:
587                 usage += HelpMessageGroup("Block creation options:");
588                 break;
589             case OptionsCategory::RPC:
590                 usage += HelpMessageGroup("RPC server options:");
591                 break;
592             case OptionsCategory::WALLET:
593                 usage += HelpMessageGroup("Wallet options:");
594                 break;
595             case OptionsCategory::WALLET_DEBUG_TEST:
596                 if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
597                 break;
598             case OptionsCategory::CHAINPARAMS:
599                 usage += HelpMessageGroup("Chain selection options:");
600                 break;
601             case OptionsCategory::GUI:
602                 usage += HelpMessageGroup("UI Options:");
603                 break;
604             case OptionsCategory::COMMANDS:
605                 usage += HelpMessageGroup("Commands:");
606                 break;
607             case OptionsCategory::REGISTER_COMMANDS:
608                 usage += HelpMessageGroup("Register Commands:");
609                 break;
610             default:
611                 break;
612         }
613 
614         // When we get to the hidden options, stop
615         if (arg_map.first == OptionsCategory::HIDDEN) break;
616 
617         for (const auto& arg : arg_map.second) {
618             if (show_debug || !arg.second.m_debug_only) {
619                 std::string name;
620                 if (arg.second.m_help_param.empty()) {
621                     name = arg.first;
622                 } else {
623                     name = arg.first + arg.second.m_help_param;
624                 }
625                 usage += HelpMessageOpt(name, arg.second.m_help_text);
626             }
627         }
628     }
629     return usage;
630 }
631 
HelpRequested(const ArgsManager & args)632 bool HelpRequested(const ArgsManager& args)
633 {
634     return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
635 }
636 
SetupHelpOptions(ArgsManager & args)637 void SetupHelpOptions(ArgsManager& args)
638 {
639     args.AddArg("-?", "Print this help message and exit", false, OptionsCategory::OPTIONS);
640     args.AddHiddenArgs({"-h", "-help"});
641 }
642 
643 static const int screenWidth = 79;
644 static const int optIndent = 2;
645 static const int msgIndent = 7;
646 
HelpMessageGroup(const std::string & message)647 std::string HelpMessageGroup(const std::string &message) {
648     return std::string(message) + std::string("\n\n");
649 }
650 
HelpMessageOpt(const std::string & option,const std::string & message)651 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
652     return std::string(optIndent,' ') + std::string(option) +
653            std::string("\n") + std::string(msgIndent,' ') +
654            FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
655            std::string("\n\n");
656 }
657 
FormatException(const std::exception * pex,const char * pszThread)658 static std::string FormatException(const std::exception* pex, const char* pszThread)
659 {
660 #ifdef WIN32
661     char pszModule[MAX_PATH] = "";
662     GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
663 #else
664     const char* pszModule = "litecoin";
665 #endif
666     if (pex)
667         return strprintf(
668             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
669     else
670         return strprintf(
671             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
672 }
673 
PrintExceptionContinue(const std::exception * pex,const char * pszThread)674 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
675 {
676     std::string message = FormatException(pex, pszThread);
677     LogPrintf("\n\n************************\n%s\n", message);
678     tfm::format(std::cerr, "\n\n************************\n%s\n", message.c_str());
679 }
680 
GetDefaultDataDir()681 fs::path GetDefaultDataDir()
682 {
683     // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
684     // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
685     // Mac: ~/Library/Application Support/Bitcoin
686     // Unix: ~/.bitcoin
687 #ifdef WIN32
688     // Windows
689     return GetSpecialFolderPath(CSIDL_APPDATA) / "Litecoin";
690 #else
691     fs::path pathRet;
692     char* pszHome = getenv("HOME");
693     if (pszHome == nullptr || strlen(pszHome) == 0)
694         pathRet = fs::path("/");
695     else
696         pathRet = fs::path(pszHome);
697 #ifdef MAC_OSX
698     // Mac
699     return pathRet / "Library/Application Support/Litecoin";
700 #else
701     // Unix
702     return pathRet / ".litecoin";
703 #endif
704 #endif
705 }
706 
707 static fs::path g_blocks_path_cache_net_specific;
708 static fs::path pathCached;
709 static fs::path pathCachedNetSpecific;
710 static CCriticalSection csPathCached;
711 
GetBlocksDir()712 const fs::path &GetBlocksDir()
713 {
714 
715     LOCK(csPathCached);
716 
717     fs::path &path = g_blocks_path_cache_net_specific;
718 
719     // This can be called during exceptions by LogPrintf(), so we cache the
720     // value so we don't have to do memory allocations after that.
721     if (!path.empty())
722         return path;
723 
724     if (gArgs.IsArgSet("-blocksdir")) {
725         path = fs::system_complete(gArgs.GetArg("-blocksdir", ""));
726         if (!fs::is_directory(path)) {
727             path = "";
728             return path;
729         }
730     } else {
731         path = GetDataDir(false);
732     }
733 
734     path /= BaseParams().DataDir();
735     path /= "blocks";
736     fs::create_directories(path);
737     return path;
738 }
739 
GetDataDir(bool fNetSpecific)740 const fs::path &GetDataDir(bool fNetSpecific)
741 {
742 
743     LOCK(csPathCached);
744 
745     fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
746 
747     // This can be called during exceptions by LogPrintf(), so we cache the
748     // value so we don't have to do memory allocations after that.
749     if (!path.empty())
750         return path;
751 
752     if (gArgs.IsArgSet("-datadir")) {
753         path = fs::system_complete(gArgs.GetArg("-datadir", ""));
754         if (!fs::is_directory(path)) {
755             path = "";
756             return path;
757         }
758     } else {
759         path = GetDefaultDataDir();
760     }
761     if (fNetSpecific)
762         path /= BaseParams().DataDir();
763 
764     if (fs::create_directories(path)) {
765         // This is the first run, create wallets subdirectory too
766         fs::create_directories(path / "wallets");
767     }
768 
769     return path;
770 }
771 
ClearDatadirCache()772 void ClearDatadirCache()
773 {
774     LOCK(csPathCached);
775 
776     pathCached = fs::path();
777     pathCachedNetSpecific = fs::path();
778     g_blocks_path_cache_net_specific = fs::path();
779 }
780 
GetConfigFile(const std::string & confPath)781 fs::path GetConfigFile(const std::string& confPath)
782 {
783     return AbsPathForConfigVal(fs::path(confPath), false);
784 }
785 
TrimString(const std::string & str,const std::string & pattern)786 static std::string TrimString(const std::string& str, const std::string& pattern)
787 {
788     std::string::size_type front = str.find_first_not_of(pattern);
789     if (front == std::string::npos) {
790         return std::string();
791     }
792     std::string::size_type end = str.find_last_not_of(pattern);
793     return str.substr(front, end - front + 1);
794 }
795 
GetConfigOptions(std::istream & stream,std::string & error,std::vector<std::pair<std::string,std::string>> & options,std::set<std::string> & sections)796 static bool GetConfigOptions(std::istream& stream, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::set<std::string>& sections)
797 {
798     std::string str, prefix;
799     std::string::size_type pos;
800     int linenr = 1;
801     while (std::getline(stream, str)) {
802         bool used_hash = false;
803         if ((pos = str.find('#')) != std::string::npos) {
804             str = str.substr(0, pos);
805             used_hash = true;
806         }
807         const static std::string pattern = " \t\r\n";
808         str = TrimString(str, pattern);
809         if (!str.empty()) {
810             if (*str.begin() == '[' && *str.rbegin() == ']') {
811                 const std::string section = str.substr(1, str.size() - 2);
812                 sections.insert(section);
813                 prefix = section + '.';
814             } else if (*str.begin() == '-') {
815                 error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
816                 return false;
817             } else if ((pos = str.find('=')) != std::string::npos) {
818                 std::string name = prefix + TrimString(str.substr(0, pos), pattern);
819                 std::string value = TrimString(str.substr(pos + 1), pattern);
820                 if (used_hash && name.find("rpcpassword") != std::string::npos) {
821                     error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
822                     return false;
823                 }
824                 options.emplace_back(name, value);
825                 if ((pos = name.rfind('.')) != std::string::npos) {
826                     sections.insert(name.substr(0, pos));
827                 }
828             } else {
829                 error = strprintf("parse error on line %i: %s", linenr, str);
830                 if (str.size() >= 2 && str.substr(0, 2) == "no") {
831                     error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
832                 }
833                 return false;
834             }
835         }
836         ++linenr;
837     }
838     return true;
839 }
840 
ReadConfigStream(std::istream & stream,std::string & error,bool ignore_invalid_keys)841 bool ArgsManager::ReadConfigStream(std::istream& stream, std::string& error, bool ignore_invalid_keys)
842 {
843     LOCK(cs_args);
844     std::vector<std::pair<std::string, std::string>> options;
845     m_config_sections.clear();
846     if (!GetConfigOptions(stream, error, options, m_config_sections)) {
847         return false;
848     }
849     for (const std::pair<std::string, std::string>& option : options) {
850         std::string strKey = std::string("-") + option.first;
851         std::string strValue = option.second;
852 
853         if (InterpretNegatedOption(strKey, strValue)) {
854             m_config_args[strKey].clear();
855         } else {
856             m_config_args[strKey].push_back(strValue);
857         }
858 
859         // Check that the arg is known
860         if (!IsArgKnown(strKey)) {
861             if (!ignore_invalid_keys) {
862                 error = strprintf("Invalid configuration value %s", option.first.c_str());
863                 return false;
864             } else {
865                 LogPrintf("Ignoring unknown configuration value %s\n", option.first);
866             }
867         }
868     }
869     return true;
870 }
871 
ReadConfigFiles(std::string & error,bool ignore_invalid_keys)872 bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
873 {
874     {
875         LOCK(cs_args);
876         m_config_args.clear();
877     }
878 
879     const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
880     fsbridge::ifstream stream(GetConfigFile(confPath));
881 
882     // ok to not have a config file
883     if (stream.good()) {
884         if (!ReadConfigStream(stream, error, ignore_invalid_keys)) {
885             return false;
886         }
887         // if there is an -includeconf in the override args, but it is empty, that means the user
888         // passed '-noincludeconf' on the command line, in which case we should not include anything
889         bool emptyIncludeConf;
890         {
891             LOCK(cs_args);
892             emptyIncludeConf = m_override_args.count("-includeconf") == 0;
893         }
894         if (emptyIncludeConf) {
895             std::string chain_id = GetChainName();
896             std::vector<std::string> includeconf(GetArgs("-includeconf"));
897             {
898                 // We haven't set m_network yet (that happens in SelectParams()), so manually check
899                 // for network.includeconf args.
900                 std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf"));
901                 includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
902             }
903 
904             // Remove -includeconf from configuration, so we can warn about recursion
905             // later
906             {
907                 LOCK(cs_args);
908                 m_config_args.erase("-includeconf");
909                 m_config_args.erase(std::string("-") + chain_id + ".includeconf");
910             }
911 
912             for (const std::string& to_include : includeconf) {
913                 fsbridge::ifstream include_config(GetConfigFile(to_include));
914                 if (include_config.good()) {
915                     if (!ReadConfigStream(include_config, error, ignore_invalid_keys)) {
916                         return false;
917                     }
918                     LogPrintf("Included configuration file %s\n", to_include.c_str());
919                 } else {
920                     error = "Failed to include configuration file " + to_include;
921                     return false;
922                 }
923             }
924 
925             // Warn about recursive -includeconf
926             includeconf = GetArgs("-includeconf");
927             {
928                 std::vector<std::string> includeconf_net(GetArgs(std::string("-") + chain_id + ".includeconf"));
929                 includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
930                 std::string chain_id_final = GetChainName();
931                 if (chain_id_final != chain_id) {
932                     // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
933                     includeconf_net = GetArgs(std::string("-") + chain_id_final + ".includeconf");
934                     includeconf.insert(includeconf.end(), includeconf_net.begin(), includeconf_net.end());
935                 }
936             }
937             for (const std::string& to_include : includeconf) {
938                 tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", to_include.c_str());
939             }
940         }
941     }
942 
943     // If datadir is changed in .conf file:
944     ClearDatadirCache();
945     if (!fs::is_directory(GetDataDir(false))) {
946         error = strprintf("specified data directory \"%s\" does not exist.", gArgs.GetArg("-datadir", "").c_str());
947         return false;
948     }
949     return true;
950 }
951 
GetChainName() const952 std::string ArgsManager::GetChainName() const
953 {
954     LOCK(cs_args);
955     bool fRegTest = ArgsManagerHelper::GetNetBoolArg(*this, "-regtest");
956     bool fTestNet = ArgsManagerHelper::GetNetBoolArg(*this, "-testnet");
957 
958     if (fTestNet && fRegTest)
959         throw std::runtime_error("Invalid combination of -regtest and -testnet.");
960     if (fRegTest)
961         return CBaseChainParams::REGTEST;
962     if (fTestNet)
963         return CBaseChainParams::TESTNET;
964     return CBaseChainParams::MAIN;
965 }
966 
RenameOver(fs::path src,fs::path dest)967 bool RenameOver(fs::path src, fs::path dest)
968 {
969 #ifdef WIN32
970     return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
971                        MOVEFILE_REPLACE_EXISTING) != 0;
972 #else
973     int rc = std::rename(src.string().c_str(), dest.string().c_str());
974     return (rc == 0);
975 #endif /* WIN32 */
976 }
977 
978 /**
979  * Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
980  * Specifically handles case where path p exists, but it wasn't possible for the user to
981  * write to the parent directory.
982  */
TryCreateDirectories(const fs::path & p)983 bool TryCreateDirectories(const fs::path& p)
984 {
985     try
986     {
987         return fs::create_directories(p);
988     } catch (const fs::filesystem_error&) {
989         if (!fs::exists(p) || !fs::is_directory(p))
990             throw;
991     }
992 
993     // create_directories didn't create the directory, it had to have existed already
994     return false;
995 }
996 
FileCommit(FILE * file)997 bool FileCommit(FILE *file)
998 {
999     if (fflush(file) != 0) { // harmless if redundantly called
1000         LogPrintf("%s: fflush failed: %d\n", __func__, errno);
1001         return false;
1002     }
1003 #ifdef WIN32
1004     HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1005     if (FlushFileBuffers(hFile) == 0) {
1006         LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1007         return false;
1008     }
1009 #else
1010     #if defined(__linux__) || defined(__NetBSD__)
1011     if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
1012         LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
1013         return false;
1014     }
1015     #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1016     if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
1017         LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1018         return false;
1019     }
1020     #else
1021     if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1022         LogPrintf("%s: fsync failed: %d\n", __func__, errno);
1023         return false;
1024     }
1025     #endif
1026 #endif
1027     return true;
1028 }
1029 
TruncateFile(FILE * file,unsigned int length)1030 bool TruncateFile(FILE *file, unsigned int length) {
1031 #if defined(WIN32)
1032     return _chsize(_fileno(file), length) == 0;
1033 #else
1034     return ftruncate(fileno(file), length) == 0;
1035 #endif
1036 }
1037 
1038 /**
1039  * this function tries to raise the file descriptor limit to the requested number.
1040  * It returns the actual file descriptor limit (which may be more or less than nMinFD)
1041  */
RaiseFileDescriptorLimit(int nMinFD)1042 int RaiseFileDescriptorLimit(int nMinFD) {
1043 #if defined(WIN32)
1044     return 2048;
1045 #else
1046     struct rlimit limitFD;
1047     if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1048         if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1049             limitFD.rlim_cur = nMinFD;
1050             if (limitFD.rlim_cur > limitFD.rlim_max)
1051                 limitFD.rlim_cur = limitFD.rlim_max;
1052             setrlimit(RLIMIT_NOFILE, &limitFD);
1053             getrlimit(RLIMIT_NOFILE, &limitFD);
1054         }
1055         return limitFD.rlim_cur;
1056     }
1057     return nMinFD; // getrlimit failed, assume it's fine
1058 #endif
1059 }
1060 
1061 /**
1062  * this function tries to make a particular range of a file allocated (corresponding to disk space)
1063  * it is advisory, and the range specified in the arguments will never contain live data
1064  */
AllocateFileRange(FILE * file,unsigned int offset,unsigned int length)1065 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1066 #if defined(WIN32)
1067     // Windows-specific version
1068     HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1069     LARGE_INTEGER nFileSize;
1070     int64_t nEndPos = (int64_t)offset + length;
1071     nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1072     nFileSize.u.HighPart = nEndPos >> 32;
1073     SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1074     SetEndOfFile(hFile);
1075 #elif defined(MAC_OSX)
1076     // OSX specific version
1077     fstore_t fst;
1078     fst.fst_flags = F_ALLOCATECONTIG;
1079     fst.fst_posmode = F_PEOFPOSMODE;
1080     fst.fst_offset = 0;
1081     fst.fst_length = (off_t)offset + length;
1082     fst.fst_bytesalloc = 0;
1083     if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1084         fst.fst_flags = F_ALLOCATEALL;
1085         fcntl(fileno(file), F_PREALLOCATE, &fst);
1086     }
1087     ftruncate(fileno(file), fst.fst_length);
1088 #else
1089     #if defined(__linux__)
1090     // Version using posix_fallocate
1091     off_t nEndPos = (off_t)offset + length;
1092     if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
1093     #endif
1094     // Fallback version
1095     // TODO: just write one byte per block
1096     static const char buf[65536] = {};
1097     if (fseek(file, offset, SEEK_SET)) {
1098         return;
1099     }
1100     while (length > 0) {
1101         unsigned int now = 65536;
1102         if (length < now)
1103             now = length;
1104         fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1105         length -= now;
1106     }
1107 #endif
1108 }
1109 
1110 #ifdef WIN32
GetSpecialFolderPath(int nFolder,bool fCreate)1111 fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
1112 {
1113     WCHAR pszPath[MAX_PATH] = L"";
1114 
1115     if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
1116     {
1117         return fs::path(pszPath);
1118     }
1119 
1120     LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1121     return fs::path("");
1122 }
1123 #endif
1124 
runCommand(const std::string & strCommand)1125 void runCommand(const std::string& strCommand)
1126 {
1127     if (strCommand.empty()) return;
1128 #ifndef WIN32
1129     int nErr = ::system(strCommand.c_str());
1130 #else
1131     int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
1132 #endif
1133     if (nErr)
1134         LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1135 }
1136 
RenameThread(const char * name)1137 void RenameThread(const char* name)
1138 {
1139 #if defined(PR_SET_NAME)
1140     // Only the first 15 characters are used (16 - NUL terminator)
1141     ::prctl(PR_SET_NAME, name, 0, 0, 0);
1142 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
1143     pthread_set_name_np(pthread_self(), name);
1144 
1145 #elif defined(MAC_OSX)
1146     pthread_setname_np(name);
1147 #else
1148     // Prevent warnings for unused parameters...
1149     (void)name;
1150 #endif
1151 }
1152 
SetupEnvironment()1153 void SetupEnvironment()
1154 {
1155 #ifdef HAVE_MALLOPT_ARENA_MAX
1156     // glibc-specific: On 32-bit systems set the number of arenas to 1.
1157     // By default, since glibc 2.10, the C library will create up to two heap
1158     // arenas per core. This is known to cause excessive virtual address space
1159     // usage in our usage. Work around it by setting the maximum number of
1160     // arenas to 1.
1161     if (sizeof(void*) == 4) {
1162         mallopt(M_ARENA_MAX, 1);
1163     }
1164 #endif
1165     // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
1166     // may be invalid, in which case the "C" locale is used as fallback.
1167 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
1168     try {
1169         std::locale(""); // Raises a runtime error if current locale is invalid
1170     } catch (const std::runtime_error&) {
1171         setenv("LC_ALL", "C", 1);
1172     }
1173 #elif defined(WIN32)
1174     // Set the default input/output charset is utf-8
1175     SetConsoleCP(CP_UTF8);
1176     SetConsoleOutputCP(CP_UTF8);
1177 #endif
1178     // The path locale is lazy initialized and to avoid deinitialization errors
1179     // in multithreading environments, it is set explicitly by the main thread.
1180     // A dummy locale is used to extract the internal default locale, used by
1181     // fs::path, which is then used to explicitly imbue the path.
1182     std::locale loc = fs::path::imbue(std::locale::classic());
1183 #ifndef WIN32
1184     fs::path::imbue(loc);
1185 #else
1186     fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
1187 #endif
1188 }
1189 
SetupNetworking()1190 bool SetupNetworking()
1191 {
1192 #ifdef WIN32
1193     // Initialize Windows Sockets
1194     WSADATA wsadata;
1195     int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1196     if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1197         return false;
1198 #endif
1199     return true;
1200 }
1201 
GetNumCores()1202 int GetNumCores()
1203 {
1204     return std::thread::hardware_concurrency();
1205 }
1206 
CopyrightHolders(const std::string & strPrefix)1207 std::string CopyrightHolders(const std::string& strPrefix)
1208 {
1209     const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS), COPYRIGHT_HOLDERS_SUBSTITUTION);
1210     std::string strCopyrightHolders = strPrefix + copyright_devs;
1211 
1212     // Make sure Bitcoin Core copyright is not removed by accident
1213     if (copyright_devs.find("Bitcoin Core") == std::string::npos) {
1214         std::string strYear = strPrefix;
1215         strYear.replace(strYear.find("2011"), sizeof("2011")-1, "2009");
1216         strCopyrightHolders += "\n" + strYear + "The Bitcoin Core developers";
1217     }
1218     return strCopyrightHolders;
1219 }
1220 
1221 // Obtain the application startup time (used for uptime calculation)
GetStartupTime()1222 int64_t GetStartupTime()
1223 {
1224     return nStartupTime;
1225 }
1226 
AbsPathForConfigVal(const fs::path & path,bool net_specific)1227 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
1228 {
1229     return fs::absolute(path, GetDataDir(net_specific));
1230 }
1231 
ScheduleBatchPriority()1232 int ScheduleBatchPriority()
1233 {
1234 #ifdef SCHED_BATCH
1235     const static sched_param param{};
1236     if (int ret = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param)) {
1237         LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(errno));
1238         return ret;
1239     }
1240     return 0;
1241 #else
1242     return 1;
1243 #endif
1244 }
1245 
1246 namespace util {
1247 #ifdef WIN32
WinCmdLineArgs()1248 WinCmdLineArgs::WinCmdLineArgs()
1249 {
1250     wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1251     std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
1252     argv = new char*[argc];
1253     args.resize(argc);
1254     for (int i = 0; i < argc; i++) {
1255         args[i] = utf8_cvt.to_bytes(wargv[i]);
1256         argv[i] = &*args[i].begin();
1257     }
1258     LocalFree(wargv);
1259 }
1260 
~WinCmdLineArgs()1261 WinCmdLineArgs::~WinCmdLineArgs()
1262 {
1263     delete[] argv;
1264 }
1265 
get()1266 std::pair<int, char**> WinCmdLineArgs::get()
1267 {
1268     return std::make_pair(argc, argv);
1269 }
1270 #endif
1271 } // namespace util
1272