From a8769a3cda4c4a32e4dcd457967873fd538928af Mon Sep 17 00:00:00 2001 From: PastaPastaPasta <6443210+PastaPastaPasta@users.noreply.github.com> Date: Sun, 24 Oct 2021 06:51:47 -0400 Subject: [PATCH] Merge bitcoin#16205: Refactor: Replace fprintf with tfm::format (#4531) * tinyformat: Add doc to Bitcoin Core specific strprintf * scripted-diff: Replace fprintf with tfm::format -BEGIN VERIFY SCRIPT- sed -i --regexp-extended -e 's/fprintf\(std(err|out), /tfm::format(std::c\1, /g' $(git grep -l 'fprintf(' -- ':(exclude)src/crypto' ':(exclude)src/leveldb' ':(exclude)src/univalue' ':(exclude)src/secp256k1') -END VERIFY SCRIPT- * Replace remaining fprintf with tfm::format manually * fixes Co-authored-by: MarcoFalke --- src/bench/bench_dash.cpp | 2 +- src/dash-cli.cpp | 18 +++++++++--------- src/dash-tx.cpp | 16 ++++++++-------- src/dashd.cpp | 20 ++++++++++---------- src/init.cpp | 5 ++--- src/logging.h | 2 +- src/noui.cpp | 2 +- src/qt/utilitydialog.cpp | 2 +- src/stacktraces.cpp | 2 +- src/sync.cpp | 8 ++++---- src/tinyformat.h | 1 - src/util/system.cpp | 4 ++-- src/wallet/wallet.cpp | 8 ++++---- test/lint/lint-format-strings.sh | 1 + test/lint/lint-locale-dependence.sh | 6 ++---- 15 files changed, 47 insertions(+), 50 deletions(-) diff --git a/src/bench/bench_dash.cpp b/src/bench/bench_dash.cpp index 9f172b7337..a1439fb6ec 100644 --- a/src/bench/bench_dash.cpp +++ b/src/bench/bench_dash.cpp @@ -63,7 +63,7 @@ int main(int argc, char** argv) SetupBenchArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { - fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str()); + tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str()); return EXIT_FAILURE; } diff --git a/src/dash-cli.cpp b/src/dash-cli.cpp index 6f8df429b6..d04264cc62 100644 --- a/src/dash-cli.cpp +++ b/src/dash-cli.cpp @@ -107,7 +107,7 @@ static int AppInitRPC(int argc, char* argv[]) SetupCliArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { - fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str()); + tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str()); return EXIT_FAILURE; } @@ -127,31 +127,31 @@ static int AppInitRPC(int argc, char* argv[]) strUsage += "\n" + gArgs.GetHelpMessage(); } - fprintf(stdout, "%s", strUsage.c_str()); + tfm::format(std::cout, "%s", strUsage.c_str()); if (argc < 2) { - fprintf(stderr, "Error: too few parameters\n"); + tfm::format(std::cerr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } bool datadirFromCmdLine = gArgs.IsArgSet("-datadir"); if (datadirFromCmdLine && !fs::is_directory(GetDataDir(false))) { - fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); + tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return EXIT_FAILURE; } if (!gArgs.ReadConfigFiles(error, true)) { - fprintf(stderr, "Error reading configuration file: %s\n", error.c_str()); + tfm::format(std::cerr, "Error reading configuration file: %s\n", error.c_str()); return EXIT_FAILURE; } if (!datadirFromCmdLine && !fs::is_directory(GetDataDir(false))) { - fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); + tfm::format(std::cerr, "Error: Specified data directory \"%s\" from config file does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return EXIT_FAILURE; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) try { SelectBaseParams(gArgs.GetChainName()); } catch (const std::exception& e) { - fprintf(stderr, "Error: %s\n", e.what()); + tfm::format(std::cerr, "Error: %s\n", e.what()); return EXIT_FAILURE; } return CONTINUE_EXECUTION; @@ -528,7 +528,7 @@ static int CommandLineRPC(int argc, char *argv[]) } if (strPrint != "") { - fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); + tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint.c_str()); } return nRet; } @@ -544,7 +544,7 @@ int main(int argc, char* argv[]) #endif SetupEnvironment(); if (!SetupNetworking()) { - fprintf(stderr, "Error: Initializing networking failed\n"); + tfm::format(std::cerr, "Error: Initializing networking failed\n"); return EXIT_FAILURE; } event_set_log_callback(&libevent_log_cb); diff --git a/src/dash-tx.cpp b/src/dash-tx.cpp index 2d1ac13ded..ff31a7852c 100644 --- a/src/dash-tx.cpp +++ b/src/dash-tx.cpp @@ -81,7 +81,7 @@ static int AppInitRawTx(int argc, char* argv[]) SetupBitcoinTxArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { - fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str()); + tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str()); return EXIT_FAILURE; } @@ -94,7 +94,7 @@ static int AppInitRawTx(int argc, char* argv[]) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { - fprintf(stderr, "Error: %s\n", e.what()); + tfm::format(std::cerr, "Error: %s\n", e.what()); return EXIT_FAILURE; } @@ -108,10 +108,10 @@ static int AppInitRawTx(int argc, char* argv[]) "\n"; strUsage += gArgs.GetHelpMessage(); - fprintf(stdout, "%s", strUsage.c_str()); + tfm::format(std::cout, "%s", strUsage.c_str()); if (argc < 2) { - fprintf(stderr, "Error: too few parameters\n"); + tfm::format(std::cerr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; @@ -679,21 +679,21 @@ static void OutputTxJSON(const CTransaction& tx) TxToUniv(tx, uint256(), entry); std::string jsonOutput = entry.write(4); - fprintf(stdout, "%s\n", jsonOutput.c_str()); + tfm::format(std::cout, "%s\n", jsonOutput.c_str()); } static void OutputTxHash(const CTransaction& tx) { std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id) - fprintf(stdout, "%s\n", strHexHash.c_str()); + tfm::format(std::cout, "%s\n", strHexHash.c_str()); } static void OutputTxHex(const CTransaction& tx) { std::string strHex = EncodeHexTx(tx); - fprintf(stdout, "%s\n", strHex.c_str()); + tfm::format(std::cout, "%s\n", strHex.c_str()); } static void OutputTx(const CTransaction& tx) @@ -784,7 +784,7 @@ static int CommandLineRawTx(int argc, char* argv[]) } if (strPrint != "") { - fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); + tfm::format(nRet == 0 ? std::cout : std::cerr, "%s\n", strPrint.c_str()); } return nRet; } diff --git a/src/dashd.cpp b/src/dashd.cpp index db0846c600..5b4bc0d0b8 100644 --- a/src/dashd.cpp +++ b/src/dashd.cpp @@ -74,7 +74,7 @@ static bool AppInit(int argc, char* argv[]) SetupServerArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { - fprintf(stderr, "Error parsing command line arguments: %s\n", error.c_str()); + tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str()); return false; } @@ -97,7 +97,7 @@ static bool AppInit(int argc, char* argv[]) strUsage += "\n" + gArgs.GetHelpMessage(); } - fprintf(stdout, "%s", strUsage.c_str()); + tfm::format(std::cout, "%s", strUsage.c_str()); return true; } @@ -106,30 +106,30 @@ static bool AppInit(int argc, char* argv[]) bool datadirFromCmdLine = gArgs.IsArgSet("-datadir"); if (datadirFromCmdLine && !fs::is_directory(GetDataDir(false))) { - fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); + tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } if (!gArgs.ReadConfigFiles(error, true)) { - fprintf(stderr, "Error reading configuration file: %s\n", error.c_str()); + tfm::format(std::cerr, "Error reading configuration file: %s\n", error.c_str()); return false; } if (!datadirFromCmdLine && !fs::is_directory(GetDataDir(false))) { - fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); + tfm::format(std::cerr, "Error: Specified data directory \"%s\" from config file does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return EXIT_FAILURE; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { - fprintf(stderr, "Error: %s\n", e.what()); + tfm::format(std::cerr, "Error: %s\n", e.what()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { - fprintf(stderr, "Error: Command line contains unexpected token '%s', see dashd -h for a list of options.\n", argv[i]); + tfm::format(std::cerr, "Error: Command line contains unexpected token '%s', see dashd -h for a list of options.\n", argv[i]); return false; } } @@ -161,18 +161,18 @@ static bool AppInit(int argc, char* argv[]) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif - fprintf(stdout, "Dash Core server starting\n"); + tfm::format(std::cout, "Dash Core server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) - fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno)); + tfm::format(std::cerr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #if defined(MAC_OSX) #pragma GCC diagnostic pop #endif #else - fprintf(stderr, "Error: -daemon is not supported on this operating system\n"); + tfm::format(std::cerr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } diff --git a/src/init.cpp b/src/init.cpp index 89dace7cef..6fa98e06b0 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -146,10 +146,9 @@ static fs::path GetPidFile() [[nodiscard]] static bool CreatePidFile() { - FILE* file = fsbridge::fopen(GetPidFile(), "w"); + fsbridge::ofstream file{GetPidFile()}; if (file) { - fprintf(file, "%d\n", getpid()); - fclose(file); + tfm::format(file, "%d\n", getpid()); return true; } else { return InitError(strprintf(_("Unable to create the PID file '%s': %s"), GetPidFile().string(), std::strerror(errno))); diff --git a/src/logging.h b/src/logging.h index 07ee3bff21..14e49993e2 100644 --- a/src/logging.h +++ b/src/logging.h @@ -170,7 +170,7 @@ std::string SafeStringFormat(const std::string& fmt, const Args&... args) return tinyformat::format(fmt, args...); } catch (std::runtime_error& fmterr) { std::string message = tinyformat::format("\n****TINYFORMAT ERROR****\n err=\"%s\"\n fmt=\"%s\"\n", fmterr.what(), fmt); - fprintf(stderr, "%s", message.c_str()); + tfm::format(std::cerr, "%s", message.c_str()); return message; } } diff --git a/src/noui.cpp b/src/noui.cpp index 39efbf6d9d..6a6ab0b0ce 100644 --- a/src/noui.cpp +++ b/src/noui.cpp @@ -44,7 +44,7 @@ bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& ca if (!fSecure) LogPrintf("%s: %s\n", strCaption, message); - fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str()); + tfm::format(std::cerr, "%s: %s\n", strCaption.c_str(), message.c_str()); return false; } diff --git a/src/qt/utilitydialog.cpp b/src/qt/utilitydialog.cpp index 77c7d4885b..599c46df9a 100644 --- a/src/qt/utilitydialog.cpp +++ b/src/qt/utilitydialog.cpp @@ -171,7 +171,7 @@ HelpMessageDialog::~HelpMessageDialog() void HelpMessageDialog::printToConsole() { // On other operating systems, the expected action is to print the message to the console. - fprintf(stdout, "%s\n", qPrintable(text)); + tfm::format(std::cout, "%s\n", qPrintable(text)); } void HelpMessageDialog::showOrPrint() diff --git a/src/stacktraces.cpp b/src/stacktraces.cpp index 98697a6d6e..e81a2bce8e 100644 --- a/src/stacktraces.cpp +++ b/src/stacktraces.cpp @@ -526,7 +526,7 @@ static void PrintCrashInfo(const crash_info& ci) { auto str = GetCrashInfoStr(ci); LogPrintf("%s", str); /* Continued */ - fprintf(stderr, "%s", str.c_str()); + tfm::format(std::cerr, "%s", str.c_str()); fflush(stderr); } diff --git a/src/sync.cpp b/src/sync.cpp index 42cac829b6..fe5b0a267c 100644 --- a/src/sync.cpp +++ b/src/sync.cpp @@ -61,7 +61,7 @@ struct CLockLocation { std::string ToString() const { - return tfm::format( + return strprintf( "'%s' in %s:%s%s (in thread '%s')", mutexName, sourceFile, itostr(sourceLine), (fTry ? " (TRY)" : ""), m_thread_name); } @@ -135,7 +135,7 @@ static void potential_deadlock_detected(const LockPair& mismatch, const LockStac LogPrintf("%s\n", strOutput.c_str()); if (g_debug_lockorder_abort) { - fprintf(stderr, "Assertion failed: detected inconsistent lock order for %s, details in debug log.\n", s2.back().second.ToString().c_str()); + tfm::format(std::cerr, "Assertion failed: detected inconsistent lock order for %s, details in debug log.\n", s2.back().second.ToString().c_str()); abort(); } throw std::logic_error(strprintf("potential deadlock detected: %s -> %s -> %s", mutex_b, mutex_a, mutex_b)); @@ -238,7 +238,7 @@ template void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) { if (LockHeld(cs)) return; - fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); + tfm::format(std::cerr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } template void AssertLockHeldInternal(const char*, const char*, int, Mutex*); @@ -247,7 +247,7 @@ template void AssertLockHeldInternal(const char*, const char*, int, CCriticalSec void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { if (!LockHeld(cs)) return; - fprintf(stderr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); + tfm::format(std::cerr, "Assertion failed: lock %s held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } diff --git a/src/tinyformat.h b/src/tinyformat.h index 98bd87e7a9..f75ec7cfca 100644 --- a/src/tinyformat.h +++ b/src/tinyformat.h @@ -1159,7 +1159,6 @@ std::string format(const std::string &fmt, const Args&... args) } // namespace tinyformat -// Added for Dash Core: /** Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for details) */ #define strprintf tfm::format diff --git a/src/util/system.cpp b/src/util/system.cpp index 551c41ea86..e08f0a2256 100644 --- a/src/util/system.cpp +++ b/src/util/system.cpp @@ -730,7 +730,7 @@ void PrintExceptionContinue(const std::exception_ptr pex, const char* pszExcepti { std::string message = strprintf("\"%s\" raised an exception\n%s", pszExceptionOrigin, GetPrettyExceptionStr(pex)); LogPrintf("\n\n************************\n%s\n", message); - fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); + tfm::format(std::cerr, "\n\n************************\n%s\n", message.c_str()); } fs::path GetDefaultDataDir() @@ -997,7 +997,7 @@ bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys) } } for (const std::string& to_include : includeconf) { - fprintf(stderr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", to_include.c_str()); + tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", to_include.c_str()); } } } else { diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 276f0236aa..aee05b559d 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -897,8 +897,8 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) assert(GetHDChain(hdChainCrypted)); DBG( - printf("EncryptWallet -- current seed: '%s'\n", HexStr(hdChainCurrent.GetSeed()).c_str()); - printf("EncryptWallet -- crypted seed: '%s'\n", HexStr(hdChainCrypted.GetSeed()).c_str()); + tfm::format(std::cout, "EncryptWallet -- current seed: '%s'\n", HexStr(hdChainCurrent.GetSeed()).c_str()); + tfm::format(std::cout, "EncryptWallet -- crypted seed: '%s'\n", HexStr(hdChainCrypted.GetSeed()).c_str()); ); // ids should match, seed hashes should not @@ -1769,8 +1769,8 @@ bool CWallet::GenerateNewHDChainEncrypted(const SecureString& secureMnemonic, co assert(res); DBG( - printf("GenerateNewHDChainEncrypted -- current seed: '%s'\n", HexStr(hdChainTmp.GetSeed()).c_str()); - printf("GenerateNewHDChainEncrypted -- crypted seed: '%s'\n", HexStr(hdChainCrypted.GetSeed()).c_str()); + tfm::format(std::cout, "GenerateNewHDChainEncrypted -- current seed: '%s'\n", HexStr(hdChainTmp.GetSeed()).c_str()); + tfm::format(std::cout, "GenerateNewHDChainEncrypted -- crypted seed: '%s'\n", HexStr(hdChainCrypted.GetSeed()).c_str()); ); // ids should match, seed hashes should not diff --git a/test/lint/lint-format-strings.sh b/test/lint/lint-format-strings.sh index c994ae3f4d..cb630c78ad 100755 --- a/test/lint/lint-format-strings.sh +++ b/test/lint/lint-format-strings.sh @@ -13,6 +13,7 @@ export LC_ALL=C FUNCTION_NAMES_AND_NUMBER_OF_LEADING_ARGUMENTS=( "FatalError,0" "fprintf,1" + "tfm::format,1" # Assuming tfm::::format(std::ostream&, ... "LogConnectFailure,1" "LogPrint,1" "LogPrintf,0" diff --git a/test/lint/lint-locale-dependence.sh b/test/lint/lint-locale-dependence.sh index 79f5b2bb82..1121e779f5 100755 --- a/test/lint/lint-locale-dependence.sh +++ b/test/lint/lint-locale-dependence.sh @@ -10,7 +10,6 @@ KNOWN_VIOLATIONS=( "src/dbwrapper.cpp:.*vsnprintf" "src/httprpc.cpp.*trim" "src/init.cpp:.*atoi" - "src/init.cpp:.*fprintf" "src/qt/rpcconsole.cpp:.*atoi" "src/rest.cpp:.*strtol" "src/rpc/blockchain.cpp.*atoi" @@ -93,7 +92,7 @@ LOCALE_DEPENDENT_FUNCTIONS=( mbtowc # LC_CTYPE mktime normalize # boost::locale::normalize -# printf # LC_NUMERIC + printf # LC_NUMERIC putwc putwchar scanf # LC_NUMERIC @@ -197,8 +196,7 @@ GIT_GREP_OUTPUT=$(git grep -E "[^a-zA-Z0-9_\`'\"<>](${REGEXP_LOCALE_DEPENDENT_FU EXIT_CODE=0 for LOCALE_DEPENDENT_FUNCTION in "${LOCALE_DEPENDENT_FUNCTIONS[@]}"; do MATCHES=$(grep -E "[^a-zA-Z0-9_\`'\"<>]${LOCALE_DEPENDENT_FUNCTION}(_r|_s)?[^a-zA-Z0-9_\`'\"<>]" <<< "${GIT_GREP_OUTPUT}" | \ - grep -vE "\.(c|cpp|h):\s*(//|\*|/\*|\").*${LOCALE_DEPENDENT_FUNCTION}" | \ - grep -vE 'fprintf\(.*(stdout|stderr)') + grep -vE "\.(c|cpp|h):\s*(//|\*|/\*|\").*${LOCALE_DEPENDENT_FUNCTION}") if [[ ${REGEXP_IGNORE_EXTERNAL_DEPENDENCIES} != "" ]]; then MATCHES=$(grep -vE "${REGEXP_IGNORE_EXTERNAL_DEPENDENCIES}" <<< "${MATCHES}") fi