diff --git a/.clang-tidy b/.clang-tidy index 1a87bbe6ed..4f1ac626be 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -75,7 +75,13 @@ Checks: "-*, bugprone-unused-return-value, bugprone-unused-local-non-trivial-variable, bugprone-virtual-near-miss, + cppcoreguidelines-init-variables, + cppcoreguidelines-misleading-capture-default-by-value, cppcoreguidelines-no-suspend-with-lock, + cppcoreguidelines-pro-type-member-init, + cppcoreguidelines-pro-type-static-cast-downcast, + cppcoreguidelines-rvalue-reference-param-not-moved, + cppcoreguidelines-use-default-member-init, cppcoreguidelines-virtual-class-destructor, hicpp-ignored-remove-result, misc-definitions-in-headers, @@ -104,13 +110,6 @@ Checks: "-*, # bugprone-move-forwarding-reference, # bugprone-use-after-move, # -# cppcoreguidelines-misleading-capture-default-by-value, -# cppcoreguidelines-init-variables, -# cppcoreguidelines-pro-type-member-init, -# cppcoreguidelines-pro-type-static-cast-downcast, -# cppcoreguidelines-use-default-member-init, -# cppcoreguidelines-rvalue-reference-param-not-moved, -# # llvm-namespace-comment, # misc-const-correctness, # misc-include-cleaner, diff --git a/include/xrpl/basics/safe_cast.h b/include/xrpl/basics/safe_cast.h index 8f5826f2a8..1e33b9663a 100644 --- a/include/xrpl/basics/safe_cast.h +++ b/include/xrpl/basics/safe_cast.h @@ -1,5 +1,7 @@ #pragma once +#include + #include namespace xrpl { @@ -70,4 +72,31 @@ unsafe_cast(Src s) noexcept return unsafe_cast(static_cast>(s)); } +template + requires std::is_pointer_v +inline Dest +safe_downcast(Src* s) noexcept +{ +#ifdef NDEBUG + return static_cast(s); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast) +#else + auto* result = dynamic_cast(s); + XRPL_ASSERT(result != nullptr, "xrpl::safe_downcast : pointer downcast is valid"); + return result; +#endif +} + +template + requires std::is_lvalue_reference_v +inline Dest +safe_downcast(Src& s) noexcept +{ +#ifndef NDEBUG + XRPL_ASSERT( + dynamic_cast>>(&s) != nullptr, + "xrpl::safe_downcast : reference downcast is valid"); +#endif + return static_cast(s); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast) +} + } // namespace xrpl diff --git a/include/xrpl/beast/core/List.h b/include/xrpl/beast/core/List.h index 75c981ea1b..504dec4c4a 100644 --- a/include/xrpl/beast/core/List.h +++ b/include/xrpl/beast/core/List.h @@ -43,8 +43,8 @@ private: template friend class ListIterator; - ListNode* m_next; - ListNode* m_prev; + ListNode* m_next = nullptr; + ListNode* m_prev = nullptr; }; //------------------------------------------------------------------------------ @@ -567,7 +567,7 @@ private: } private: - size_type m_size; + size_type m_size = 0u; Node m_head; Node m_tail; }; diff --git a/include/xrpl/json/json_value.h b/include/xrpl/json/json_value.h index 5895c94065..fc7625d67a 100644 --- a/include/xrpl/json/json_value.h +++ b/include/xrpl/json/json_value.h @@ -421,7 +421,7 @@ private: ObjectValues* map_{nullptr}; } value_; ValueType type_ : 8; - int allocated_ : 1; // Notes: if declared as bool, bitfield is useless. + int allocated_ : 1 {}; // Notes: if declared as bool, bitfield is useless. }; inline Value diff --git a/include/xrpl/json/json_writer.h b/include/xrpl/json/json_writer.h index e468a5940d..cc3790a7dd 100644 --- a/include/xrpl/json/json_writer.h +++ b/include/xrpl/json/json_writer.h @@ -108,7 +108,7 @@ private: std::string indentString_; int rightMargin_; int indentSize_; - bool addChildValues_; + bool addChildValues_{}; }; /** \brief Writes a Value in JSON format in a @@ -175,7 +175,7 @@ private: std::string indentString_; int rightMargin_; std::string indentation_; - bool addChildValues_; + bool addChildValues_{}; }; std::string diff --git a/include/xrpl/protocol/PublicKey.h b/include/xrpl/protocol/PublicKey.h index e806f6ffeb..67e55ca136 100644 --- a/include/xrpl/protocol/PublicKey.h +++ b/include/xrpl/protocol/PublicKey.h @@ -44,7 +44,7 @@ protected: // All the constructed public keys are valid, non-empty and contain 33 // bytes of data. static constexpr std::size_t size_ = 33; - std::uint8_t buf_[size_]; // should be large enough + std::uint8_t buf_[size_]{}; // should be large enough public: using const_iterator = std::uint8_t const*; diff --git a/include/xrpl/protocol/STAccount.h b/include/xrpl/protocol/STAccount.h index 3fdb2e015e..76c8f24b7b 100644 --- a/include/xrpl/protocol/STAccount.h +++ b/include/xrpl/protocol/STAccount.h @@ -24,7 +24,7 @@ public: STAccount(); STAccount(SField const& n); - STAccount(SField const& n, Buffer&& v); + STAccount(SField const& n, Buffer const& v); STAccount(SerialIter& sit, SField const& name); STAccount(SField const& n, AccountID const& v); diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index 09eff8c3d2..0eb76a80c1 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -57,7 +57,7 @@ class STObject : public STBase, public CountedObject using list_type = std::vector; list_type v_; - SOTemplate const* mType; + SOTemplate const* mType{}; public: using iterator = boost::transform_iterator; diff --git a/include/xrpl/protocol/SecretKey.h b/include/xrpl/protocol/SecretKey.h index 550ccf75bc..dd5566915f 100644 --- a/include/xrpl/protocol/SecretKey.h +++ b/include/xrpl/protocol/SecretKey.h @@ -20,7 +20,7 @@ public: static constexpr std::size_t size_ = 32; private: - std::uint8_t buf_[size_]; + std::uint8_t buf_[size_]{}; public: using const_iterator = std::uint8_t const*; diff --git a/include/xrpl/protocol/Seed.h b/include/xrpl/protocol/Seed.h index 1fad94e2bd..5b490be12e 100644 --- a/include/xrpl/protocol/Seed.h +++ b/include/xrpl/protocol/Seed.h @@ -13,7 +13,7 @@ namespace xrpl { class Seed { private: - std::array buf_; + std::array buf_{}; public: using const_iterator = std::array::const_iterator; diff --git a/include/xrpl/protocol/detail/STVar.h b/include/xrpl/protocol/detail/STVar.h index b5373d1a4a..bab2c2e024 100644 --- a/include/xrpl/protocol/detail/STVar.h +++ b/include/xrpl/protocol/detail/STVar.h @@ -44,7 +44,7 @@ private: // The largest "small object" we can accommodate static std::size_t constexpr max_size = 72; - std::aligned_storage::type d_; + std::aligned_storage::type d_ = {}; STBase* p_ = nullptr; public: diff --git a/include/xrpl/protocol/digest.h b/include/xrpl/protocol/digest.h index b5ec277e7b..9e6606f51f 100644 --- a/include/xrpl/protocol/digest.h +++ b/include/xrpl/protocol/digest.h @@ -40,7 +40,7 @@ public: operator result_type() noexcept; private: - char ctx_[96]; + char ctx_[96]{}; }; /** SHA-512 digest @@ -63,7 +63,7 @@ public: operator result_type() noexcept; private: - char ctx_[216]; + char ctx_[216]{}; }; /** SHA-256 digest @@ -86,7 +86,7 @@ public: operator result_type() noexcept; private: - char ctx_[112]; + char ctx_[112]{}; }; //------------------------------------------------------------------------------ diff --git a/include/xrpl/tx/Transactor.h b/include/xrpl/tx/Transactor.h index b415316358..03cbd60a8e 100644 --- a/include/xrpl/tx/Transactor.h +++ b/include/xrpl/tx/Transactor.h @@ -114,7 +114,7 @@ protected: beast::Journal const j_; AccountID const account_; - XRPAmount preFeeBalance_; // Balance before fees. + XRPAmount preFeeBalance_{}; // Balance before fees. virtual ~Transactor() = default; Transactor(Transactor const&) = delete; diff --git a/include/xrpl/tx/paths/BookTip.h b/include/xrpl/tx/paths/BookTip.h index 69d3ec70d8..98036a86eb 100644 --- a/include/xrpl/tx/paths/BookTip.h +++ b/include/xrpl/tx/paths/BookTip.h @@ -22,7 +22,7 @@ private: uint256 m_dir; uint256 m_index; std::shared_ptr m_entry; - Quality m_quality; + Quality m_quality{}; public: /** Create the iterator. */ diff --git a/include/xrpl/tx/transactors/dex/AMMHelpers.h b/include/xrpl/tx/transactors/dex/AMMHelpers.h index 3520b81113..e2735ea80f 100644 --- a/include/xrpl/tx/transactors/dex/AMMHelpers.h +++ b/include/xrpl/tx/transactors/dex/AMMHelpers.h @@ -639,9 +639,9 @@ getRoundedAsset(Rules const& rules, STAmount const& balance, A const& frac, IsDe STAmount getRoundedAsset( Rules const& rules, - std::function&& noRoundCb, + std::function const& noRoundCb, STAmount const& balance, - std::function&& productCb, + std::function const& productCb, IsDeposit isDeposit); /** Round AMM deposit/withdrawal LPToken amount. Deposit/withdrawal formulas @@ -672,9 +672,9 @@ getRoundedLPTokens( STAmount getRoundedLPTokens( Rules const& rules, - std::function&& noRoundCb, + std::function const& noRoundCb, STAmount const& lptAMMBalance, - std::function&& productCb, + std::function const& productCb, IsDeposit isDeposit); /* Next two functions adjust asset in/out amount to factor in the adjusted diff --git a/include/xrpl/tx/transactors/nft/NFTokenUtils.h b/include/xrpl/tx/transactors/nft/NFTokenUtils.h index a5e2b30354..f33bd6e911 100644 --- a/include/xrpl/tx/transactors/nft/NFTokenUtils.h +++ b/include/xrpl/tx/transactors/nft/NFTokenUtils.h @@ -54,7 +54,7 @@ removeToken( ApplyView& view, AccountID const& owner, uint256 const& nftokenID, - std::shared_ptr&& page); + std::shared_ptr const& page); /** Deletes the given token offer. diff --git a/src/libxrpl/basics/Archive.cpp b/src/libxrpl/basics/Archive.cpp index 06f19b27ee..a09d77d794 100644 --- a/src/libxrpl/basics/Archive.cpp +++ b/src/libxrpl/basics/Archive.cpp @@ -51,8 +51,8 @@ extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& if (archive_write_disk_set_standard_lookup(aw.get()) < ARCHIVE_OK) Throw(archive_error_string(aw.get())); - int result; - struct archive_entry* entry; + int result = 0; + struct archive_entry* entry = nullptr; while (true) { result = archive_read_next_header(ar.get(), &entry); @@ -67,9 +67,9 @@ extractTarLz4(boost::filesystem::path const& src, boost::filesystem::path const& if (archive_entry_size(entry) > 0) { - void const* buf; - size_t sz; - la_int64_t offset; + void const* buf = nullptr; + size_t sz = 0; + la_int64_t offset = 0; while (true) { result = archive_read_data_block(ar.get(), &buf, &sz, &offset); diff --git a/src/libxrpl/basics/Number.cpp b/src/libxrpl/basics/Number.cpp index 8bd048ae9e..11d2368b03 100644 --- a/src/libxrpl/basics/Number.cpp +++ b/src/libxrpl/basics/Number.cpp @@ -66,14 +66,12 @@ concept UnsignedMantissa = std::is_unsigned_v || std::is_same_v class Number::Guard { - std::uint64_t digits_; // 16 decimal guard digits - std::uint8_t xbit_ : 1; // has a non-zero digit been shifted off the end - std::uint8_t sbit_ : 1; // the sign of the guard digits + std::uint64_t digits_{0}; // 16 decimal guard digits + std::uint8_t xbit_ : 1 {0}; // has a non-zero digit been shifted off the end + std::uint8_t sbit_ : 1 {0}; // the sign of the guard digits public: - explicit Guard() : digits_{0}, xbit_{0}, sbit_{0} - { - } + explicit Guard() = default; // set & test the sign bit void diff --git a/src/libxrpl/basics/ResolverAsio.cpp b/src/libxrpl/basics/ResolverAsio.cpp index f5095b31fa..225cbe2926 100644 --- a/src/libxrpl/basics/ResolverAsio.cpp +++ b/src/libxrpl/basics/ResolverAsio.cpp @@ -109,7 +109,7 @@ public: std::condition_variable m_cv; std::mutex m_mut; - bool m_asyncHandlersCompleted; + bool m_asyncHandlersCompleted{true}; std::atomic m_stop_called; std::atomic m_stopped; @@ -136,7 +136,6 @@ public: , m_io_context(io_context) , m_strand(boost::asio::make_strand(io_context)) , m_resolver(io_context) - , m_asyncHandlersCompleted(true) , m_stop_called(false) , m_stopped(true) { diff --git a/src/libxrpl/basics/StringUtilities.cpp b/src/libxrpl/basics/StringUtilities.cpp index 96b5cfdb9b..0dd466c9b4 100644 --- a/src/libxrpl/basics/StringUtilities.cpp +++ b/src/libxrpl/basics/StringUtilities.cpp @@ -103,7 +103,7 @@ trim_whitespace(std::string str) std::optional to_uint64(std::string const& s) { - std::uint64_t result; + std::uint64_t result = 0; if (beast::lexicalCastChecked(result, s)) return result; return std::nullopt; diff --git a/src/libxrpl/beast/clock/basic_seconds_clock.cpp b/src/libxrpl/beast/clock/basic_seconds_clock.cpp index 5248657479..4727599740 100644 --- a/src/libxrpl/beast/clock/basic_seconds_clock.cpp +++ b/src/libxrpl/beast/clock/basic_seconds_clock.cpp @@ -16,7 +16,7 @@ class seconds_clock_thread { using Clock = basic_seconds_clock::Clock; - bool stop_; + bool stop_{false}; std::mutex mut_; std::condition_variable cv_; std::thread thread_; @@ -48,8 +48,7 @@ seconds_clock_thread::~seconds_clock_thread() thread_.join(); } -seconds_clock_thread::seconds_clock_thread() - : stop_{false}, tp_{Clock::now().time_since_epoch().count()} +seconds_clock_thread::seconds_clock_thread() : tp_{Clock::now().time_since_epoch().count()} { thread_ = std::thread(&seconds_clock_thread::run, this); } diff --git a/src/libxrpl/beast/core/SemanticVersion.cpp b/src/libxrpl/beast/core/SemanticVersion.cpp index 06cd622722..e8899e6854 100644 --- a/src/libxrpl/beast/core/SemanticVersion.cpp +++ b/src/libxrpl/beast/core/SemanticVersion.cpp @@ -29,7 +29,7 @@ print_identifiers(SemanticVersion::identifier_list const& list) bool isNumeric(std::string const& s) { - int n; + int n = 0; // Must be convertible to an integer if (!lexicalCastChecked(n, s)) @@ -68,7 +68,7 @@ chopUInt(int& value, int limit, std::string& input) if (item.empty()) return false; - int n; + int n = 0; // Must be convertible to an integer if (!lexicalCastChecked(n, item)) diff --git a/src/libxrpl/beast/insight/StatsDCollector.cpp b/src/libxrpl/beast/insight/StatsDCollector.cpp index bf7dde7bbb..cc3bbf2861 100644 --- a/src/libxrpl/beast/insight/StatsDCollector.cpp +++ b/src/libxrpl/beast/insight/StatsDCollector.cpp @@ -104,8 +104,8 @@ private: std::shared_ptr m_impl; std::string m_name; - CounterImpl::value_type m_value; - bool m_dirty; + CounterImpl::value_type m_value{0}; + bool m_dirty{false}; }; //------------------------------------------------------------------------------ @@ -162,9 +162,9 @@ private: std::shared_ptr m_impl; std::string m_name; - GaugeImpl::value_type m_last_value; - GaugeImpl::value_type m_value; - bool m_dirty; + GaugeImpl::value_type m_last_value{0}; + GaugeImpl::value_type m_value{0}; + bool m_dirty{false}; }; //------------------------------------------------------------------------------ @@ -194,8 +194,8 @@ private: std::shared_ptr m_impl; std::string m_name; - MeterImpl::value_type m_value; - bool m_dirty; + MeterImpl::value_type m_value{0}; + bool m_dirty{false}; }; //------------------------------------------------------------------------------ @@ -505,7 +505,7 @@ StatsDHookImpl::do_process() StatsDCounterImpl::StatsDCounterImpl( std::string const& name, std::shared_ptr const& impl) - : m_impl(impl), m_name(name), m_value(0), m_dirty(false) + : m_impl(impl), m_name(name) { m_impl->add(*this); } @@ -587,7 +587,7 @@ StatsDEventImpl::do_notify(EventImpl::value_type const& value) StatsDGaugeImpl::StatsDGaugeImpl( std::string const& name, std::shared_ptr const& impl) - : m_impl(impl), m_name(name), m_last_value(0), m_value(0), m_dirty(false) + : m_impl(impl), m_name(name) { m_impl->add(*this); } @@ -676,7 +676,7 @@ StatsDGaugeImpl::do_process() StatsDMeterImpl::StatsDMeterImpl( std::string const& name, std::shared_ptr const& impl) - : m_impl(impl), m_name(name), m_value(0), m_dirty(false) + : m_impl(impl), m_name(name) { m_impl->add(*this); } diff --git a/src/libxrpl/beast/net/IPEndpoint.cpp b/src/libxrpl/beast/net/IPEndpoint.cpp index 701181ef88..992da0041b 100644 --- a/src/libxrpl/beast/net/IPEndpoint.cpp +++ b/src/libxrpl/beast/net/IPEndpoint.cpp @@ -159,7 +159,7 @@ operator>>(std::istream& is, Endpoint& endpoint) if (is.rdbuf()->in_avail() > 0) { - Port port; + Port port = 0; is >> port; if (is.fail()) return is; diff --git a/src/libxrpl/beast/utility/beast_PropertyStream.cpp b/src/libxrpl/beast/utility/beast_PropertyStream.cpp index f714ad8871..f1edb4c4ef 100644 --- a/src/libxrpl/beast/utility/beast_PropertyStream.cpp +++ b/src/libxrpl/beast/utility/beast_PropertyStream.cpp @@ -15,7 +15,7 @@ namespace beast { // //------------------------------------------------------------------------------ -PropertyStream::Item::Item(Source* source) : m_source(source) +PropertyStream::Item::Item(Source* source) : ListNode(), m_source(source) { } diff --git a/src/libxrpl/core/detail/JobQueue.cpp b/src/libxrpl/core/detail/JobQueue.cpp index 80fb8d2536..9adbf6312b 100644 --- a/src/libxrpl/core/detail/JobQueue.cpp +++ b/src/libxrpl/core/detail/JobQueue.cpp @@ -331,7 +331,7 @@ JobQueue::finishJob(JobType type) void JobQueue::processTask(int instance) { - JobType type; + JobType type = jtINVALID; { using namespace std::chrono; diff --git a/src/libxrpl/crypto/RFC1751.cpp b/src/libxrpl/crypto/RFC1751.cpp index 54d3e6f9d0..a21bc71c31 100644 --- a/src/libxrpl/crypto/RFC1751.cpp +++ b/src/libxrpl/crypto/RFC1751.cpp @@ -198,10 +198,10 @@ char const* RFC1751::s_dictionary[2048] = { unsigned long RFC1751::extract(char const* s, int start, int length) { - unsigned char cl; - unsigned char cc; - unsigned char cr; - unsigned long x; + unsigned char cl = 0; + unsigned char cc = 0; + unsigned char cr = 0; + unsigned long x = 0; XRPL_ASSERT(length <= 11, "xrpl::RFC1751::extract : maximum length"); XRPL_ASSERT(start >= 0, "xrpl::RFC1751::extract : minimum start"); @@ -226,7 +226,7 @@ void RFC1751::btoe(std::string& strHuman, std::string const& strData) { char caBuffer[9]; /* add in room for the parity 2 bits*/ - int p, i; + int p = 0, i = 0; memcpy(caBuffer, strData.c_str(), 8); @@ -245,11 +245,11 @@ RFC1751::btoe(std::string& strHuman, std::string const& strData) void RFC1751::insert(char* s, int x, int start, int length) { - unsigned char cl; - unsigned char cc; - unsigned char cr; - unsigned long y; - int shift; + unsigned char cl = 0; + unsigned char cc = 0; + unsigned char cr = 0; + unsigned long y = 0; + int shift = 0; XRPL_ASSERT(length <= 11, "xrpl::RFC1751::insert : maximum length"); XRPL_ASSERT(start >= 0, "xrpl::RFC1751::insert : minimum start"); @@ -336,7 +336,7 @@ RFC1751::etob(std::string& strData, std::vector vsHuman) if (6 != vsHuman.size()) return -1; - int i, p = 0; + int i = 0, p = 0; char b[9] = {0}; for (auto& strWord : vsHuman) diff --git a/src/libxrpl/crypto/csprng.cpp b/src/libxrpl/crypto/csprng.cpp index 7858d4089c..25e24c0b08 100644 --- a/src/libxrpl/crypto/csprng.cpp +++ b/src/libxrpl/crypto/csprng.cpp @@ -30,7 +30,7 @@ csprng_engine::~csprng_engine() void csprng_engine::mix_entropy(void* buffer, std::size_t count) { - std::array entropy; + std::array entropy{}; { // On every platform we support, std::random_device @@ -71,7 +71,7 @@ csprng_engine::operator()(void* ptr, std::size_t count) csprng_engine::result_type csprng_engine::operator()() { - result_type ret; + result_type ret = 0; (*this)(&ret, sizeof(result_type)); return ret; } diff --git a/src/libxrpl/json/Writer.cpp b/src/libxrpl/json/Writer.cpp index be9595b088..ee3d6f97a8 100644 --- a/src/libxrpl/json/Writer.cpp +++ b/src/libxrpl/json/Writer.cpp @@ -196,7 +196,7 @@ private: explicit Collection() = default; /** What type of collection are we in? */ - Writer::CollectionType type; + Writer::CollectionType type = Writer::CollectionType::array; /** Is this the first entry in a collection? * If false, we have to emit a , before we write the next entry. */ diff --git a/src/libxrpl/json/json_reader.cpp b/src/libxrpl/json/json_reader.cpp index 3e75757f12..1195816516 100644 --- a/src/libxrpl/json/json_reader.cpp +++ b/src/libxrpl/json/json_reader.cpp @@ -94,7 +94,7 @@ Reader::parse(char const* beginDoc, char const* endDoc, Value& root) nodes_.push(&root); bool successful = readValue(0); - Token token; + Token token{}; skipCommentTokens(token); if (!root.isNull() && !root.isArray() && !root.isObject()) @@ -114,7 +114,7 @@ Reader::parse(char const* beginDoc, char const* endDoc, Value& root) bool Reader::readValue(unsigned depth) { - Token token; + Token token{}; skipCommentTokens(token); if (depth > nest_limit) return addError("Syntax error: maximum nesting depth exceeded", token); @@ -395,7 +395,7 @@ Reader::readString() bool Reader::readObject(Token& tokenStart, unsigned depth) { - Token tokenName; + Token tokenName{}; std::string name; currentValue() = Value(objectValue); @@ -420,7 +420,7 @@ Reader::readObject(Token& tokenStart, unsigned depth) if (!decodeString(tokenName, name)) return recoverFromError(tokenObjectEnd); - Token colon; + Token colon{}; if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { @@ -440,7 +440,7 @@ Reader::readObject(Token& tokenStart, unsigned depth) if (!ok) // error already set return recoverFromError(tokenObjectEnd); - Token comma; + Token comma{}; if (!readToken(comma) || (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && @@ -470,7 +470,7 @@ Reader::readArray(Token& tokenStart, unsigned depth) if (*current_ == ']') // empty array { - Token endArray; + Token endArray{}; readToken(endArray); return true; } @@ -487,7 +487,7 @@ Reader::readArray(Token& tokenStart, unsigned depth) if (!ok) // error already set return recoverFromError(tokenArrayEnd); - Token token; + Token token{}; // Accept Comment after last item in the array. ok = readToken(token); @@ -591,7 +591,7 @@ Reader::decodeDouble(Token& token) { double value = 0; int const bufferSize = 32; - int count; + int count = 0; int length = int(token.end_ - token.start_); // Sanity check to avoid buffer overflow exploits. if (length < 0) @@ -689,7 +689,7 @@ Reader::decodeString(Token& token, std::string& decoded) break; case 'u': { - unsigned int unicode; + unsigned int unicode = 0; if (!decodeUnicodeCodePoint(token, current, end, unicode)) return false; @@ -727,7 +727,7 @@ Reader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, un token, current); - unsigned int surrogatePair; + unsigned int surrogatePair = 0; if (*current != '\\' || *(current + 1) != 'u') return addError( @@ -796,7 +796,7 @@ bool Reader::recoverFromError(TokenType skipUntilToken) { int errorCount = int(errors_.size()); - Token skip; + Token skip{}; while (true) { @@ -867,7 +867,7 @@ Reader::getLocationLineAndColumn(Location location, int& line, int& column) cons std::string Reader::getLocationLineAndColumn(Location location) const { - int line, column; + int line = 0, column = 0; getLocationLineAndColumn(location, line, column); return "Line " + std::to_string(line) + ", Column " + std::to_string(column); } diff --git a/src/libxrpl/json/json_value.cpp b/src/libxrpl/json/json_value.cpp index 60197d75f0..88542f530d 100644 --- a/src/libxrpl/json/json_value.cpp +++ b/src/libxrpl/json/json_value.cpp @@ -157,7 +157,7 @@ Value::CZString::isStaticString() const * memset( this, 0, sizeof(Value) ) * This optimization is used in ValueInternalMap fast allocator. */ -Value::Value(ValueType type) : type_(type), allocated_(0) +Value::Value(ValueType type) : type_(type) { switch (type) { @@ -225,7 +225,7 @@ Value::Value(std::string const& value) : type_(stringValue), allocated_(true) valueAllocator()->duplicateStringValue(value.c_str(), (unsigned int)value.length()); } -Value::Value(StaticString const& value) : type_(stringValue), allocated_(false) +Value::Value(StaticString const& value) : type_(stringValue) { value_.string_ = const_cast(value.c_str()); } diff --git a/src/libxrpl/ledger/ApplyStateTable.cpp b/src/libxrpl/ledger/ApplyStateTable.cpp index e31b39b437..8c1f8d64d2 100644 --- a/src/libxrpl/ledger/ApplyStateTable.cpp +++ b/src/libxrpl/ledger/ApplyStateTable.cpp @@ -107,7 +107,7 @@ ApplyStateTable::apply( Mods newMod; for (auto& item : items_) { - SField const* type; + SField const* type = nullptr; switch (item.second.first) { default: @@ -513,7 +513,7 @@ void ApplyStateTable::threadItem(TxMeta& meta, std::shared_ptr const& sle) { key_type prevTxID; - LedgerIndex prevLgrID; + LedgerIndex prevLgrID = 0; if (!sle->thread(meta.getTxID(), meta.getLgrSeq(), prevTxID, prevLgrID)) return; diff --git a/src/libxrpl/net/HTTPClient.cpp b/src/libxrpl/net/HTTPClient.cpp index cbae927feb..8ddae12a7e 100644 --- a/src/libxrpl/net/HTTPClient.cpp +++ b/src/libxrpl/net/HTTPClient.cpp @@ -478,7 +478,7 @@ public: private: using pointer = std::shared_ptr; - bool mSSL; + bool mSSL{}; AutoSocket mSocket; boost::asio::ip::tcp::resolver mResolver; @@ -496,7 +496,7 @@ private: std::string mBody; unsigned short const mPort; std::size_t const maxResponseSize_; - int mStatus; + int mStatus{}; std::function mBuild; std::function< bool(boost::system::error_code const& ecResult, int iStatus, std::string const& strData)> @@ -508,7 +508,7 @@ private: boost::system::error_code mShutdown; std::deque mDeqSites; - std::chrono::seconds mTimeout; + std::chrono::seconds mTimeout{}; beast::Journal j_; }; diff --git a/src/libxrpl/nodestore/BatchWriter.cpp b/src/libxrpl/nodestore/BatchWriter.cpp index ed7753f68e..98fe78c489 100644 --- a/src/libxrpl/nodestore/BatchWriter.cpp +++ b/src/libxrpl/nodestore/BatchWriter.cpp @@ -75,7 +75,7 @@ BatchWriter::writeBatch() } } - BatchWriteReport report; + BatchWriteReport report{}; report.writeCount = set.size(); auto const before = std::chrono::steady_clock::now(); diff --git a/src/libxrpl/nodestore/DatabaseNodeImp.cpp b/src/libxrpl/nodestore/DatabaseNodeImp.cpp index d1452dba86..a24379aea9 100644 --- a/src/libxrpl/nodestore/DatabaseNodeImp.cpp +++ b/src/libxrpl/nodestore/DatabaseNodeImp.cpp @@ -29,7 +29,7 @@ DatabaseNodeImp::fetchNodeObject( bool duplicate) { std::shared_ptr nodeObject = nullptr; - Status status; + Status status = ok; try { diff --git a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp index e058fa76ac..6cf51fbf31 100644 --- a/src/libxrpl/nodestore/DatabaseRotatingImp.cpp +++ b/src/libxrpl/nodestore/DatabaseRotatingImp.cpp @@ -101,7 +101,7 @@ DatabaseRotatingImp::fetchNodeObject( bool duplicate) { auto fetch = [&](std::shared_ptr const& backend) { - Status status; + Status status = ok; std::shared_ptr nodeObject; try { diff --git a/src/libxrpl/nodestore/backend/NuDBFactory.cpp b/src/libxrpl/nodestore/backend/NuDBFactory.cpp index c79938bcf8..229bf8b67b 100644 --- a/src/libxrpl/nodestore/backend/NuDBFactory.cpp +++ b/src/libxrpl/nodestore/backend/NuDBFactory.cpp @@ -181,7 +181,7 @@ public: Status fetch(uint256 const& hash, std::shared_ptr* pno) override { - Status status; + Status status = ok; pno->reset(); nudb::error_code ec; db_.fetch( @@ -239,7 +239,7 @@ public: void store(std::shared_ptr const& no) override { - BatchWriteReport report; + BatchWriteReport report{}; report.writeCount = 1; auto const start = std::chrono::steady_clock::now(); do_insert(no); @@ -251,7 +251,7 @@ public: void storeBatch(Batch const& batch) override { - BatchWriteReport report; + BatchWriteReport report{}; report.writeCount = batch.size(); auto const start = std::chrono::steady_clock::now(); for (auto const& e : batch) diff --git a/src/libxrpl/protocol/STAccount.cpp b/src/libxrpl/protocol/STAccount.cpp index b85341daf3..9570191273 100644 --- a/src/libxrpl/protocol/STAccount.cpp +++ b/src/libxrpl/protocol/STAccount.cpp @@ -24,7 +24,7 @@ STAccount::STAccount(SField const& n) : STBase(n), value_(beast::zero), default_ { } -STAccount::STAccount(SField const& n, Buffer&& v) : STAccount(n) +STAccount::STAccount(SField const& n, Buffer const& v) : STAccount(n) { if (v.empty()) return; // Zero is a valid size for a defaulted STAccount. diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index 9503da57a2..5990e1d7d4 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -181,7 +181,7 @@ STAmount::STAmount(SerialIter& sit, SField const& name) : STBase(name) } STAmount::STAmount(SField const& name, std::int64_t mantissa) - : STBase(name), mAsset(xrpIssue()), mOffset(0) + : STBase(name), mAsset(xrpIssue()), mValue(0), mOffset(0), mIsNegative(false) { set(mantissa); } diff --git a/src/libxrpl/protocol/STArray.cpp b/src/libxrpl/protocol/STArray.cpp index 8e7827cccc..91acc9ddd3 100644 --- a/src/libxrpl/protocol/STArray.cpp +++ b/src/libxrpl/protocol/STArray.cpp @@ -44,7 +44,7 @@ STArray::STArray(SerialIter& sit, SField const& f, int depth) : STBase(f) { while (!sit.empty()) { - int type, field; + int type = 0, field = 0; sit.getFieldID(type, field); if ((type == STI_ARRAY) && (field == 1)) diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index 5887b5c21f..1d37554251 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -100,7 +100,7 @@ STIssue::add(Serializer& s) const auto const& issue = asset_.get(); s.addBitString(issue.getIssuer()); s.addBitString(noAccount()); - std::uint32_t sequence; + std::uint32_t sequence = 0; memcpy(&sequence, issue.getMptID().data(), sizeof(sequence)); s.add32(sequence); } diff --git a/src/libxrpl/protocol/STLedgerEntry.cpp b/src/libxrpl/protocol/STLedgerEntry.cpp index 8d0d56a737..09993583be 100644 --- a/src/libxrpl/protocol/STLedgerEntry.cpp +++ b/src/libxrpl/protocol/STLedgerEntry.cpp @@ -43,14 +43,14 @@ STLedgerEntry::STLedgerEntry(Keylet const& k) : STObject(sfLedgerEntry), key_(k. } STLedgerEntry::STLedgerEntry(SerialIter& sit, uint256 const& index) - : STObject(sfLedgerEntry), key_(index) + : STObject(sfLedgerEntry), key_(index), type_(ltANY) { set(sit); setSLEType(); } STLedgerEntry::STLedgerEntry(STObject const& object, uint256 const& index) - : STObject(object), key_(index) + : STObject(object), key_(index), type_(ltANY) { setSLEType(); } diff --git a/src/libxrpl/protocol/STNumber.cpp b/src/libxrpl/protocol/STNumber.cpp index cdee274f67..6d382bee9c 100644 --- a/src/libxrpl/protocol/STNumber.cpp +++ b/src/libxrpl/protocol/STNumber.cpp @@ -179,8 +179,8 @@ partsFromString(std::string const& number) bool negative = (match[1].matched && (match[1] == "-")); - std::uint64_t mantissa; - int exponent; + std::uint64_t mantissa = 0; + int exponent = 0; if (!match[4].matched) // integer only { diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index 829f8eaeef..05d4d12503 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -46,7 +46,7 @@ STObject::STObject(STObject&& other) { } -STObject::STObject(SField const& name) : STBase(name), mType(nullptr) +STObject::STObject(SField const& name) : STBase(name) { } @@ -62,8 +62,7 @@ STObject::STObject(SOTemplate const& type, SerialIter& sit, SField const& name) applyTemplate(type); // May throw } -STObject::STObject(SerialIter& sit, SField const& name, int depth) noexcept(false) - : STBase(name), mType(nullptr) +STObject::STObject(SerialIter& sit, SField const& name, int depth) noexcept(false) : STBase(name) { if (depth > 10) Throw("Maximum nesting depth of STObject exceeded"); @@ -216,8 +215,8 @@ STObject::set(SerialIter& sit, int depth) // Consume data in the pipe until we run out or reach the end while (!sit.empty()) { - int type; - int field; + int type = 0; + int field = 0; // Get the metadata for the next field sit.getFieldID(type, field); diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index d72db32282..b246daf48e 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -449,7 +449,7 @@ parseLeaf( { auto const str = value.asString(); - std::uint64_t val; + std::uint64_t val = 0; bool const useBase10 = field.shouldMeta(SField::sMD_BaseTen); diff --git a/src/libxrpl/protocol/STTx.cpp b/src/libxrpl/protocol/STTx.cpp index edc668bbd5..bb4b9b3067 100644 --- a/src/libxrpl/protocol/STTx.cpp +++ b/src/libxrpl/protocol/STTx.cpp @@ -708,9 +708,9 @@ invalidMPTAmountInTx(STObject const& tx) { if (auto const& field = tx.peekAtField(e.sField()); (field.getSType() == STI_AMOUNT && - static_cast(field).holds()) || + safe_downcast(field).holds()) || (field.getSType() == STI_ISSUE && - static_cast(field).holds())) + safe_downcast(field).holds())) { if (e.supportMPT() != soeMPTSupported) return true; diff --git a/src/libxrpl/protocol/SecretKey.cpp b/src/libxrpl/protocol/SecretKey.cpp index 4f0963e72d..aa398e9fe1 100644 --- a/src/libxrpl/protocol/SecretKey.cpp +++ b/src/libxrpl/protocol/SecretKey.cpp @@ -74,7 +74,7 @@ deriveDeterministicRootKey(Seed const& seed) // buf |----------------|----| // | seed | seq| - std::array buf; + std::array buf{}; std::copy(seed.begin(), seed.end(), buf.begin()); // The odds that this loop executes more than once are negligible @@ -119,7 +119,7 @@ class Generator { private: uint256 root_; - std::array generator_; + std::array generator_{}; uint256 calculateTweak(std::uint32_t seq) const @@ -133,7 +133,7 @@ private: // buf |---------------------------------|----|----| // | generator | seq| cnt| - std::array buf; + std::array buf{}; std::copy(generator_.begin(), generator_.end(), buf.begin()); copy_uint32(buf.data() + 33, seq); diff --git a/src/libxrpl/protocol/Seed.cpp b/src/libxrpl/protocol/Seed.cpp index 0e0bb7fb2b..8aa1d8b67d 100644 --- a/src/libxrpl/protocol/Seed.cpp +++ b/src/libxrpl/protocol/Seed.cpp @@ -46,7 +46,7 @@ Seed::Seed(uint128 const& seed) Seed randomSeed() { - std::array buffer; + std::array buffer{}; beast::rngfill(buffer.data(), buffer.size(), crypto_prng()); Seed seed(makeSlice(buffer)); secure_erase(buffer.data(), buffer.size()); diff --git a/src/libxrpl/protocol/Serializer.cpp b/src/libxrpl/protocol/Serializer.cpp index 483e6b516f..4415f96484 100644 --- a/src/libxrpl/protocol/Serializer.cpp +++ b/src/libxrpl/protocol/Serializer.cpp @@ -206,7 +206,7 @@ Serializer::addVL(void const* ptr, int len) int Serializer::addEncoded(int length) { - std::array bytes; + std::array bytes{}; int numBytes = 0; if (length <= 192) @@ -466,7 +466,7 @@ int SerialIter::getVLDataLength() { int b1 = get8(); - int datLen; + int datLen = 0; int lenLen = Serializer::decodeLengthLength(b1); if (lenLen == 1) { diff --git a/src/libxrpl/protocol/tokens.cpp b/src/libxrpl/protocol/tokens.cpp index 867c69a802..868c45e46c 100644 --- a/src/libxrpl/protocol/tokens.cpp +++ b/src/libxrpl/protocol/tokens.cpp @@ -329,7 +329,7 @@ decodeBase58Token(std::string const& s, TokenType type) return {}; // And the checksum must as well. - std::array guard; + std::array guard{}; checksum(guard.data(), ret.data(), ret.size() - guard.size()); if (!std::equal(guard.rbegin(), guard.rend(), ret.rbegin())) return {}; @@ -610,7 +610,7 @@ encodeBase58Token( std::span out) { constexpr std::size_t tmpBufSize = 128; - std::array buf; + std::array buf{}; if (input.size() > tmpBufSize - 5) { return Unexpected(TokenCodecErrc::inputTooLarge); @@ -637,7 +637,7 @@ encodeBase58Token( B58Result> decodeBase58Token(TokenType type, std::string_view s, std::span outBuf) { - std::array tmpBuf; + std::array tmpBuf{}; auto const decodeResult = detail::b58_to_b256_be(s, std::span(tmpBuf.data(), tmpBuf.size())); if (!decodeResult) @@ -654,7 +654,7 @@ decodeBase58Token(TokenType type, std::string_view s, std::span ou return Unexpected(TokenCodecErrc::mismatchedTokenType); // And the checksum must as well. - std::array guard; + std::array guard{}; checksum(guard.data(), ret.data(), ret.size() - guard.size()); if (!std::equal(guard.rbegin(), guard.rend(), ret.rbegin())) { diff --git a/src/libxrpl/server/JSONRPCUtil.cpp b/src/libxrpl/server/JSONRPCUtil.cpp index 6cf09327f2..db2ea450a2 100644 --- a/src/libxrpl/server/JSONRPCUtil.cpp +++ b/src/libxrpl/server/JSONRPCUtil.cpp @@ -17,7 +17,7 @@ getHTTPHeaderTimestamp() // sense. There's no point in doing all this work if this function // gets called multiple times a second. char buffer[96]; - time_t now; + time_t now = 0; time(&now); struct tm now_gmt{}; #ifndef _MSC_VER diff --git a/src/libxrpl/server/Port.cpp b/src/libxrpl/server/Port.cpp index 9e73d9f007..0cef9bed90 100644 --- a/src/libxrpl/server/Port.cpp +++ b/src/libxrpl/server/Port.cpp @@ -98,7 +98,7 @@ populate( while (std::getline(ss, ip, ',')) { boost::algorithm::trim(ip); - bool v4; + bool v4 = false; boost::asio::ip::network_v4 v4Net; boost::asio::ip::network_v6 v6Net; diff --git a/src/libxrpl/server/State.cpp b/src/libxrpl/server/State.cpp index f41a0c61b3..371f2b4d0a 100644 --- a/src/libxrpl/server/State.cpp +++ b/src/libxrpl/server/State.cpp @@ -54,7 +54,7 @@ initStateDB(soci::session& session, BasicConfig const& config, std::string const LedgerIndex getCanDelete(soci::session& session) { - LedgerIndex seq; + LedgerIndex seq = 0; session << "SELECT CanDeleteSeq FROM CanDelete WHERE Key = 1;", soci::into(seq); ; return seq; diff --git a/src/libxrpl/server/Vacuum.cpp b/src/libxrpl/server/Vacuum.cpp index cb31c6fa7a..89764b777a 100644 --- a/src/libxrpl/server/Vacuum.cpp +++ b/src/libxrpl/server/Vacuum.cpp @@ -25,7 +25,7 @@ doVacuumDB(DatabaseCon::Setup const& setup, beast::Journal j) auto txnDB = std::make_unique(setup, TxDBName, setup.txPragma, TxDBInit, j); auto& session = txnDB->getSession(); - std::uint32_t pageSize; + std::uint32_t pageSize = 0; // Only the most trivial databases will fit in memory on typical // (recommended) hardware. Force temp files to be written to disk diff --git a/src/libxrpl/shamap/SHAMap.cpp b/src/libxrpl/shamap/SHAMap.cpp index 15457b2d2e..9d0bfcb625 100644 --- a/src/libxrpl/shamap/SHAMap.cpp +++ b/src/libxrpl/shamap/SHAMap.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -122,7 +123,7 @@ SHAMap::walkTowardsKey(uint256 const& id, SharedPtrNodeStack* stack) const if (stack != nullptr) stack->push({inNode, nodeID}); - return static_cast(inNode.get()); + return safe_downcast(inNode.get()); } SHAMapLeafNode* @@ -471,7 +472,7 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const while (!node->isLeaf()) { SHAMapTreeNode* nextNode = nullptr; - auto inner = static_cast(node); + auto inner = safe_downcast(node); for (int i = 0; i < branchFactor; ++i) { if (!inner->isEmptyBranch(i)) @@ -496,7 +497,7 @@ SHAMap::onlyBelow(SHAMapTreeNode* node) const // An inner node must have at least one leaf // below it, unless it's the root_ - auto const leaf = static_cast(node); + auto const leaf = safe_downcast(node); XRPL_ASSERT( leaf->peekItem() || (leaf == root_.get()), "xrpl::SHAMap::onlyBelow : valid inner node"); return leaf->peekItem(); @@ -578,7 +579,7 @@ SHAMap::upper_bound(uint256 const& id) const auto [node, nodeID] = stack.top(); if (node->isLeaf()) { - auto leaf = static_cast(node.get()); + auto leaf = safe_downcast(node.get()); if (leaf->peekItem()->key() > id) return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } @@ -611,7 +612,7 @@ SHAMap::lower_bound(uint256 const& id) const auto [node, nodeID] = stack.top(); if (node->isLeaf()) { - auto leaf = static_cast(node.get()); + auto leaf = safe_downcast(node.get()); if (leaf->peekItem()->key() < id) return const_iterator(this, leaf->peekItem().get(), std::move(stack)); } @@ -764,7 +765,7 @@ SHAMap::addGiveItem(SHAMapNodeType type, boost::intrusive_ptr node = intr_ptr::make_shared(node->cowid()); - unsigned int b1, b2; + unsigned int b1 = 0, b2 = 0; while ((b1 = selectBranch(nodeID, tag)) == (b2 = selectBranch(nodeID, otherItem->key()))) { @@ -779,7 +780,7 @@ SHAMap::addGiveItem(SHAMapNodeType type, boost::intrusive_ptr // we can add the two leaf nodes here XRPL_ASSERT(node->isInner(), "xrpl::SHAMap::addGiveItem : node is inner"); - auto inner = static_cast(node.get()); + auto inner = safe_downcast(node.get()); inner->setChild(b1, makeTypedLeaf(type, std::move(item), cowid_)); inner->setChild(b2, makeTypedLeaf(type, std::move(otherItem), cowid_)); } @@ -1088,7 +1089,7 @@ SHAMap::dump(bool hash) const if (node->isInner()) { - auto inner = static_cast(node); + auto inner = safe_downcast(node); for (int i = 0; i < branchFactor; ++i) { if (!inner->isEmptyBranch(i)) diff --git a/src/libxrpl/shamap/SHAMapDelta.cpp b/src/libxrpl/shamap/SHAMapDelta.cpp index 9a6342343f..7ef78d51c3 100644 --- a/src/libxrpl/shamap/SHAMapDelta.cpp +++ b/src/libxrpl/shamap/SHAMapDelta.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include @@ -39,7 +40,7 @@ SHAMap::walkBranch( if (node->isInner()) { // This is an inner node, add all non-empty branches - auto inner = static_cast(node); + auto inner = safe_downcast(node); for (int i = 0; i < 16; ++i) if (!inner->isEmptyBranch(i)) nodeStack.push({descendThrow(inner, i)}); @@ -47,7 +48,7 @@ SHAMap::walkBranch( else { // This is a leaf node, process its item - auto item = static_cast(node)->peekItem(); + auto item = safe_downcast(node)->peekItem(); if (emptyBranch || (item->key() != otherMapItem->key())) { @@ -132,8 +133,8 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const if (ourNode->isLeaf() && otherNode->isLeaf()) { // two leaves - auto ours = static_cast(ourNode); - auto other = static_cast(otherNode); + auto ours = safe_downcast(ourNode); + auto other = safe_downcast(otherNode); if (ours->peekItem()->key() == other->peekItem()->key()) { if (ours->peekItem()->slice() != other->peekItem()->slice()) @@ -161,22 +162,22 @@ SHAMap::compare(SHAMap const& otherMap, Delta& differences, int maxCount) const } else if (ourNode->isInner() && otherNode->isLeaf()) { - auto ours = static_cast(ourNode); - auto other = static_cast(otherNode); + auto ours = safe_downcast(ourNode); + auto other = safe_downcast(otherNode); if (!walkBranch(ours, other->peekItem(), true, differences, maxCount)) return false; } else if (ourNode->isLeaf() && otherNode->isInner()) { - auto ours = static_cast(ourNode); - auto other = static_cast(otherNode); + auto ours = safe_downcast(ourNode); + auto other = safe_downcast(otherNode); if (!otherMap.walkBranch(other, ours->peekItem(), false, differences, maxCount)) return false; } else if (ourNode->isInner() && otherNode->isInner()) { - auto ours = static_cast(ourNode); - auto other = static_cast(otherNode); + auto ours = safe_downcast(ourNode); + auto other = safe_downcast(otherNode); for (int i = 0; i < 16; ++i) if (ours->getChildHash(i) != other->getChildHash(i)) { diff --git a/src/libxrpl/shamap/SHAMapInnerNode.cpp b/src/libxrpl/shamap/SHAMapInnerNode.cpp index 7c344d9264..695e35c75d 100644 --- a/src/libxrpl/shamap/SHAMapInnerNode.cpp +++ b/src/libxrpl/shamap/SHAMapInnerNode.cpp @@ -20,7 +20,7 @@ SHAMapInnerNode::~SHAMapInnerNode() = default; void SHAMapInnerNode::partialDestructor() { - intr_ptr::SharedPtr* children; + intr_ptr::SharedPtr* children = nullptr; // structured bindings can't be captured in c++ 17; use tie instead std::tie(std::ignore, std::ignore, children) = hashesAndChildren_.getHashesAndChildren(); iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { children[indexNum].reset(); }); @@ -61,8 +61,8 @@ SHAMapInnerNode::clone(std::uint32_t cowid) const p->hash_ = hash_; p->isBranch_ = isBranch_; p->fullBelowGen_ = fullBelowGen_; - SHAMapHash *cloneHashes, *thisHashes; - intr_ptr::SharedPtr*cloneChildren, *thisChildren; + SHAMapHash *cloneHashes = nullptr, *thisHashes = nullptr; + intr_ptr::SharedPtr*cloneChildren = nullptr, *thisChildren = nullptr; // structured bindings can't be captured in c++ 17; use tie instead std::tie(std::ignore, cloneHashes, cloneChildren) = p->hashesAndChildren_.getHashesAndChildren(); @@ -185,8 +185,8 @@ SHAMapInnerNode::updateHash() void SHAMapInnerNode::updateHashDeep() { - SHAMapHash* hashes; - intr_ptr::SharedPtr* children; + SHAMapHash* hashes = nullptr; + intr_ptr::SharedPtr* children = nullptr; // structured bindings can't be captured in c++ 17; use tie instead std::tie(std::ignore, hashes, children) = hashesAndChildren_.getHashesAndChildren(); iterNonEmptyChildIndexes([&](auto branchNum, auto indexNum) { diff --git a/src/libxrpl/shamap/SHAMapSync.cpp b/src/libxrpl/shamap/SHAMapSync.cpp index d80ddb1e43..948d972c18 100644 --- a/src/libxrpl/shamap/SHAMapSync.cpp +++ b/src/libxrpl/shamap/SHAMapSync.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -12,7 +13,7 @@ SHAMap::visitLeaves( { visitNodes([&leafFunction](SHAMapTreeNode& node) { if (!node.isInner()) - leafFunction(static_cast(node).peekItem()); + leafFunction(safe_downcast(node).peekItem()); return true; }); } @@ -104,7 +105,7 @@ SHAMap::visitDifferences( using StackEntry = std::pair; std::stack> stack; - stack.push({static_cast(root_.get()), SHAMapNodeID{}}); + stack.push({safe_downcast(root_.get()), SHAMapNodeID{}}); while (!stack.empty()) { @@ -127,12 +128,12 @@ SHAMap::visitDifferences( if (next->isInner()) { if (!have || !have->hasInnerNode(childID, childHash)) - stack.push({static_cast(next), childID}); + stack.push({safe_downcast(next), childID}); } else if ( !have || !have->hasLeafNode( - static_cast(next)->peekItem()->key(), childHash)) + safe_downcast(next)->peekItem()->key(), childHash)) { if (!function(*next)) return; @@ -201,12 +202,13 @@ SHAMap::gmn_ProcessNodes(MissingNodes& mn, MissingNodes::StackEntry& se) if (--mn.max_ <= 0) return; } - else if (d->isInner() && !static_cast(d)->isFullBelow(mn.generation_)) + else if ( + d->isInner() && !safe_downcast(d)->isFullBelow(mn.generation_)) { mn.stack_.push(se); // Switch to processing the child node - node = static_cast(d); + node = safe_downcast(d); nodeID = nodeID.getChildNodeID(branch); firstChild = rand_int(255); currentChild = 0; @@ -305,7 +307,7 @@ SHAMap::getMissingNodes(int max, SHAMapSyncFilter* filter) // that the two threads will produce different request sets (which is // more efficient than sending identical requests). MissingNodes::StackEntry pos{ - static_cast(root_.get()), SHAMapNodeID(), rand_int(255), 0, true}; + safe_downcast(root_.get()), SHAMapNodeID(), rand_int(255), 0, true}; auto& node = std::get<0>(pos); auto& nextChild = std::get<3>(pos); auto& fullBelow = std::get<4>(pos); @@ -399,7 +401,7 @@ SHAMap::getNodeFat( while (node && node->isInner() && (nodeID.getDepth() < wanted.getDepth())) { int branch = selectBranch(nodeID, wanted.getNodeID()); - auto inner = static_cast(node); + auto inner = safe_downcast(node); if (inner->isEmptyBranch(branch)) return false; node = descendThrow(inner, branch); @@ -413,7 +415,7 @@ SHAMap::getNodeFat( return false; } - if (node->isInner() && static_cast(node)->isEmpty()) + if (node->isInner() && safe_downcast(node)->isEmpty()) { JLOG(journal_.warn()) << "peer requests empty node"; return false; @@ -438,7 +440,7 @@ SHAMap::getNodeFat( { // We descend inner nodes with only a single child // without decrementing the depth - auto inner = static_cast(node); + auto inner = safe_downcast(node); int bc = inner->getBranchCount(); if ((depth > 0) || (bc == 1)) @@ -530,12 +532,12 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF auto currNode = root_.get(); while (currNode->isInner() && - !static_cast(currNode)->isFullBelow(generation) && + !safe_downcast(currNode)->isFullBelow(generation) && (currNodeID.getDepth() < node.getDepth())) { int const branch = selectBranch(currNodeID, node.getNodeID()); XRPL_ASSERT(branch >= 0, "xrpl::SHAMap::addKnownNode : valid branch"); - auto inner = static_cast(currNode); + auto inner = safe_downcast(currNode); if (inner->isEmptyBranch(branch)) { JLOG(journal_.warn()) << "Add known node for empty branch" << node; @@ -570,7 +572,7 @@ SHAMap::addKnownNode(SHAMapNodeID const& node, Slice const& rawNode, SHAMapSyncF if (newNode->isLeaf()) { auto const& actualKey = - static_cast(newNode.get())->peekItem()->key(); + safe_downcast(newNode.get())->peekItem()->key(); // Validate that this leaf belongs at the target position auto const expectedNodeID = SHAMapNodeID::createID(node.getDepth(), actualKey); @@ -652,8 +654,8 @@ SHAMap::deepCompare(SHAMap& other) const { if (!otherNode->isLeaf()) return false; - auto& nodePeek = static_cast(node)->peekItem(); - auto& otherNodePeek = static_cast(otherNode)->peekItem(); + auto& nodePeek = safe_downcast(node)->peekItem(); + auto& otherNodePeek = safe_downcast(otherNode)->peekItem(); if (nodePeek->key() != otherNodePeek->key()) return false; if (nodePeek->slice() != otherNodePeek->slice()) @@ -663,8 +665,8 @@ SHAMap::deepCompare(SHAMap& other) const { if (!otherNode->isInner()) return false; - auto node_inner = static_cast(node); - auto other_inner = static_cast(otherNode); + auto node_inner = safe_downcast(node); + auto other_inner = safe_downcast(otherNode); for (int i = 0; i < 16; ++i) { if (node_inner->isEmptyBranch(i)) @@ -704,7 +706,7 @@ SHAMap::hasInnerNode(SHAMapNodeID const& targetNodeID, SHAMapHash const& targetN while (node->isInner() && (nodeID.getDepth() < targetNodeID.getDepth())) { int branch = selectBranch(nodeID, targetNodeID.getNodeID()); - auto inner = static_cast(node); + auto inner = safe_downcast(node); if (inner->isEmptyBranch(branch)) return false; @@ -729,7 +731,7 @@ SHAMap::hasLeafNode(uint256 const& tag, SHAMapHash const& targetNodeHash) const do { int branch = selectBranch(nodeID, tag); - auto inner = static_cast(node); + auto inner = safe_downcast(node); if (inner->isEmptyBranch(branch)) return false; // Dead end, node must not be here @@ -800,7 +802,7 @@ SHAMap::verifyProofPath(uint256 const& rootHash, uint256 const& key, std::vector if (node->isInner()) { auto nodeId = SHAMapNodeID::createID(depth, key); - hash = static_cast(node.get()) + hash = safe_downcast(node.get()) ->getChildHash(selectBranch(nodeId, key)); } else diff --git a/src/libxrpl/tx/apply.cpp b/src/libxrpl/tx/apply.cpp index def82aca18..caf42e9326 100644 --- a/src/libxrpl/tx/apply.cpp +++ b/src/libxrpl/tx/apply.cpp @@ -149,7 +149,7 @@ applyBatchTransactions( auto const parentBatchId = batchTxn.getTransactionID(); auto const mode = batchTxn.getFlags(); - auto applyOneTransaction = [®istry, &j, &parentBatchId, &batchView](STTx&& tx) { + auto applyOneTransaction = [®istry, &j, &parentBatchId, &batchView](STTx const& tx) { OpenView perTxBatchView(batch_view, batchView); auto const ret = apply(registry, perTxBatchView, parentBatchId, tx, tapBATCH, j); diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index ba40d6da36..3597cc8959 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -981,7 +981,7 @@ applyCreateAccountAttestations( struct ScopeResult { OnNewAttestationResult newAttResult; - bool createCID; + bool createCID{}; XChainCreateAccountAttestations curAtts; }; @@ -1209,9 +1209,9 @@ attestationDoApply(ApplyContext& ctx) struct ScopeResult { - STXChainBridge::ChainType srcChain; + STXChainBridge::ChainType srcChain = STXChainBridge::ChainType::locking; std::unordered_map signersList; - std::uint32_t quorum; + std::uint32_t quorum{}; AccountID thisDoor; Keylet bridgeK; }; diff --git a/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp b/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp index c232f82543..75aa51c9d4 100644 --- a/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMHelpers.cpp @@ -257,9 +257,9 @@ multiply(STAmount const& amount, Number const& frac, Number::rounding_mode rm) STAmount getRoundedAsset( Rules const& rules, - std::function&& noRoundCb, + std::function const& noRoundCb, STAmount const& balance, - std::function&& productCb, + std::function const& productCb, IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) @@ -290,9 +290,9 @@ getRoundedLPTokens( STAmount getRoundedLPTokens( Rules const& rules, - std::function&& noRoundCb, + std::function const& noRoundCb, STAmount const& lptAMMBalance, - std::function&& productCb, + std::function const& productCb, IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) diff --git a/src/libxrpl/tx/transactors/dex/AMMUtils.cpp b/src/libxrpl/tx/transactors/dex/AMMUtils.cpp index ce44c9ffd6..a4edaddb6f 100644 --- a/src/libxrpl/tx/transactors/dex/AMMUtils.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMUtils.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -153,7 +154,7 @@ getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) "xrpl::getTradingFee : auction present"); if (ammSle.isFieldPresent(sfAuctionSlot)) { - auto const& auctionSlot = static_cast(ammSle.peekAtField(sfAuctionSlot)); + auto const& auctionSlot = safe_downcast(ammSle.peekAtField(sfAuctionSlot)); // Not expired if (auto const expiration = auctionSlot[~sfExpiration]; duration_cast(view.header().parentCloseTime.time_since_epoch()).count() < diff --git a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp index 650fdabf29..f66a3698d0 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenUtils.cpp @@ -343,7 +343,7 @@ removeToken( ApplyView& view, AccountID const& owner, uint256 const& nftokenID, - std::shared_ptr&& curr) + std::shared_ptr const& curr) { // We found a page, but the given NFT may not be in it. auto arr = curr->getFieldArray(sfNFTokens); diff --git a/src/libxrpl/tx/transactors/token/SetTrust.cpp b/src/libxrpl/tx/transactors/token/SetTrust.cpp index f636827745..d2984825b6 100644 --- a/src/libxrpl/tx/transactors/token/SetTrust.cpp +++ b/src/libxrpl/tx/transactors/token/SetTrust.cpp @@ -376,10 +376,10 @@ SetTrust::doApply() STAmount saLowLimit; STAmount saHighBalance; STAmount saHighLimit; - std::uint32_t uLowQualityIn; - std::uint32_t uLowQualityOut; - std::uint32_t uHighQualityIn; - std::uint32_t uHighQualityOut; + std::uint32_t uLowQualityIn = 0; + std::uint32_t uLowQualityOut = 0; + std::uint32_t uHighQualityIn = 0; + std::uint32_t uHighQualityOut = 0; auto const& uLowAccountID = !bHigh ? account_ : uDstAccountID; auto const& uHighAccountID = bHigh ? account_ : uDstAccountID; SLE::ref sleLowAccount = !bHigh ? sle : sleDst; diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 1cf684ac28..d09c482801 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -5154,7 +5154,7 @@ private: // verify that the quality is better in the first case, and CLOB // is selected in the second case. { - std::array q; + std::array q{}; for (auto i = 0; i < 3; ++i) { Env env(*this, features); @@ -5227,7 +5227,7 @@ private: // Same as the payment but reduced offer quality { - std::array q; + std::array q{}; for (auto i = 0; i < 3; ++i) { Env env(*this, features); @@ -5426,7 +5426,7 @@ private: // multiple AMM offers are generated, which results in slightly // worse overall quality. { - std::array q; + std::array q{}; for (auto i = 0; i < 3; ++i) { Env env(*this, features); diff --git a/src/test/app/DNS_test.cpp b/src/test/app/DNS_test.cpp index f478bc89ee..0c2946f8ed 100644 --- a/src/test/app/DNS_test.cpp +++ b/src/test/app/DNS_test.cpp @@ -33,7 +33,7 @@ public: { auto onFetch = [&](error_code const& errorCode, endpoint_type const& endpoint, - xrpl::detail::response_type&& resp) { + xrpl::detail::response_type const& resp) { BEAST_EXPECT(!errorCode); lastEndpoint_ = endpoint; resolved_[endpoint.address().to_string()]++; diff --git a/src/test/app/HashRouter_test.cpp b/src/test/app/HashRouter_test.cpp index 753922a67d..43ef4a4e06 100644 --- a/src/test/app/HashRouter_test.cpp +++ b/src/test/app/HashRouter_test.cpp @@ -243,7 +243,7 @@ class HashRouter_test : public beast::unit_test::suite HashRouter router(getSetup(5s, 1s), stopwatch); uint256 const key(1); HashRouter::PeerShortID peer = 1; - HashRouterFlags flags; + HashRouterFlags flags = HashRouterFlags::UNDEFINED; BEAST_EXPECT(router.shouldProcess(key, peer, flags, 1s)); BEAST_EXPECT(!router.shouldProcess(key, peer, flags, 1s)); diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 6a010a7e82..8b78caec11 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -110,6 +110,7 @@ class Invariants_test : public beast::unit_test::suite void doInvariantCheck( + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) test::jtx::Env&& env, test::jtx::Account const& A1, test::jtx::Account const& A2, diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index f01cf5709e..f1cd76d88b 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -7087,7 +7087,7 @@ public: return defaultNum; try { - std::size_t pos; + std::size_t pos = 0; auto const r = stoi(s, &pos); if (pos != s.size()) return defaultNum; diff --git a/src/test/app/MultiSign_test.cpp b/src/test/app/MultiSign_test.cpp index adfcb12ee0..f96bfba2d2 100644 --- a/src/test/app/MultiSign_test.cpp +++ b/src/test/app/MultiSign_test.cpp @@ -486,7 +486,7 @@ public: env.close(); auto const baseFee = env.current()->fees().base; - std::uint32_t aliceSeq; + std::uint32_t aliceSeq = 0; // these represent oft-repeated setup for input json below auto setup_tx = [&]() -> Json::Value { diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index 7ff2e7d1cb..95dfc60c41 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -2930,7 +2930,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite uint256 const nftokenID1 = token::getNextID(env, issuer, 0, tfTransferable); env(token::mint(minter, 0), token::issuer(issuer), txflags(tfTransferable)); env.close(); - uint8_t issuerCount, minterCount, buyerCount; + uint8_t issuerCount = 0, minterCount = 0, buyerCount = 0; // Test how adding an Expiration field to an offer affects permissions // for cancelling offers. diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index 5c5eca52cd..ad3b0a8d2d 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -493,7 +493,7 @@ public: return std::nullopt; try { - std::size_t pos; + std::size_t pos = 0; auto const r = stoi(s, &pos); if (pos != s.size()) return std::nullopt; diff --git a/src/test/app/ValidatorSite_test.cpp b/src/test/app/ValidatorSite_test.cpp index 5fc290eda5..eaae4c278e 100644 --- a/src/test/app/ValidatorSite_test.cpp +++ b/src/test/app/ValidatorSite_test.cpp @@ -155,7 +155,7 @@ private: std::vector list; std::string uri; FetchListConfig const& cfg; - bool isRetry; + bool isRetry{}; }; std::vector servers; diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index a9517b7d70..5a5292b06c 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -3348,7 +3348,7 @@ class Vault_test : public beast::unit_test::suite MPTIssue shares(issuanceId); env.memoize(vaultAccount); - auto const peek = [=, &env, this](std::function fn) -> bool { + auto const peek = [keylet, &env, this](std::function fn) -> bool { return env.app().openLedger().modify([&](OpenView& view, beast::Journal j) -> bool { Sandbox sb(&view, tapNONE); auto vault = sb.peek(keylet::vault(keylet.key)); diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index 55ead66b8f..f941e059f8 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -84,7 +84,7 @@ struct SEnv template SEnv& - multiTx(jtx::JValueVec&& jvv, FN const&... fN) + multiTx(jtx::JValueVec const& jvv, FN const&... fN) { for (auto const& jv : jvv) env_(jv, fN...); @@ -3826,7 +3826,7 @@ private: void sendAttestations() { - bool callback_called; + bool callback_called = false; // we have this "do {} while" loop because we want to process // all the account create which can reach quorum at this time @@ -4044,7 +4044,7 @@ private: std::shared_ptr const& chainstate, BridgeDef const& bridge, AccountCreate create) - : Base(chainstate, bridge), sm_state(st_initial), cr(std::move(create)) + : Base(chainstate, bridge), cr(std::move(create)) { } @@ -4076,7 +4076,7 @@ private: ChainStateTrack& st = destState(); // check all signers, but start at a random one - size_t i; + size_t i = 0; for (i = 0; i < num_signers; ++i) { size_t signer_idx = (rnd + i) % num_signers; @@ -4157,7 +4157,7 @@ private: } private: - SmState sm_state; + SmState sm_state{st_initial}; AccountCreate cr; }; @@ -4171,7 +4171,7 @@ private: std::shared_ptr const& chainstate, BridgeDef const& bridge, Transfer xfer) - : Base(chainstate, bridge), xfer(std::move(xfer)), sm_state(st_initial) + : Base(chainstate, bridge), xfer(std::move(xfer)) { } @@ -4318,7 +4318,7 @@ private: private: Transfer xfer; - SmState sm_state; + SmState sm_state{st_initial}; }; // -------------------------------------------------- diff --git a/src/test/basics/PerfLog_test.cpp b/src/test/basics/PerfLog_test.cpp index a2976301ef..6e73b5f696 100644 --- a/src/test/basics/PerfLog_test.cpp +++ b/src/test/basics/PerfLog_test.cpp @@ -793,7 +793,7 @@ public: perfLog->start(); // Randomly select a job type and its name. - JobType jobType; + JobType jobType = jtINVALID; std::string jobTypeName; { auto const& jobTypes = JobTypes::instance(); diff --git a/src/test/basics/XRPAmount_test.cpp b/src/test/basics/XRPAmount_test.cpp index fc095c2023..8b8d657123 100644 --- a/src/test/basics/XRPAmount_test.cpp +++ b/src/test/basics/XRPAmount_test.cpp @@ -121,7 +121,7 @@ public: // since some of them are templated, but not used anywhere else. auto make = [&](auto x) -> XRPAmount { return XRPAmount{x}; }; - XRPAmount defaulted; + XRPAmount defaulted{}; (void)defaulted; XRPAmount test{0}; BEAST_EXPECT(test.drops() == 0); diff --git a/src/test/basics/base58_test.cpp b/src/test/basics/base58_test.cpp index 46e0c7615e..ca62ac02ef 100644 --- a/src/test/basics/base58_test.cpp +++ b/src/test/basics/base58_test.cpp @@ -270,7 +270,7 @@ class base58_test : public beast::unit_test::suite } else { - std::array tmpBuf; + std::array tmpBuf{}; std::string const s = xrpl::b58_ref::detail::encodeBase58( b256Data.data(), b256Data.size(), tmpBuf.data(), tmpBuf.size()); BEAST_EXPECT(s.size()); @@ -394,7 +394,7 @@ class base58_test : public beast::unit_test::suite // bytes range from 0-255 for (int i = 0; i < numTokenTypeIndexes; ++i) { - std::array b256DataBuf; + std::array b256DataBuf{}; auto const [tokType, tokSize] = tokenTypeAndSize(i); for (int d = 0; d <= 255; ++d) { @@ -407,7 +407,7 @@ class base58_test : public beast::unit_test::suite constexpr std::size_t iters = 100000; for (int i = 0; i < iters; ++i) { - std::array b256DataBuf; + std::array b256DataBuf{}; auto const [tokType, b256Data] = randomB256TestData(b256DataBuf); testIt(tokType, b256Data); } diff --git a/src/test/basics/base_uint_test.cpp b/src/test/basics/base_uint_test.cpp index 0aa89bcecc..c8f931e2b5 100644 --- a/src/test/basics/base_uint_test.cpp +++ b/src/test/basics/base_uint_test.cpp @@ -142,7 +142,7 @@ struct base_uint_test : beast::unit_test::suite // Test hash_append by "hashing" with a no-op hasher (h) // and then extracting the bytes that were written during hashing // back into another base_uint (w) for comparison with the original - nonhash<96> h; + nonhash<96> h{}; hash_append(h, u); test96 w{std::vector(h.data_.begin(), h.data_.end())}; BEAST_EXPECT(w == u); diff --git a/src/test/beast/LexicalCast_test.cpp b/src/test/beast/LexicalCast_test.cpp index 4d55b95278..0c84e075c6 100644 --- a/src/test/beast/LexicalCast_test.cpp +++ b/src/test/beast/LexicalCast_test.cpp @@ -198,7 +198,7 @@ public: testcase("zero conversion"); { - std::int32_t out; + std::int32_t out = 0; expect(lexicalCastChecked(out, "-0"), "0"); expect(lexicalCastChecked(out, "0"), "0"); @@ -206,7 +206,7 @@ public: } { - std::uint32_t out; + std::uint32_t out = 0; expect(!lexicalCastChecked(out, "-0"), "0"); expect(lexicalCastChecked(out, "0"), "0"); diff --git a/src/test/beast/beast_Journal_test.cpp b/src/test/beast/beast_Journal_test.cpp index 407e9ea7aa..cb190e57a0 100644 --- a/src/test/beast/beast_Journal_test.cpp +++ b/src/test/beast/beast_Journal_test.cpp @@ -9,10 +9,10 @@ public: class TestSink : public Journal::Sink { private: - int m_count; + int m_count{0}; public: - TestSink() : Sink(severities::kWarning, false), m_count(0) + TestSink() : Sink(severities::kWarning, false) { } diff --git a/src/test/consensus/NegativeUNL_test.cpp b/src/test/consensus/NegativeUNL_test.cpp index 3885edf6f0..7275566ef7 100644 --- a/src/test/consensus/NegativeUNL_test.cpp +++ b/src/test/consensus/NegativeUNL_test.cpp @@ -1304,7 +1304,7 @@ class NegativeUNLVoteScoreTable_test : public beast::unit_test::suite NodeID myId = history.UNLNodeIDs[3]; history.walkHistoryAndAddValidations( [&](std::shared_ptr const& l, std::size_t idx) -> bool { - std::size_t k; + std::size_t k = 0; if (idx < 2) k = 0; else if (idx < 4) diff --git a/src/test/core/ClosureCounter_test.cpp b/src/test/core/ClosureCounter_test.cpp index 71a5c88d5d..f91cdbddf7 100644 --- a/src/test/core/ClosureCounter_test.cpp +++ b/src/test/core/ClosureCounter_test.cpp @@ -207,7 +207,8 @@ class ClosureCounter_test : public beast::unit_test::suite // leaving scope. So, without intervention, they would // do a copy for the return (June 2017). An explicit // std::move() was required. - return std::move(in += "!"); + in += "!"; + return std::move(in); }); BEAST_EXPECT(strCounter.count() == 1); diff --git a/src/test/core/JobQueue_test.cpp b/src/test/core/JobQueue_test.cpp index 8289e305a0..bf6a5590e6 100644 --- a/src/test/core/JobQueue_test.cpp +++ b/src/test/core/JobQueue_test.cpp @@ -36,7 +36,7 @@ class JobQueue_test : public beast::unit_test::suite // The Job should never run, so having the Job access this // unprotected variable on the stack should be completely safe. // Not recommended for the faint of heart... - bool unprotected; + bool unprotected = false; BEAST_EXPECT(jQueue.addJob(jtCLIENT, "JobAddTest2", [&unprotected]() { unprotected = false; }) == false); @@ -118,7 +118,7 @@ class JobQueue_test : public beast::unit_test::suite // The Coro should never run, so having the Coro access this // unprotected variable on the stack should be completely safe. // Not recommended for the faint of heart... - bool unprotected; + bool unprotected = false; auto const coro = jQueue.postCoro( jtCLIENT, "PostCoroTest3", [&unprotected](std::shared_ptr const&) { unprotected = false; diff --git a/src/test/jtx/AMMTest.h b/src/test/jtx/AMMTest.h index be6e228c0a..78e26b9e40 100644 --- a/src/test/jtx/AMMTest.h +++ b/src/test/jtx/AMMTest.h @@ -83,14 +83,14 @@ protected: */ void testAMM( - std::function&& cb, + std::function const& cb, std::optional> const& pool = std::nullopt, std::uint16_t tfee = 0, std::optional const& ter = std::nullopt, std::vector const& features = {testable_amendments()}); void - testAMM(std::function&& cb, TestAMMArg const& arg); + testAMM(std::function const& cb, TestAMMArg const& arg); }; class AMMTest : public jtx::AMMTestBase diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index bb159d6bc1..e1f6137a10 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -627,7 +628,8 @@ AMM::bid(BidArg const& arg) amm->isFieldPresent(sfAuctionSlot)); if (amm->isFieldPresent(sfAuctionSlot)) { - auto const& auctionSlot = static_cast(amm->peekAtField(sfAuctionSlot)); + auto const& auctionSlot = + safe_downcast(amm->peekAtField(sfAuctionSlot)); lastPurchasePrice_ = auctionSlot[sfPrice].iou(); } } @@ -719,7 +721,8 @@ AMM::expectAuctionSlot(auto&& cb) const amm->isFieldPresent(sfAuctionSlot)); if (amm->isFieldPresent(sfAuctionSlot)) { - auto const& auctionSlot = static_cast(amm->peekAtField(sfAuctionSlot)); + auto const& auctionSlot = + safe_downcast(amm->peekAtField(sfAuctionSlot)); if (auctionSlot.isFieldPresent(sfAccount)) { // This could fail in pre-fixInnerObjTemplate tests diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index bd567cf3de..eb39408fbd 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -82,18 +82,17 @@ AMMTestBase::AMMTestBase() void AMMTestBase::testAMM( - std::function&& cb, + std::function const& cb, std::optional> const& pool, std::uint16_t tfee, std::optional const& ter, std::vector const& vfeatures) { - testAMM( - std::move(cb), TestAMMArg{.pool = pool, .tfee = tfee, .ter = ter, .features = vfeatures}); + testAMM(cb, TestAMMArg{.pool = pool, .tfee = tfee, .ter = ter, .features = vfeatures}); } void -AMMTestBase::testAMM(std::function&& cb, TestAMMArg const& arg) +AMMTestBase::testAMM(std::function const& cb, TestAMMArg const& arg) { using namespace jtx; diff --git a/src/test/jtx/impl/Oracle.cpp b/src/test/jtx/impl/Oracle.cpp index 5aac101262..9c75b21973 100644 --- a/src/test/jtx/impl/Oracle.cpp +++ b/src/test/jtx/impl/Oracle.cpp @@ -273,7 +273,7 @@ Oracle::ledgerEntry( toJson(jvParams[jss::oracle][jss::oracle_document_id], *documentID); if (index) { - std::uint32_t i; + std::uint32_t i = 0; if (boost::conversion::try_lexical_convert(*index, i)) jvParams[jss::oracle][jss::ledger_index] = i; else diff --git a/src/test/jtx/impl/WSClient.cpp b/src/test/jtx/impl/WSClient.cpp index d7edbd6186..a51357c9b5 100644 --- a/src/test/jtx/impl/WSClient.cpp +++ b/src/test/jtx/impl/WSClient.cpp @@ -27,7 +27,7 @@ class WSClientImpl : public WSClient { Json::Value jv; - explicit msg(Json::Value&& jv_) : jv(jv_) + explicit msg(Json::Value&& jv_) : jv(std::move(jv_)) { } }; diff --git a/src/test/nodestore/Timing_test.cpp b/src/test/nodestore/Timing_test.cpp index e4ecd80654..e334283052 100644 --- a/src/test/nodestore/Timing_test.cpp +++ b/src/test/nodestore/Timing_test.cpp @@ -638,7 +638,7 @@ public: for (auto const& config_string : config_strings) { - Params params; + Params params{}; params.items = default_items; params.threads = threads; for (auto i = default_repeat; i--;) diff --git a/src/test/nodestore/import_test.cpp b/src/test/nodestore/import_test.cpp index 578dd3670e..2177646eaa 100644 --- a/src/test/nodestore/import_test.cpp +++ b/src/test/nodestore/import_test.cpp @@ -339,7 +339,7 @@ public: } // Create data file with values std::size_t nitems = 0; - dat_file_header dh; + dat_file_header dh{}; dh.version = currentVersion; dh.uid = make_uid(); dh.appnum = 1; @@ -406,7 +406,7 @@ public: if (ec) Throw(ec); // Create key file - key_file_header kh; + key_file_header kh{}; kh.version = currentVersion; kh.uid = dh.uid; kh.appnum = dh.appnum; @@ -465,7 +465,7 @@ public: { auto const offset = r.offset(); // Data Record or Spill Record - std::size_t size; + std::size_t size = 0; auto is = r.prepare(field::size, ec); // Size if (ec) Throw(ec); diff --git a/src/test/nodestore/varint_test.cpp b/src/test/nodestore/varint_test.cpp index 7ef624e777..f6145a9f52 100644 --- a/src/test/nodestore/varint_test.cpp +++ b/src/test/nodestore/varint_test.cpp @@ -17,11 +17,11 @@ public: testcase("encode, decode"); for (auto const v : vv) { - std::array::max> vi; + std::array::max> vi{}; auto const n0 = write_varint(vi.data(), v); expect(n0 > 0, "write error"); expect(n0 == size_varint(v), "size error"); - std::size_t v1; + std::size_t v1 = 0; auto const n1 = read_varint(vi.data(), n0, v1); expect(n1 == n0, "read error"); expect(v == v1, "wrong value"); diff --git a/src/test/overlay/reduce_relay_test.cpp b/src/test/overlay/reduce_relay_test.cpp index 3bc3ab2729..7e105e9f85 100644 --- a/src/test/overlay/reduce_relay_test.cpp +++ b/src/test/overlay/reduce_relay_test.cpp @@ -249,7 +249,7 @@ public: Validator& validator, PeerSPtr peer, Latency const& latency = {milliseconds(5), milliseconds(15)}) - : validator_(validator), peer_(peer), latency_(latency), up_(true) + : validator_(validator), peer_(peer), latency_(latency) { auto sp = peer_.lock(); assert(sp); @@ -294,7 +294,7 @@ private: Validator& validator_; PeerWPtr peer_; Latency latency_; - bool up_; + bool up_{true}; }; /** Simulate Validator */ @@ -553,7 +553,7 @@ public: addPeer(bool useCache = true) { PeerSPtr peer{}; - Peer::id_t id; + Peer::id_t id = 0; if (peersCache_.empty() || !useCache) { peer = std::make_shared(*this, logs_.journal("Squelch")); @@ -901,8 +901,8 @@ protected: std::uint32_t cnt_ = 0; std::uint32_t handledCnt_ = 0; bool isSelected_ = false; - Peer::id_t peer_; - std::uint16_t validator_; + Peer::id_t peer_{}; + std::uint16_t validator_{}; std::optional key_; time_point time_; bool handled_ = false; @@ -1449,7 +1449,7 @@ vp_base_squelch_max_selected_peers=2 struct Handler : public reduce_relay::SquelchHandler { - Handler() : maxDuration_(0) + Handler() { } void @@ -1462,7 +1462,7 @@ vp_base_squelch_max_selected_peers=2 unsquelch(PublicKey const&, Peer::id_t) const override { } - mutable int maxDuration_; + mutable int maxDuration_{0}; }; void diff --git a/src/test/protocol/MultiApiJson_test.cpp b/src/test/protocol/MultiApiJson_test.cpp index bbd6ec1a07..0da511b976 100644 --- a/src/test/protocol/MultiApiJson_test.cpp +++ b/src/test/protocol/MultiApiJson_test.cpp @@ -830,6 +830,7 @@ struct MultiApiJson_test : beast::unit_test::suite // Rvalue MultivarJson visitor only binds to regular reference static_assert([](auto&& v) { + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) return !requires { std::forward(v).visit(1, [](Json::Value&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { @@ -846,6 +847,7 @@ struct MultiApiJson_test : beast::unit_test::suite }; }(std::move(s1))); static_assert([](auto&& v) { + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) return !requires { std::forward(v).visit()(1, [](Json::Value&&) {}); }; }(std::move(s1))); static_assert([](auto&& v) { diff --git a/src/test/protocol/PublicKey_test.cpp b/src/test/protocol/PublicKey_test.cpp index 96dd4a6d0a..053e945a7b 100644 --- a/src/test/protocol/PublicKey_test.cpp +++ b/src/test/protocol/PublicKey_test.cpp @@ -17,7 +17,7 @@ public: { struct Table { - int val[256]; + int val[256]{}; Table() { std::fill(val, val + 256, 0); diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index c9d93b87a6..7ebe6e97ae 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -30,7 +30,7 @@ class Book_test : public beast::unit_test::suite { auto sleOfferDir = view->read(keylet::page(key.value())); uint256 offerIndex; - unsigned int bookEntry; + unsigned int bookEntry = 0; cdirFirst(*view, sleOfferDir->key(), sleOfferDir, bookEntry, offerIndex); auto sleOffer = view->read(keylet::offer(offerIndex)); dir = to_string(sleOffer->getFieldH256(sfBookDirectory)); diff --git a/src/test/server/ServerStatus_test.cpp b/src/test/server/ServerStatus_test.cpp index f48d1f4192..49ee3d2079 100644 --- a/src/test/server/ServerStatus_test.cpp +++ b/src/test/server/ServerStatus_test.cpp @@ -87,7 +87,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en std::random_device rd; std::mt19937 e{rd()}; std::uniform_int_distribution<> d(0, 255); - std::array key; + std::array key{}; for (auto& v : key) v = d(e); req.insert("Sec-WebSocket-Key", base64_encode(key.data(), key.size())); @@ -132,7 +132,7 @@ class ServerStatus_test : public beast::unit_test::suite, public beast::test::en void doRequest( boost::asio::yield_context& yield, - boost::beast::http::request&& req, + boost::beast::http::request const& req, std::string const& host, uint16_t port, bool secure, diff --git a/src/test/server/Server_test.cpp b/src/test/server/Server_test.cpp index 6e514cad1e..bc12d98659 100644 --- a/src/test/server/Server_test.cpp +++ b/src/test/server/Server_test.cpp @@ -100,8 +100,8 @@ public: Handoff onHandoff( Session& session, - std::unique_ptr&& bundle, - http_request_type&& request, + std::unique_ptr const& bundle, + http_request_type const& request, boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; @@ -110,7 +110,7 @@ public: Handoff onHandoff( Session& session, - http_request_type&& request, + http_request_type const& request, boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; @@ -308,8 +308,8 @@ public: Handoff onHandoff( Session& session, - std::unique_ptr&& bundle, - http_request_type&& request, + std::unique_ptr const& bundle, + http_request_type const& request, boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; @@ -318,7 +318,7 @@ public: Handoff onHandoff( Session& session, - http_request_type&& request, + http_request_type const& request, boost::asio::ip::tcp::endpoint remote_address) { return Handoff{}; diff --git a/src/test/shamap/FetchPack_test.cpp b/src/test/shamap/FetchPack_test.cpp index 8919241996..471ad91e95 100644 --- a/src/test/shamap/FetchPack_test.cpp +++ b/src/test/shamap/FetchPack_test.cpp @@ -45,7 +45,7 @@ public: bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t ledgerSeq, - Blob&& nodeData, + Blob&& nodeData, // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) SHAMapNodeType type) const override { } diff --git a/src/tests/libxrpl/basics/Slice.cpp b/src/tests/libxrpl/basics/Slice.cpp index 8fef0d61a3..0e5e0877d0 100644 --- a/src/tests/libxrpl/basics/Slice.cpp +++ b/src/tests/libxrpl/basics/Slice.cpp @@ -44,8 +44,8 @@ TEST(Slice, equality_and_inequality) } // Test slices of equal size but pointing to different data: - std::array a; - std::array b; + std::array a{}; + std::array b{}; for (std::size_t i = 0; i != sizeof(data); ++i) a[i] = b[i] = data[i]; diff --git a/src/tests/libxrpl/net/HTTPClient.cpp b/src/tests/libxrpl/net/HTTPClient.cpp index 1f648cced4..36159cb089 100644 --- a/src/tests/libxrpl/net/HTTPClient.cpp +++ b/src/tests/libxrpl/net/HTTPClient.cpp @@ -33,7 +33,7 @@ private: boost::asio::ip::tcp::endpoint endpoint_; bool running_{true}; bool finished_{false}; - unsigned short port_; + unsigned short port_{0}; // Custom headers to return std::map customHeaders_; @@ -43,7 +43,7 @@ private: beast::Journal j_; public: - TestHTTPServer() : acceptor_(ioc_), port_(0), j_(TestSink::instance()) + TestHTTPServer() : acceptor_(ioc_), j_(TestSink::instance()) { // Bind to any available port endpoint_ = {boost::asio::ip::tcp::v4(), 0}; diff --git a/src/xrpld/app/consensus/RCLConsensus.cpp b/src/xrpld/app/consensus/RCLConsensus.cpp index 91f24a650c..16cf7f4c9d 100644 --- a/src/xrpld/app/consensus/RCLConsensus.cpp +++ b/src/xrpld/app/consensus/RCLConsensus.cpp @@ -382,7 +382,10 @@ RCLConsensus::Adaptor::onAccept( bool const validating) { app_.getJobQueue().addJob( - jtACCEPT, "AcceptLedger", [=, this, cj = std::move(consensusJson)]() mutable { + jtACCEPT, + "AcceptLedger", + // NOLINTNEXTLINE(cppcoreguidelines-misleading-capture-default-by-value) + [=, this, cj = std::move(consensusJson)]() mutable { // Note that no lock is held or acquired during this job. // This is because generic Consensus guarantees that once a ledger // is accepted, the consensus results and capture by reference state @@ -406,7 +409,7 @@ RCLConsensus::Adaptor::doAccept( prevProposers_ = result.proposers; prevRoundTime_ = result.roundTime.read(); - bool closeTimeCorrect; + bool closeTimeCorrect = false; bool const proposing = mode == ConsensusMode::proposing; bool const haveCorrectLCL = mode != ConsensusMode::wrongLedger; @@ -671,7 +674,7 @@ RCLConsensus::Adaptor::notify( ledger.parentID().begin(), std::decay_t::bytes); s.set_ledgerhash(ledger.id().begin(), std::decay_t::bytes); - std::uint32_t uMin, uMax; + std::uint32_t uMin = 0, uMax = 0; if (!ledgerMaster_.getFullValidatedRange(uMin, uMax)) { uMin = 0; diff --git a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp index 575a1a1460..48080aaedb 100644 --- a/src/xrpld/app/ledger/ConsensusTransSetSF.cpp +++ b/src/xrpld/app/ledger/ConsensusTransSetSF.cpp @@ -21,7 +21,7 @@ ConsensusTransSetSF::gotNode( bool fromFilter, SHAMapHash const& nodeHash, std::uint32_t, - Blob&& nodeData, + Blob&& nodeData, // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved) SHAMapNodeType type) const { if (fromFilter) diff --git a/src/xrpld/app/ledger/Ledger.cpp b/src/xrpld/app/ledger/Ledger.cpp index bde5ca010a..3a81b5f3a3 100644 --- a/src/xrpld/app/ledger/Ledger.cpp +++ b/src/xrpld/app/ledger/Ledger.cpp @@ -846,7 +846,7 @@ Ledger::updateSkipList() auto sle = peek(k); std::vector hashes; - bool created; + bool created = false; if (!sle) { sle = std::make_shared(k); @@ -873,7 +873,7 @@ Ledger::updateSkipList() auto const k = keylet::skip(); auto sle = peek(k); std::vector hashes; - bool created; + bool created = false; if (!sle) { sle = std::make_shared(k); @@ -1003,7 +1003,7 @@ Ledger::invariants() const std::shared_ptr loadLedgerHelper(LedgerHeader const& info, Application& app, bool acquire) { - bool loaded; + bool loaded = false; auto ledger = std::make_shared( info, loaded, acquire, app.config(), app.getNodeFamily(), app.journal("Ledger")); diff --git a/src/xrpld/app/ledger/LedgerReplayTask.h b/src/xrpld/app/ledger/LedgerReplayTask.h index 028e7ba0bd..030121b240 100644 --- a/src/xrpld/app/ledger/LedgerReplayTask.h +++ b/src/xrpld/app/ledger/LedgerReplayTask.h @@ -78,7 +78,7 @@ public: InboundLedgers& inboundLedgers, LedgerReplayer& replayer, std::shared_ptr& skipListAcquirer, - TaskParameter&& parameter); + TaskParameter const& parameter); ~LedgerReplayTask(); diff --git a/src/xrpld/app/ledger/detail/InboundLedgers.cpp b/src/xrpld/app/ledger/detail/InboundLedgers.cpp index e17437d64f..a5fdd889ec 100644 --- a/src/xrpld/app/ledger/detail/InboundLedgers.cpp +++ b/src/xrpld/app/ledger/detail/InboundLedgers.cpp @@ -340,7 +340,7 @@ public: // Make a list of things to sweep, while holding the lock std::vector stuffToSweep; - std::size_t total; + std::size_t total = 0; { ScopedLockType sl(mLock); diff --git a/src/xrpld/app/ledger/detail/InboundTransactions.cpp b/src/xrpld/app/ledger/detail/InboundTransactions.cpp index b6f4c961c1..b10adad438 100644 --- a/src/xrpld/app/ledger/detail/InboundTransactions.cpp +++ b/src/xrpld/app/ledger/detail/InboundTransactions.cpp @@ -50,7 +50,6 @@ public: std::function const&, bool)> gotSet, std::unique_ptr peerSetBuilder) : app_(app) - , m_seq(0) , m_zeroSet(m_map[uint256()]) , m_gotSet(std::move(gotSet)) , m_peerSetBuilder(std::move(peerSetBuilder)) @@ -227,7 +226,7 @@ private: bool stopping_{false}; MapType m_map; - std::uint32_t m_seq; + std::uint32_t m_seq{0}; // The empty transaction set whose hash is zero InboundTransactionSet& m_zeroSet; diff --git a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp index ad9c6a277d..4266185591 100644 --- a/src/xrpld/app/ledger/detail/LedgerCleaner.cpp +++ b/src/xrpld/app/ledger/detail/LedgerCleaner.cpp @@ -356,10 +356,10 @@ private: while (!shouldExit()) { - LedgerIndex ledgerIndex; + LedgerIndex ledgerIndex = 0; LedgerHash ledgerHash; - bool doNodes; - bool doTxns; + bool doNodes = false; + bool doTxns = false; if (app_.getFeeTrack().isLoadedLocal()) { diff --git a/src/xrpld/app/ledger/detail/LedgerMaster.cpp b/src/xrpld/app/ledger/detail/LedgerMaster.cpp index 64bdf04df1..178e14f5c1 100644 --- a/src/xrpld/app/ledger/detail/LedgerMaster.cpp +++ b/src/xrpld/app/ledger/detail/LedgerMaster.cpp @@ -927,7 +927,7 @@ LedgerMaster::checkAccept(std::shared_ptr const& ledger) fees.reserve(fees.size() + fees2.size()); std::copy(fees2.begin(), fees2.end(), std::back_inserter(fees)); } - std::uint32_t fee; + std::uint32_t fee = 0; if (!fees.empty()) { std::sort(fees.begin(), fees.end()); @@ -1063,10 +1063,7 @@ LedgerMaster::consensusBuilt( class valSeq { public: - valSeq() : valCount_(0), ledgerSeq_(0) - { - ; - } + valSeq() = default; void mergeValidation(LedgerIndex seq) @@ -1078,8 +1075,8 @@ LedgerMaster::consensusBuilt( ledgerSeq_ = seq; } - std::size_t valCount_; - LedgerIndex ledgerSeq_; + std::size_t valCount_{0}; + LedgerIndex ledgerSeq_{0}; }; // Count the number of current, trusted validations @@ -1750,7 +1747,7 @@ LedgerMaster::fetchForHistory( XRPL_ASSERT(seq == missing, "xrpl::LedgerMaster::fetchForHistory : sequence match"); JLOG(m_journal.trace()) << "fetchForHistory acquired " << seq; setFullLedger(ledger, false, false); - int fillInProgress; + int fillInProgress = 0; { std::lock_guard lock(m_mutex); mHistLedger = ledger; @@ -1771,7 +1768,7 @@ LedgerMaster::fetchForHistory( } else { - std::uint32_t fetchSz; + std::uint32_t fetchSz = 0; // Do not fetch ledger sequences lower // than the earliest ledger sequence fetchSz = app_.getNodeStore().earliestLedgerSeq(); diff --git a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp index 73fcf77e4e..93cf0e5cce 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayMsgHandler.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -136,7 +137,7 @@ LedgerReplayMsgHandler::processProofPathResponse( return false; } - if (auto item = static_cast(node.get())->peekItem()) + if (auto item = safe_downcast(node.get())->peekItem()) { replayer_.gotSkipList(info, item); return true; diff --git a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp index 42db911830..8f225335c7 100644 --- a/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp +++ b/src/xrpld/app/ledger/detail/LedgerReplayTask.cpp @@ -67,7 +67,7 @@ LedgerReplayTask::LedgerReplayTask( InboundLedgers& inboundLedgers, LedgerReplayer& replayer, std::shared_ptr& skipListAcquirer, - TaskParameter&& parameter) + TaskParameter const& parameter) : TimeoutCounter( app, parameter.finishHash_, diff --git a/src/xrpld/app/main/Application.cpp b/src/xrpld/app/main/Application.cpp index 3e3d87dcd5..53eada2dec 100644 --- a/src/xrpld/app/main/Application.cpp +++ b/src/xrpld/app/main/Application.cpp @@ -1346,7 +1346,8 @@ ApplicationImp::setup(boost::program_options::variables_map const& cmdline) { try { - auto setup = setup_ServerHandler(*config_, beast::logstream{m_journal.error()}); + beast::logstream logStream{m_journal.error()}; + auto setup = setup_ServerHandler(*config_, logStream); setup.makeContexts(); serverHandler_->setup(setup, m_journal); fixConfigPorts(*config_, serverHandler_->endpoints()); @@ -1867,7 +1868,7 @@ ApplicationImp::loadOldLedger( else { // assume by sequence - std::uint32_t index; + std::uint32_t index = 0; if (beast::lexicalCastChecked(index, ledgerID)) loadLedger = loadByIndex(index, *this); diff --git a/src/xrpld/app/main/GRPCServer.cpp b/src/xrpld/app/main/GRPCServer.cpp index c6b5c91e14..7f4fb57fb7 100644 --- a/src/xrpld/app/main/GRPCServer.cpp +++ b/src/xrpld/app/main/GRPCServer.cpp @@ -383,8 +383,8 @@ GRPCServerImpl::handleRpcs() requests.pop_back(); }; - void* tag; // uniquely identifies a request. - bool ok; + void* tag = nullptr; // uniquely identifies a request. + bool ok = false; // Block waiting to read the next event from the completion queue. The // event is uniquely identified by its tag, which in this case is the // memory address of a CallData instance. diff --git a/src/xrpld/app/main/Main.cpp b/src/xrpld/app/main/Main.cpp index 56ddc07279..7c440d728c 100644 --- a/src/xrpld/app/main/Main.cpp +++ b/src/xrpld/app/main/Main.cpp @@ -61,7 +61,7 @@ adjustDescriptorLimit(int needed, beast::Journal j) { #ifdef RLIMIT_NOFILE // Get the current limit, then adjust it to what we need. - struct rlimit rl; + struct rlimit rl{}; int available = 0; diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index fd3caa4dab..2ceabd6608 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -165,9 +165,9 @@ class NetworkOPsImp final : public NetworkOPs struct CounterData { decltype(counters_) counters; - decltype(mode_) mode; + decltype(mode_) mode = OperatingMode::DISCONNECTED; decltype(start_) start; - decltype(initialSyncUs_) initialSyncUs; + decltype(initialSyncUs_) initialSyncUs{}; }; CounterData @@ -648,23 +648,16 @@ private: { AccountID const accountId_; // forward - std::uint32_t forwardTxIndex_; + std::uint32_t forwardTxIndex_{0}; // separate backward and forward - std::uint32_t separationLedgerSeq_; + std::uint32_t separationLedgerSeq_{0}; // history, backward - std::uint32_t historyLastLedgerSeq_; - std::int32_t historyTxIndex_; - bool haveHistorical_; - std::atomic stopHistorical_; + std::uint32_t historyLastLedgerSeq_{0}; + std::int32_t historyTxIndex_{-1}; + bool haveHistorical_{false}; + std::atomic stopHistorical_{false}; - SubAccountHistoryIndex(AccountID const& accountId) - : accountId_(accountId) - , forwardTxIndex_(0) - , separationLedgerSeq_(0) - , historyLastLedgerSeq_(0) - , historyTxIndex_(-1) - , haveHistorical_(false) - , stopHistorical_(false) + SubAccountHistoryIndex(AccountID const& accountId) : accountId_(accountId) { } }; @@ -717,7 +710,7 @@ private: std::optional const validatorPK_; std::optional const validatorMasterPK_; - ConsensusPhase mLastConsensusPhase; + ConsensusPhase mLastConsensusPhase{ConsensusPhase::open}; LedgerMaster& m_ledgerMaster; @@ -1639,7 +1632,7 @@ NetworkOPsImp::getOwnerInfo(std::shared_ptr lpLedger, AccountID auto sleNode = lpLedger->read(keylet::page(root)); if (sleNode) { - std::uint64_t uNodeDir; + std::uint64_t uNodeDir = 0; do { @@ -3597,7 +3590,8 @@ NetworkOPsImp::addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo) switch (dbType) { case Sqlite: { - auto db = static_cast(®istry_.getRelationalDatabase()); + auto db = + safe_downcast(®istry_.getRelationalDatabase()); RelationalDatabase::AccountTxPageOptions options{ accountId, minLedger, maxLedger, marker, 0, true}; return db->newestAccountTxPage(options); @@ -4203,7 +4197,7 @@ NetworkOPsImp::getBookPage( std::shared_ptr sleOfferDir; uint256 offerIndex; - unsigned int uBookEntry; + unsigned int uBookEntry = 0; STAmount saDirRate; auto const rate = transferRate(view, book.out.account); diff --git a/src/xrpld/app/misc/SHAMapStoreImp.cpp b/src/xrpld/app/misc/SHAMapStoreImp.cpp index 47e9f0ef52..60dcd90388 100644 --- a/src/xrpld/app/misc/SHAMapStoreImp.cpp +++ b/src/xrpld/app/misc/SHAMapStoreImp.cpp @@ -97,7 +97,7 @@ SHAMapStoreImp::SHAMapStoreImp( { // Configuration that affects the behavior of online delete get_if_exists(section, "delete_batch", deleteBatch_); - std::uint32_t temp; + std::uint32_t temp = 0; if (get_if_exists(section, "back_off_milliseconds", temp) || // Included for backward compatibility with an undocumented setting get_if_exists(section, "backOff", temp)) diff --git a/src/xrpld/app/misc/ValidatorSite.h b/src/xrpld/app/misc/ValidatorSite.h index 9c2d45fb6d..9d9031b9a2 100644 --- a/src/xrpld/app/misc/ValidatorSite.h +++ b/src/xrpld/app/misc/ValidatorSite.h @@ -197,7 +197,7 @@ private: onSiteFetch( boost::system::error_code const& ec, endpoint_type const& endpoint, - detail::response_type&& res, + detail::response_type const& res, std::size_t siteIdx); /// Store latest list fetched from anywhere @@ -224,7 +224,7 @@ private: /// lock over sites_mutex_ required std::shared_ptr processRedirect( - detail::response_type& res, + detail::response_type const& res, std::size_t siteIdx, std::lock_guard const&); diff --git a/src/xrpld/app/misc/detail/AmendmentTable.cpp b/src/xrpld/app/misc/detail/AmendmentTable.cpp index 196584fe6f..5bdd604828 100644 --- a/src/xrpld/app/misc/detail/AmendmentTable.cpp +++ b/src/xrpld/app/misc/detail/AmendmentTable.cpp @@ -357,7 +357,7 @@ private: mutable std::mutex mutex_; hash_map amendmentMap_; - std::uint32_t lastUpdateSeq_; + std::uint32_t lastUpdateSeq_{0}; // Record of the last votes seen from trusted validators. TrustedVotes previousTrustedVotes_; @@ -370,7 +370,7 @@ private: std::unique_ptr lastVote_; // True if an unsupported amendment is enabled - bool unsupportedEnabled_; + bool unsupportedEnabled_{false}; // Unset if no unsupported amendments reach majority, // else set to the earliest time an unsupported amendment @@ -477,11 +477,7 @@ AmendmentTableImpl::AmendmentTableImpl( Section const& enabled, Section const& vetoed, beast::Journal journal) - : lastUpdateSeq_(0) - , majorityTime_(majorityTime) - , unsupportedEnabled_(false) - , j_(journal) - , db_(registry.getWalletDB()) + : majorityTime_(majorityTime), j_(journal), db_(registry.getWalletDB()) { std::lock_guard lock(mutex_); diff --git a/src/xrpld/app/misc/detail/TxQ.cpp b/src/xrpld/app/misc/detail/TxQ.cpp index 718b468ff0..caa5a15ff1 100644 --- a/src/xrpld/app/misc/detail/TxQ.cpp +++ b/src/xrpld/app/misc/detail/TxQ.cpp @@ -1798,7 +1798,7 @@ setup_TxQ(Config const& config) set(setup.minimumTxnInLedger, "minimum_txn_in_ledger", section); set(setup.minimumTxnInLedgerSA, "minimum_txn_in_ledger_standalone", section); set(setup.targetTxnInLedger, "target_txn_in_ledger", section); - std::uint32_t max; + std::uint32_t max = 0; if (set(max, "maximum_txn_in_ledger", section)) { if (max < setup.minimumTxnInLedger) diff --git a/src/xrpld/app/misc/detail/ValidatorSite.cpp b/src/xrpld/app/misc/detail/ValidatorSite.cpp index c4077a1b8b..0a207c344c 100644 --- a/src/xrpld/app/misc/detail/ValidatorSite.cpp +++ b/src/xrpld/app/misc/detail/ValidatorSite.cpp @@ -367,7 +367,7 @@ ValidatorSite::parseJsonResponse( body[jss::manifest].isString() && body.isMember(jss::version) && body[jss::version].isInt(); // Check the version-specific blob & signature fields - std::uint32_t version; + std::uint32_t version = 0; std::vector blobs; if (valid) { @@ -453,7 +453,7 @@ ValidatorSite::parseJsonResponse( std::shared_ptr ValidatorSite::processRedirect( - detail::response_type& res, + detail::response_type const& res, std::size_t siteIdx, std::lock_guard const& sites_lock) { @@ -496,7 +496,7 @@ void ValidatorSite::onSiteFetch( boost::system::error_code const& ec, endpoint_type const& endpoint, - detail::response_type&& res, + detail::response_type const& res, std::size_t siteIdx) { std::lock_guard lock_sites{sites_mutex_}; diff --git a/src/xrpld/app/paths/PathRequest.h b/src/xrpld/app/paths/PathRequest.h index fde499a312..0ffc6c6e2c 100644 --- a/src/xrpld/app/paths/PathRequest.h +++ b/src/xrpld/app/paths/PathRequest.h @@ -139,7 +139,7 @@ private: std::optional domain; - bool convert_all_; + bool convert_all_{}; std::recursive_mutex mIndexLock; LedgerIndex mLastIndex; diff --git a/src/xrpld/app/paths/Pathfinder.cpp b/src/xrpld/app/paths/Pathfinder.cpp index 14bfe2b4fc..b852ebd4d4 100644 --- a/src/xrpld/app/paths/Pathfinder.cpp +++ b/src/xrpld/app/paths/Pathfinder.cpp @@ -260,7 +260,7 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue // Now compute the payment type from the types of the source and destination // currencies. - PaymentType paymentType; + PaymentType paymentType = pt_XRP_to_XRP; if (bSrcXrp && bDstXrp) { // XRP -> XRP @@ -491,7 +491,7 @@ Pathfinder::rankPaths( if (!currentPath.empty()) { STAmount liquidity; - uint64_t uQuality; + uint64_t uQuality = 0; auto const resultCode = getPathLiquidity(currentPath, saMinDstAmount, liquidity, uQuality); if (resultCode != tesSUCCESS) diff --git a/src/xrpld/app/rdb/backend/detail/Node.cpp b/src/xrpld/app/rdb/backend/detail/Node.cpp index 9425cd9159..eccc946e9f 100644 --- a/src/xrpld/app/rdb/backend/detail/Node.cpp +++ b/src/xrpld/app/rdb/backend/detail/Node.cpp @@ -74,8 +74,8 @@ makeLedgerDBs( { // Check if AccountTransactions has primary key std::string cid, name, type; - std::size_t notnull, dflt_value, pk; - soci::indicator ind; + std::size_t notnull = 0, dflt_value = 0, pk = 0; + soci::indicator ind = soci::i_null; soci::statement st = (tx->getSession().prepare << ("PRAGMA table_info(AccountTransactions);"), soci::into(cid), @@ -136,7 +136,7 @@ deleteBeforeLedgerSeq(soci::session& session, TableType type, LedgerIndex ledger std::size_t getRows(soci::session& session, TableType type) { - std::size_t rows; + std::size_t rows = 0; session << "SELECT COUNT(*) AS rows " "FROM " << to_string(type) << ";", @@ -148,7 +148,7 @@ getRows(soci::session& session, TableType type) RelationalDatabase::CountMinMax getRowsMinMax(soci::session& session, TableType type) { - RelationalDatabase::CountMinMax res; + RelationalDatabase::CountMinMax res{}; session << "SELECT COUNT(*) AS rows, " "MIN(LedgerSeq) AS first, " "MAX(LedgerSeq) AS last " @@ -543,7 +543,7 @@ getHashesByIndex(soci::session& session, LedgerIndex minSeq, LedgerIndex maxSeq, sql.append(std::to_string(maxSeq)); sql.append(";"); - std::uint64_t ls; + std::uint64_t ls = 0; std::string lh; // SOCI requires boost::optional (not std::optional) as the parameter. boost::optional ph; @@ -587,7 +587,7 @@ getTxHistory(soci::session& session, Application& app, LedgerIndex startIndex, i boost::optional ledgerSeq; boost::optional status; soci::blob sociRawTxnBlob(session); - soci::indicator rti; + soci::indicator rti = soci::i_null; Blob rawTxn; soci::statement st = @@ -645,7 +645,7 @@ transactionsSQL( constexpr std::uint32_t NONBINARY_PAGE_LENGTH = 200; constexpr std::uint32_t BINARY_PAGE_LENGTH = 500; - std::uint32_t numberOfResults; + std::uint32_t numberOfResults = 0; if (count) { @@ -755,7 +755,7 @@ getAccountTxs( boost::optional ledgerSeq; boost::optional status; soci::blob sociTxnBlob(session), sociTxnMetaBlob(session); - soci::indicator rti, tmi; + soci::indicator rti = soci::i_null, tmi = soci::i_null; Blob rawTxn, txnMeta; soci::statement st = @@ -872,7 +872,7 @@ getAccountTxsB( boost::optional ledgerSeq; boost::optional status; soci::blob sociTxnBlob(session), sociTxnMetaBlob(session); - soci::indicator rti, tmi; + soci::indicator rti = soci::i_null, tmi = soci::i_null; soci::statement st = (session.prepare << sql, @@ -953,7 +953,7 @@ accountTxPage( bool lookingForMarker = options.marker.has_value(); - std::uint32_t numberOfResults; + std::uint32_t numberOfResults = 0; if (options.limit == 0 || options.limit == UINT32_MAX || (options.limit > page_length && !options.bAdmin)) @@ -1041,7 +1041,7 @@ accountTxPage( boost::optional status; soci::blob txnData(session); soci::blob txnMeta(session); - soci::indicator dataPresent, metaPresent; + soci::indicator dataPresent = soci::i_null, metaPresent = soci::i_null; soci::statement st = (session.prepare << sql, @@ -1151,7 +1151,7 @@ getTransaction( Blob rawTxn, rawMeta; { soci::blob sociRawTxnBlob(session), sociRawMetaBlob(session); - soci::indicator txn, meta; + soci::indicator txn = soci::i_null, meta = soci::i_null; session << sql, soci::into(ledgerSeq), soci::into(status), soci::into(sociRawTxnBlob, txn), soci::into(sociRawMetaBlob, meta); @@ -1164,7 +1164,7 @@ getTransaction( if (!got_data) { uint64_t count = 0; - soci::indicator rti; + soci::indicator rti = soci::i_null; session << "SELECT COUNT(DISTINCT LedgerSeq) FROM Transactions WHERE " "LedgerSeq BETWEEN " @@ -1230,16 +1230,16 @@ dbHasSpace(soci::session& session, Config const& config, beast::Journal j) } static auto const pageSize = [&] { - std::uint32_t ps; + std::uint32_t ps = 0; session << "PRAGMA page_size;", soci::into(ps); return ps; }(); static auto const maxPages = [&] { - std::uint32_t mp; + std::uint32_t mp = 0; session << "PRAGMA max_page_count;", soci::into(mp); return mp; }(); - std::uint32_t pageCount; + std::uint32_t pageCount = 0; session << "PRAGMA page_count;", soci::into(pageCount); std::uint32_t freePages = maxPages - pageCount; std::uint64_t freeSpace = safe_cast(freePages) * pageSize; diff --git a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp index 1b15fcf52e..4f5365ea01 100644 --- a/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp +++ b/src/xrpld/app/rdb/backend/detail/SQLiteDatabase.cpp @@ -400,7 +400,8 @@ SQLiteDatabase::oldestAccountTxPage(AccountTxPageOptions const& options) auto onTransaction = [&ret, &app = registry_.app()]( std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { - convertBlobsToTxResult(ret, ledger_index, status, rawTxn, rawMeta, app); + convertBlobsToTxResult( + ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); }; if (existsTransaction()) @@ -428,7 +429,8 @@ SQLiteDatabase::newestAccountTxPage(AccountTxPageOptions const& options) auto onTransaction = [&ret, &app = registry_.app()]( std::uint32_t ledger_index, std::string const& status, Blob&& rawTxn, Blob&& rawMeta) { - convertBlobsToTxResult(ret, ledger_index, status, rawTxn, rawMeta, app); + convertBlobsToTxResult( + ret, ledger_index, status, std::move(rawTxn), std::move(rawMeta), app); }; if (existsTransaction()) diff --git a/src/xrpld/app/rdb/detail/PeerFinder.cpp b/src/xrpld/app/rdb/detail/PeerFinder.cpp index cfab6f764a..d619d4bb85 100644 --- a/src/xrpld/app/rdb/detail/PeerFinder.cpp +++ b/src/xrpld/app/rdb/detail/PeerFinder.cpp @@ -83,7 +83,7 @@ updatePeerFinderDB(soci::session& session, int currentSchemaVersion, beast::Jour " PeerFinder_BootstrapCache_Next " " ( address ); "; - std::size_t count; + std::size_t count = 0; session << "SELECT COUNT(*) FROM PeerFinder_BootstrapCache;", soci::into(count); std::vector list; @@ -91,7 +91,7 @@ updatePeerFinderDB(soci::session& session, int currentSchemaVersion, beast::Jour { list.reserve(count); std::string s; - int valence; + int valence = 0; soci::statement st = (session.prepare << "SELECT " " address, " @@ -187,7 +187,7 @@ void readPeerFinderDB(soci::session& session, std::function const& func) { std::string s; - int valence; + int valence = 0; soci::statement st = (session.prepare << "SELECT " " address, " diff --git a/src/xrpld/core/detail/Config.cpp b/src/xrpld/core/detail/Config.cpp index ce4ba43cd8..cee1ce5ed1 100644 --- a/src/xrpld/core/detail/Config.cpp +++ b/src/xrpld/core/detail/Config.cpp @@ -51,7 +51,7 @@ namespace detail { [[nodiscard]] std::uint64_t getMemorySize() { - if (struct sysinfo si; sysinfo(&si) == 0) + if (struct sysinfo si{}; sysinfo(&si) == 0) return static_cast(si.totalram) * si.mem_unit; return 0; @@ -1050,13 +1050,13 @@ setup_FeeVote(Section const& section) { FeeSetup setup; { - std::uint64_t temp; + std::uint64_t temp = 0; if (set(temp, "reference_fee", section) && temp <= std::numeric_limits::max()) setup.reference_fee = temp; } { - std::uint32_t temp; + std::uint32_t temp = 0; if (set(temp, "account_reserve", section)) setup.account_reserve = temp; if (set(temp, "owner_reserve", section)) diff --git a/src/xrpld/overlay/detail/Handshake.cpp b/src/xrpld/overlay/detail/Handshake.cpp index c463a31257..715afc90e8 100644 --- a/src/xrpld/overlay/detail/Handshake.cpp +++ b/src/xrpld/overlay/detail/Handshake.cpp @@ -211,7 +211,7 @@ verifyHandshake( if (auto const iter = headers.find("Network-ID"); iter != headers.end()) { - std::uint32_t nid; + std::uint32_t nid = 0; if (!beast::lexicalCastChecked(nid, iter->value())) throw std::runtime_error("Invalid peer network identifier"); @@ -223,7 +223,7 @@ verifyHandshake( if (auto const iter = headers.find("Network-Time"); iter != headers.end()) { auto const netTime = [str = iter->value()]() -> TimeKeeper::time_point { - TimeKeeper::duration::rep val; + TimeKeeper::duration::rep val = 0; if (beast::lexicalCastChecked(val, str)) return TimeKeeper::time_point{TimeKeeper::duration{val}}; diff --git a/src/xrpld/overlay/detail/OverlayImpl.cpp b/src/xrpld/overlay/detail/OverlayImpl.cpp index f3280c4923..7fc977a7ab 100644 --- a/src/xrpld/overlay/detail/OverlayImpl.cpp +++ b/src/xrpld/overlay/detail/OverlayImpl.cpp @@ -635,7 +635,7 @@ OverlayImpl::onManifests( if (!relay.list().empty()) for_each([m2 = std::make_shared(relay, protocol::mtMANIFESTS)]( - std::shared_ptr&& p) { p->send(m2); }); + std::shared_ptr const& p) { p->send(m2); }); } void @@ -673,7 +673,7 @@ OverlayImpl::getOverlayInfo() Json::Value jv; auto& av = jv["active"] = Json::Value(Json::arrayValue); - for_each([&](std::shared_ptr&& sp) { + for_each([&](std::shared_ptr const& sp) { auto& pv = av.append(Json::Value(Json::objectValue)); pv[jss::public_key] = base64_encode(sp->getNodePublic().data(), sp->getNodePublic().size()); pv[jss::type] = sp->slot()->inbound() ? "in" : "out"; @@ -699,7 +699,7 @@ OverlayImpl::getOverlayInfo() pv[jss::version] = std::string{version}; } - std::uint32_t minSeq, maxSeq; + std::uint32_t minSeq = 0, maxSeq = 0; sp->ledgerRange(minSeq, maxSeq); if (minSeq != 0 || maxSeq != 0) pv[jss::complete_ledgers] = std::to_string(minSeq) + "-" + std::to_string(maxSeq); @@ -991,7 +991,7 @@ OverlayImpl::getActivePeers() const Overlay::PeerSequence ret; ret.reserve(size()); - for_each([&ret](std::shared_ptr&& sp) { ret.emplace_back(std::move(sp)); }); + for_each([&ret](std::shared_ptr const& sp) { ret.emplace_back(std::move(sp)); }); return ret; } @@ -1034,7 +1034,7 @@ OverlayImpl::getActivePeers( void OverlayImpl::checkTracking(std::uint32_t index) { - for_each([index](std::shared_ptr&& sp) { sp->checkTracking(index); }); + for_each([index](std::shared_ptr const& sp) { sp->checkTracking(index); }); } std::shared_ptr @@ -1070,7 +1070,7 @@ void OverlayImpl::broadcast(protocol::TMProposeSet& m) { auto const sm = std::make_shared(m, protocol::mtPROPOSE_LEDGER); - for_each([&](std::shared_ptr&& p) { p->send(sm); }); + for_each([&](std::shared_ptr const& p) { p->send(sm); }); } std::set @@ -1079,7 +1079,7 @@ OverlayImpl::relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey cons if (auto const toSkip = app_.getHashRouter().shouldRelay(uid)) { auto const sm = std::make_shared(m, protocol::mtPROPOSE_LEDGER, validator); - for_each([&](std::shared_ptr&& p) { + for_each([&](std::shared_ptr const& p) { if (toSkip->find(p->id()) == toSkip->end()) p->send(sm); }); @@ -1092,7 +1092,7 @@ void OverlayImpl::broadcast(protocol::TMValidation& m) { auto const sm = std::make_shared(m, protocol::mtVALIDATION); - for_each([sm](std::shared_ptr&& p) { p->send(sm); }); + for_each([sm](std::shared_ptr const& p) { p->send(sm); }); } std::set @@ -1101,7 +1101,7 @@ OverlayImpl::relay(protocol::TMValidation& m, uint256 const& uid, PublicKey cons if (auto const toSkip = app_.getHashRouter().shouldRelay(uid)) { auto const sm = std::make_shared(m, protocol::mtVALIDATION, validator); - for_each([&](std::shared_ptr&& p) { + for_each([&](std::shared_ptr const& p) { if (toSkip->find(p->id()) == toSkip->end()) p->send(sm); }); diff --git a/src/xrpld/overlay/detail/PeerImp.cpp b/src/xrpld/overlay/detail/PeerImp.cpp index 248ff65d6d..18e784cdeb 100644 --- a/src/xrpld/overlay/detail/PeerImp.cpp +++ b/src/xrpld/overlay/detail/PeerImp.cpp @@ -392,7 +392,7 @@ PeerImp::json() ret[jss::uptime] = static_cast(std::chrono::duration_cast(uptime()).count()); - std::uint32_t minSeq, maxSeq; + std::uint32_t minSeq = 0, maxSeq = 0; ledgerRange(minSeq, maxSeq); if ((minSeq != 0) || (maxSeq != 0)) @@ -921,7 +921,7 @@ PeerImp::onReadMessage(error_code ec, std::size_t bytes_transferred) while (read_buffer_.size() > 0) { - std::size_t bytes_consumed; + std::size_t bytes_consumed = 0; using namespace std::chrono_literals; std::tie(bytes_consumed, ec) = perf::measureDurationAndLog( @@ -1315,7 +1315,7 @@ PeerImp::handleTransaction( } // LCOV_EXCL_STOP - HashRouterFlags flags; + HashRouterFlags flags = HashRouterFlags::UNDEFINED; constexpr std::chrono::seconds tx_interval = 10s; if (!app_.getHashRouter().shouldProcess(txID, id_, flags, tx_interval)) @@ -1856,7 +1856,7 @@ PeerImp::onMessage(std::shared_ptr const& m) checkTracking(m->ledgerseq(), app_.getLedgerMaster().getValidLedgerIndex()); } - app_.getOPs().pubPeerStatus([=, this]() -> Json::Value { + app_.getOPs().pubPeerStatus([m, this]() -> Json::Value { Json::Value j = Json::objectValue; if (m->has_newstatus()) @@ -1933,7 +1933,7 @@ PeerImp::onMessage(std::shared_ptr const& m) void PeerImp::checkTracking(std::uint32_t validationSeq) { - std::uint32_t serverSeq; + std::uint32_t serverSeq = 0; { // Extract the sequence number of the highest // ledger this peer has @@ -2879,7 +2879,7 @@ PeerImp::checkPropose( return; } - bool relay; + bool relay = false; if (isTrusted) relay = app_.getOPs().processTrustedProposal(peerPos); diff --git a/src/xrpld/overlay/detail/ProtocolVersion.cpp b/src/xrpld/overlay/detail/ProtocolVersion.cpp index 3163ba55e0..29bff996a9 100644 --- a/src/xrpld/overlay/detail/ProtocolVersion.cpp +++ b/src/xrpld/overlay/detail/ProtocolVersion.cpp @@ -81,8 +81,8 @@ parseProtocolVersions(boost::beast::string_view const& value) if (boost::regex_match(s, m, re)) { - std::uint16_t major; - std::uint16_t minor; + std::uint16_t major = 0; + std::uint16_t minor = 0; if (!beast::lexicalCastChecked(major, std::string(m[1]))) continue; diff --git a/src/xrpld/perflog/detail/PerfLogImp.cpp b/src/xrpld/perflog/detail/PerfLogImp.cpp index d1267953e4..eb271ac91a 100644 --- a/src/xrpld/perflog/detail/PerfLogImp.cpp +++ b/src/xrpld/perflog/detail/PerfLogImp.cpp @@ -472,7 +472,7 @@ setup_PerfLog(Section const& section, boost::filesystem::path const& configDir) } } - std::uint64_t logInterval; + std::uint64_t logInterval = 0; if (get_if_exists(section, "log_interval", logInterval)) setup.logInterval = std::chrono::seconds(logInterval); return setup; diff --git a/src/xrpld/rpc/ServerHandler.h b/src/xrpld/rpc/ServerHandler.h index af7ec4bf1c..74f59756b0 100644 --- a/src/xrpld/rpc/ServerHandler.h +++ b/src/xrpld/rpc/ServerHandler.h @@ -182,7 +182,7 @@ private: Port const& port, std::string const& request, beast::IP::Endpoint const& remoteIPAddress, - Output&&, + Output const&, std::shared_ptr coro, std::string_view forwardedFor, std::string_view user); @@ -192,7 +192,7 @@ private: }; ServerHandler::Setup -setup_ServerHandler(Config const& c, std::ostream&& log); +setup_ServerHandler(Config const& c, std::ostream& log); std::unique_ptr make_ServerHandler( diff --git a/src/xrpld/rpc/detail/RPCCall.cpp b/src/xrpld/rpc/detail/RPCCall.cpp index 134cbb34f8..43ca166f9f 100644 --- a/src/xrpld/rpc/detail/RPCCall.cpp +++ b/src/xrpld/rpc/detail/RPCCall.cpp @@ -1476,8 +1476,8 @@ rpcClient( xrpl::ServerHandler::Setup setup; try { - setup = setup_ServerHandler( - config, beast::logstream{logs.journal("HTTPClient").warn()}); + beast::logstream rpcCallLog{logs.journal("HTTPClient").warn()}; + setup = setup_ServerHandler(config, rpcCallLog); } catch (std::exception const&) // NOLINT(bugprone-empty-catch) { diff --git a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp index ddf78425bd..acf9ecd23a 100644 --- a/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCLedgerHelpers.cpp @@ -55,7 +55,7 @@ ledgerFromIndex( if (index == "closed") return getLedger(ledger, LedgerShortcut::Closed, context); - std::uint32_t iVal; + std::uint32_t iVal = 0; if (!beast::lexicalCastChecked(iVal, index)) return {rpcINVALID_PARAMS, expected_field_message(fieldName, "string or number")}; diff --git a/src/xrpld/rpc/detail/RPCSub.cpp b/src/xrpld/rpc/detail/RPCSub.cpp index a0e29f68e2..49a78d0755 100644 --- a/src/xrpld/rpc/detail/RPCSub.cpp +++ b/src/xrpld/rpc/detail/RPCSub.cpp @@ -26,10 +26,8 @@ public: , m_io_context(io_context) , m_jobQueue(jobQueue) , mUrl(strUrl) - , mSSL(false) , mUsername(strUsername) , mPassword(strPassword) - , mSending(false) , j_(logs.journal("RPCSub")) , logs_(logs) { @@ -97,7 +95,7 @@ private: sendThread() { Json::Value jvEvent; - bool bSend; + bool bSend = false; do { @@ -159,14 +157,14 @@ private: std::string mUrl; std::string mIp; std::uint16_t mPort; - bool mSSL; + bool mSSL{false}; std::string mUsername; std::string mPassword; std::string mPath; int mSeq; // Next id to allocate. - bool mSending; // Sending thread is active. + bool mSending{false}; // Sending thread is active. std::deque> mDeque; diff --git a/src/xrpld/rpc/detail/ServerHandler.cpp b/src/xrpld/rpc/detail/ServerHandler.cpp index f6e20d0977..39f0be6722 100644 --- a/src/xrpld/rpc/detail/ServerHandler.cpp +++ b/src/xrpld/rpc/detail/ServerHandler.cpp @@ -561,7 +561,7 @@ ServerHandler::processRequest( Port const& port, std::string const& request, beast::IP::Endpoint const& remoteIPAddress, - Output&& output, + Output const& output, std::shared_ptr coro, std::string_view forwardedFor, std::string_view user) @@ -1175,7 +1175,7 @@ setup_Overlay(ServerHandler::Setup& setup) } ServerHandler::Setup -setup_ServerHandler(Config const& config, std::ostream&& log) +setup_ServerHandler(Config const& config, std::ostream& log) { ServerHandler::Setup setup; setup.ports = parse_Ports(config, log); diff --git a/src/xrpld/rpc/handlers/AMMInfo.cpp b/src/xrpld/rpc/handlers/AMMInfo.cpp index 4e91c9c308..e174a49f87 100644 --- a/src/xrpld/rpc/handlers/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/AMMInfo.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -175,7 +176,7 @@ doAMMInfo(RPC::JsonContext& context) "xrpl::doAMMInfo : auction slot is set"); if (amm->isFieldPresent(sfAuctionSlot)) { - auto const& auctionSlot = static_cast(amm->peekAtField(sfAuctionSlot)); + auto const& auctionSlot = safe_downcast(amm->peekAtField(sfAuctionSlot)); if (auctionSlot.isFieldPresent(sfAccount)) { Json::Value auction; diff --git a/src/xrpld/rpc/handlers/AccountChannels.cpp b/src/xrpld/rpc/handlers/AccountChannels.cpp index 062a2b69a0..d2c3d4546d 100644 --- a/src/xrpld/rpc/handlers/AccountChannels.cpp +++ b/src/xrpld/rpc/handlers/AccountChannels.cpp @@ -81,7 +81,7 @@ doAccountChannels(RPC::JsonContext& context) if (!strDst.empty() && !raDstAccount) return rpcError(rpcACT_MALFORMED); - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::accountChannels, context)) return *err; diff --git a/src/xrpld/rpc/handlers/AccountLines.cpp b/src/xrpld/rpc/handlers/AccountLines.cpp index bb61e6f6c0..d065180c64 100644 --- a/src/xrpld/rpc/handlers/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/AccountLines.cpp @@ -98,7 +98,7 @@ doAccountLines(RPC::JsonContext& context) return result; } - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::accountLines, context)) return *err; diff --git a/src/xrpld/rpc/handlers/AccountObjects.cpp b/src/xrpld/rpc/handlers/AccountObjects.cpp index e01822e901..f5f48d8050 100644 --- a/src/xrpld/rpc/handlers/AccountObjects.cpp +++ b/src/xrpld/rpc/handlers/AccountObjects.cpp @@ -53,7 +53,7 @@ doAccountNFTs(RPC::JsonContext& context) if (!ledger->exists(keylet::account(accountID))) return rpcError(rpcACT_NOT_FOUND); - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::accountNFTokens, context)) return *err; @@ -435,7 +435,7 @@ doAccountObjects(RPC::JsonContext& context) } } - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::accountObjects, context)) return *err; diff --git a/src/xrpld/rpc/handlers/AccountOffers.cpp b/src/xrpld/rpc/handlers/AccountOffers.cpp index 130decad04..842cac71eb 100644 --- a/src/xrpld/rpc/handlers/AccountOffers.cpp +++ b/src/xrpld/rpc/handlers/AccountOffers.cpp @@ -63,7 +63,7 @@ doAccountOffers(RPC::JsonContext& context) if (!ledger->exists(keylet::account(accountID))) return rpcError(rpcACT_NOT_FOUND); - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::accountOffers, context)) return *err; diff --git a/src/xrpld/rpc/handlers/AccountTx.cpp b/src/xrpld/rpc/handlers/AccountTx.cpp index a6dcbb7b9d..6c227b16b9 100644 --- a/src/xrpld/rpc/handlers/AccountTx.cpp +++ b/src/xrpld/rpc/handlers/AccountTx.cpp @@ -108,8 +108,8 @@ parseLedgerArgs(RPC::Context& context, Json::Value const& params) std::variant getLedgerRange(RPC::Context& context, std::optional const& ledgerSpecifier) { - std::uint32_t uValidatedMin; - std::uint32_t uValidatedMax; + std::uint32_t uValidatedMin = 0; + std::uint32_t uValidatedMax = 0; bool bValidated = context.ledgerMaster.getValidatedRange(uValidatedMin, uValidatedMax); if (!bValidated) diff --git a/src/xrpld/rpc/handlers/BookOffers.cpp b/src/xrpld/rpc/handlers/BookOffers.cpp index 070d7988de..593f3e1fa2 100644 --- a/src/xrpld/rpc/handlers/BookOffers.cpp +++ b/src/xrpld/rpc/handlers/BookOffers.cpp @@ -167,7 +167,7 @@ doBookOffers(RPC::JsonContext& context) return RPC::make_error(rpcBAD_MARKET); } - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::bookOffers, context)) return *err; diff --git a/src/xrpld/rpc/handlers/Connect.cpp b/src/xrpld/rpc/handlers/Connect.cpp index c76ebed546..415adbd2fd 100644 --- a/src/xrpld/rpc/handlers/Connect.cpp +++ b/src/xrpld/rpc/handlers/Connect.cpp @@ -33,7 +33,7 @@ doConnect(RPC::JsonContext& context) return rpcError(rpcINVALID_PARAMS); } - int iPort; + int iPort = 0; if (context.params.isMember(jss::port)) iPort = context.params[jss::port].asInt(); diff --git a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp index eaeff767cd..4fc8e360fc 100644 --- a/src/xrpld/rpc/handlers/GetAggregatePrice.cpp +++ b/src/xrpld/rpc/handlers/GetAggregatePrice.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -25,7 +26,7 @@ static void iteratePriceData( RPC::JsonContext& context, std::shared_ptr const& sle, - std::function&& f) + std::function const& f) { using Meta = std::shared_ptr; constexpr std::uint8_t maxHistory = 3; @@ -87,8 +88,8 @@ iteratePriceData( if (isNew && history == 1) return; - oracle = isNew ? &static_cast(node.peekAtField(sfNewFields)) - : &static_cast(node.peekAtField(sfFinalFields)); + oracle = isNew ? &safe_downcast(node.peekAtField(sfNewFields)) + : &safe_downcast(node.peekAtField(sfFinalFields)); break; } } @@ -148,7 +149,7 @@ doGetAggregatePrice(RPC::JsonContext& context) // support positive int, uint, and a number represented as a string auto validUInt = [](Json::Value const& params, Json::StaticString const& field) { auto const& jv = params[field]; - std::uint32_t v; + std::uint32_t v = 0; return jv.isUInt() || (jv.isInt() && jv.asInt() >= 0) || (jv.isString() && beast::lexicalCastChecked(v, jv.asString())); }; diff --git a/src/xrpld/rpc/handlers/NFTOffers.cpp b/src/xrpld/rpc/handlers/NFTOffers.cpp index 51f75bfe4c..3af7c28f9e 100644 --- a/src/xrpld/rpc/handlers/NFTOffers.cpp +++ b/src/xrpld/rpc/handlers/NFTOffers.cpp @@ -44,7 +44,7 @@ appendNftOfferJson( static Json::Value enumerateNFTOffers(RPC::JsonContext& context, uint256 const& nftId, Keylet const& directory) { - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::nftOffers, context)) return *err; diff --git a/src/xrpld/rpc/handlers/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/NoRippleCheck.cpp index e17a437efc..9985591303 100644 --- a/src/xrpld/rpc/handlers/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/NoRippleCheck.cpp @@ -60,7 +60,7 @@ doNoRippleCheck(RPC::JsonContext& context) return RPC::invalid_field_error("role"); } - unsigned int limit; + unsigned int limit = 0; if (auto err = readLimitField(limit, RPC::Tuning::noRippleCheck, context)) return *err; diff --git a/src/xrpld/rpc/handlers/Tx.cpp b/src/xrpld/rpc/handlers/Tx.cpp index 84f2a6c618..a34c1f1a2e 100644 --- a/src/xrpld/rpc/handlers/Tx.cpp +++ b/src/xrpld/rpc/handlers/Tx.cpp @@ -42,7 +42,7 @@ struct TxResult std::optional ctid; std::optional closeTime; std::optional ledgerHash; - TxSearched searchedAll; + TxSearched searchedAll = TxSearched::unknown; }; struct TxArgs