Skip to content

Conversation

fanquake
Copy link
Member

@fanquake fanquake commented May 19, 2022

We currently use a mix of std::mem*( and mem*( throughout the codebase. Consolidate to std::mem*(.

Follows up to a comment in #24962:

Maybe switch to std::memmove, which comes with the documentation:

Also includes a change to std::vsnprintf and header changes required to perform compilation.

@DrahtBot
Copy link
Contributor

DrahtBot commented May 20, 2022

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #26177 (refactor / kernel: Move non-gArgs chainparams functionality to kernel by TheCharlatan)
  • #26153 (Reduce wasted pseudorandom bytes in ChaCha20 + various improvements by sipa)
  • #25903 (Use static member functions from class instead of instances by aureleoules)
  • #25830 (refactor: Replace m_params with chainman.GetParams() by aureleoules)
  • #25361 (BIP324: Cipher suite by dhruv)
  • #25152 (refactor: Split util/system into exception, shell, and fs-specific files by Empact)
  • #24994 (build: Build libbitcoinconsensus from its own convenience library by hebasto)
  • #23561 (BIP324: Handshake prerequisites by dhruv)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@aureleoules
Copy link
Contributor

I believe some were missed:

Git diff
diff --git a/src/addrdb.cpp b/src/addrdb.cpp
index 31f8eadf9..cd124d157 100644
--- a/src/addrdb.cpp
+++ b/src/addrdb.cpp
@@ -92,7 +92,7 @@ void DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
     unsigned char pchMsgTmp[4];
     verifier >> pchMsgTmp;
     // ... verify the network matches ours
-    if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {
+    if (std::memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {
         throw std::runtime_error{"Invalid network magic number"};
     }
 
diff --git a/src/base58.cpp b/src/base58.cpp
index 11c1ce739..de9a82d46 100644
--- a/src/base58.cpp
+++ b/src/base58.cpp
@@ -150,7 +150,7 @@ std::string EncodeBase58Check(Span<const unsigned char> input)
     }
     // re-calculate the checksum, ensure it matches the included 4-byte checksum
     uint256 hash = Hash(Span{vchRet}.first(vchRet.size() - 4));
-    if (memcmp(&hash, &vchRet[vchRet.size() - 4], 4) != 0) {
+    if (std::memcmp(&hash, &vchRet[vchRet.size() - 4], 4) != 0) {
         vchRet.clear();
         return false;
     }
diff --git a/src/net.cpp b/src/net.cpp
index 88f4cef5b..47ccede26 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -732,7 +732,7 @@ int V1TransportDeserializer::readHeader(Span<const uint8_t> msg_bytes)
     }
 
     // Check start string, network magic
-    if (memcmp(hdr.pchMessageStart, m_chain_params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
+    if (std::memcmp(hdr.pchMessageStart, m_chain_params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
         LogPrint(BCLog::NET, "Header error: Wrong MessageStart %s received, peer=%d\n", HexStr(hdr.pchMessageStart), m_node_id);
         return -1;
     }
@@ -793,7 +793,7 @@ CNetMessage V1TransportDeserializer::GetMessage(const std::chrono::microseconds
     RandAddEvent(ReadLE32(hash.begin()));
 
     // Check checksum and header message type string
-    if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) {
+    if (std::memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) {
         LogPrint(BCLog::NET, "Header error: Wrong checksum (%s, %u bytes), expected %s was %s, peer=%d\n",
                  SanitizeString(msg.m_type), msg.m_message_size,
                  HexStr(Span{hash}.first(CMessageHeader::CHECKSUM_SIZE)),
diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp
index 17ab226a3..88a90e256 100644
--- a/src/node/blockstorage.cpp
+++ b/src/node/blockstorage.cpp
@@ -768,7 +768,7 @@ bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, c
 
         filein >> blk_start >> blk_size;
 
-        if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
+        if (std::memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
             return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
                          HexStr(blk_start),
                          HexStr(message_start));
diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp
index c4d13d728..1cabf65ac 100644
--- a/src/script/interpreter.cpp
+++ b/src/script/interpreter.cpp
@@ -1877,7 +1877,7 @@ static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion,
             exec_script = CScript(script_bytes.begin(), script_bytes.end());
             uint256 hash_exec_script;
             CSHA256().Write(exec_script.data(), exec_script.size()).Finalize(hash_exec_script.begin());
-            if (memcmp(hash_exec_script.begin(), program.data(), 32)) {
+            if (std::memcmp(hash_exec_script.begin(), program.data(), 32)) {
                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
             }
             return ExecuteWitnessScript(stack, exec_script, flags, SigVersion::WITNESS_V0, checker, execdata, serror);
diff --git a/src/validation.cpp b/src/validation.cpp
index fefbe033e..b3fcba2cd 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -3548,7 +3548,7 @@ static bool ContextualCheckBlock(const CBlock& block, BlockValidationState& stat
                 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-nonce-size", strprintf("%s : invalid witness reserved value size", __func__));
             }
             CHash256().Write(hashWitness).Write(block.vtx[0]->vin[0].scriptWitness.stack[0]).Finalize(hashWitness);
-            if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
+            if (std::memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
                 return state.Invalid(BlockValidationResult::BLOCK_MUTATED, "bad-witness-merkle-match", strprintf("%s : witness merkle commitment mismatch", __func__));
             }
             fHaveWitness = true;
@@ -4294,7 +4294,7 @@ void CChainState::LoadExternalBlockFile(FILE* fileIn, FlatFilePos* dbp)
                 blkdat.FindByte(m_params.MessageStart()[0]);
                 nRewind = blkdat.GetPos() + 1;
                 blkdat >> buf;
-                if (memcmp(buf, m_params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) {
+                if (std::memcmp(buf, m_params.MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) {
                     continue;
                 }
                 // read size

@fanquake fanquake changed the title refactor: use std:: for mem*( funcs refactor: use std:: prefix for std lib funcs May 23, 2022
@fanquake fanquake force-pushed the use_std_variants branch from 1b7b070 to 1d2d121 Compare May 23, 2022 06:58
@fanquake
Copy link
Member Author

I believe some were missed:

Thanks. Have addressed more cases.

@fanquake fanquake force-pushed the use_std_variants branch 2 times, most recently from 14d5f20 to 7749a28 Compare May 23, 2022 09:09
Copy link
Contributor

@dunxen dunxen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 7749a28

@laanwj
Copy link
Member

laanwj commented May 26, 2022

No problem with this, I agree it's good to be consistent here, though not generally a fan of 'all-over-the-place' PRs.

I do think we need a way to enforce this to prevent reintroducing unqualified std functions, for example adapt one of the linters.

@Empact
Copy link
Contributor

Empact commented Jun 18, 2022

In the spirit of "Include what you use", we should also ensure we are including the appropriate headers for these functions, <cstring> for std::mem* and <cstdlib> for std::getenv.

Copy link
Contributor

@w0xlt w0xlt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strong ACK 7749a28

fanquake added 4 commits July 20, 2022 17:35
-BEGIN VERIFY SCRIPT-

sed -i -e "s/ memset(/ std::memset(/" $(git grep -l "memset(" -- ":(exclude)src/bench/nanobench.h" ":(exclude)src/secp256k1" ":(exclude)src/crc32c" ":(exclude)src/leveldb" ":(exclude)test/functional")
sed -i -e "s/string.h/cstring/" src/crypto/aes.cpp src/crypto/chacha20.cpp src/crypto/chacha_poly_aead.cpp src/crypto/hmac_sha256.cpp src/crypto/hmac_sha512.cpp
-END VERIFY SCRIPT-
-BEGIN VERIFY SCRIPT-

sed -i -e "s/ memcmp(/ std::memcmp(/" $(git grep -l "memcmp(" -- ":(exclude)src/secp256k1" ":(exclude)src/leveldb" src)
sed -i -e "s/(memcmp(/(std::memcmp(/" $(git grep -l "memcmp(" -- ":(exclude)src/secp256k1" ":(exclude)src/leveldb" ":(exclude)src/crypto/ctaes" src)
-END VERIFY SCRIPT-
-BEGIN VERIFY SCRIPT-

sed -i -e "s/ memcpy(/ std::memcpy(/" $(git grep -l "memcpy(" -- ":(exclude)src/secp256k1" ":(exclude)src/leveldb" src)
sed -i -e "s/string.h/cstring/" src/crypto/common.h

-END VERIFY SCRIPT-
@hebasto
Copy link
Member

hebasto commented Jul 20, 2022

Concept ACK.

@maflcko
Copy link
Member

maflcko commented Jul 20, 2022

Was #25172 (comment) addressed?

@fanquake
Copy link
Member Author

Was #25172 (comment) addressed?

Not yet, but I am going to address this via clang-tidy plugin, rather than a python linter. Although there a few steps before that will be available.

@fanquake
Copy link
Member Author

Looks like Clang is moving in the direction of adding warnings for unqualified std function usage, beginning with std::move and std::forward. Starting with LLVM 15 there will be an -Wunqualified-std-cast-call warning. See https://reviews.llvm.org/D119670.

Copy link
Member

@hebasto hebasto left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 8dd3c4a, I have reviewed the code and it looks OK, I agree it can be merged.

@maflcko
Copy link
Member

maflcko commented Aug 3, 2022

glozow removed the Waiting for author label 21 hours ago

Well, if we want the changes, I'd still prefer to enforce them. If we don't, then we could close this pull.

@DrahtBot
Copy link
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

Want to unsubscribe from rebase notifications on this pull request? Just convert this pull request to a "draft".

@fanquake fanquake closed this Dec 5, 2022
@fanquake fanquake deleted the use_std_variants branch September 11, 2023 09:36
@bitcoin bitcoin locked and limited conversation to collaborators Sep 10, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.