-
-
Notifications
You must be signed in to change notification settings - Fork 354
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
DRAFT
CMake Build System Support
#1504
base: master
Are you sure you want to change the base?
Conversation
* Required for CMake build system. * Leveldb abondands SSE support and depends on crc32c. * The crc32 library uses SSE if possible. * General build script improvement.
WalkthroughThe changes in this pull request involve extensive modifications across multiple files, primarily focusing on the configuration and build system for the LevelDB and CRC32C projects. Key updates include the introduction of new checks for system features, removal of LevelDB-related configurations, and enhancements to the Makefile and CMake configurations. Additionally, new source files and headers for CRC32C functionality are added, including implementations for checksum calculations and unit tests. The overall structure and organization of the code are improved for readability and maintainability, while also ensuring modern C++ practices are followed. Changes
Poem
Tip CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 18
🧹 Outside diff range and nitpick comments (43)
src/leveldb/README.md (2)
32-41
: Verify CMake minimum version requirementWhile the CMake build instructions are clear, they should specify the minimum required CMake version for compatibility.
Consider adding the minimum CMake version requirement before the build instructions:
This project supports [CMake](https://cmake.org/) out of the box. + Minimum required version: CMake 3.x.x + ### Build for POSIX🧰 Tools
🪛 Markdownlint (0.35.0)
34-34: Expected: h2; Actual: h3
Heading levels should only increment by one level at a time(MD001, heading-increment)
52-53
: Fix typo in Windows build instructionsThere's a duplicate word in the Windows build instructions.
- The default default will build for x86. + The default will build for x86.🧰 Tools
🪛 LanguageTool
[duplication] ~52-~52: Possible typo: you repeated a word
Context: ... cmake -G "Visual Studio 15" .. ``` The default default will build for x86. For 64-bit run: ``...(ENGLISH_WORD_REPEAT_RULE)
src/leveldb/CONTRIBUTING.md (1)
34-35
: Update style guide URL to use HTTPSThe style guide URL should use HTTPS for security.
- [the style guide](http://google.github.io/styleguide/cppguide.html) + [the style guide](https://google.github.io/styleguide/cppguide.html)🧰 Tools
🪛 LanguageTool
[style] ~34-~34: Consider using a different verb to strengthen your wording.
Context: ...your contribution contains code, please make sure that it follows [the style guide](http:...(MAKE_SURE_ENSURE)
[uncategorized] ~35-~35: A comma may be missing after the conjunctive/linking adverb ‘Otherwise’.
Context: ...le.github.io/styleguide/cppguide.html). Otherwise we will have to ask you to make changes...(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)
src/crc32c/src/crc32c_arm64.cc (1)
31-64
: Simplify macro definitions for better readability and maintenanceThe macros
CRC32C32BYTES
,CRC32C256BYTES
, andCRC32C1024BYTES
are complex and can be difficult to read and maintain. Consider refactoring them into inline functions or loops to improve code clarity.Example refactor:
// Replace macros with inline functions inline void CRC32C32Bytes(const uint8_t* P, int IND, uint32_t& crc0, uint32_t& crc1, uint32_t& crc2, uint32_t& crc3, uint64_t& d64) { std::memcpy(&d64, P + SEGMENTBYTES * 1 + IND * 8, sizeof(d64)); crc1 = __crc32cd(crc1, d64); std::memcpy(&d64, P + SEGMENTBYTES * 2 + IND * 8, sizeof(d64)); crc2 = __crc32cd(crc2, d64); std::memcpy(&d64, P + SEGMENTBYTES * 3 + IND * 8, sizeof(d64)); crc3 = __crc32cd(crc3, d64); std::memcpy(&d64, P + SEGMENTBYTES * 0 + IND * 8, sizeof(d64)); crc0 = __crc32cd(crc0, d64); } inline void CRC32C256Bytes(const uint8_t* P, int IND, uint32_t& crc0, uint32_t& crc1, uint32_t& crc2, uint32_t& crc3, uint64_t& d64) { for (int i = 0; i < 8; ++i) { CRC32C32Bytes(P, IND * 8 + i, crc0, crc1, crc2, crc3, d64); } } inline void CRC32C1024Bytes(const uint8_t*& P, uint32_t& crc0, uint32_t& crc1, uint32_t& crc2, uint32_t& crc3, uint64_t& d64) { for (int i = 0; i < 4; ++i) { CRC32C256Bytes(P, i, crc0, crc1, crc2, crc3, d64); } P += 4 * SEGMENTBYTES; }src/leveldb/db/db_impl.h (1)
186-187
: Avoid potential deadlocks by minimizing mutex-held timeIn the
BuildBatchGroup
function and within the writers' deque handling, ensure that holding the mutex for extended periods doesn't lead to performance bottlenecks or deadlocks, especially when writing large batches.Consider refactoring to release the mutex during long-running operations if safe, or restructuring the code to minimize mutex contention.
src/crc32c/src/crc32c_sse42.cc (1)
179-179
: Typo in comment: Correct 'Proccess' to 'Process'There's a minor typo in the comment; 'Proccess' should be corrected to 'Process' for clarity.
src/leveldb/.gitignore (1)
1-8
: LGTM with a minor suggestion for CMake-specific patternsThe patterns look good and follow standard conventions. Consider adding these CMake-specific patterns:
+# CMake specific +CMakeCache.txt +CMakeFiles/ +cmake_install.cmake +compile_commands.jsonsrc/crc32c/src/crc32c_internal.h (1)
15-16
: Consider enhancing function documentationWhile the current documentation is clear, consider adding:
src/crc32c/src/crc32c_read_le_unittest.cc (1)
16-22
: Consider adding edge cases to ReadUint32LE testWhile the basic test case is good, consider adding tests for:
- Maximum value (0xFFFFFFFF)
- Minimum value (0x00000000)
- Alternating bit patterns (0xAAAAAAAA, 0x55555555)
src/crc32c/src/crc32c_round_up.h (1)
13-16
: Enhance function documentationConsider adding:
- @tparam N description with valid range/constraints
- @param descriptions
- @return value details
- @throws information if applicable
- Example usage in comments
Also applies to: 22-25
src/crc32c/src/crc32c_sse42.h (1)
26-27
: Consider adding parameter documentationThe function declaration would benefit from brief documentation of its parameters and return value.
// SSE4.2-accelerated implementation in crc32c_sse42.cc +// Parameters: +// crc: Initial CRC value +// data: Pointer to data buffer +// count: Length of data in bytes +// Returns: Updated CRC32C value uint32_t ExtendSse42(uint32_t crc, const uint8_t* data, size_t count);src/crc32c/src/crc32c_sse42_check.h (1)
26-30
: Consider caching the SSE4.2 detection resultThe
CanUseSse42()
function performs CPU feature detection on every call. Since CPU features don't change at runtime, consider caching the result.namespace crc32c { +namespace { +bool cached_can_use_sse42 = false; +bool cached_can_use_sse42_initialized = false; +} // namespace inline bool CanUseSse42() { + if (cached_can_use_sse42_initialized) { + return cached_can_use_sse42; + } + +#if defined(_MSC_VER) int cpu_info[4]; __cpuid(cpu_info, 1); - return (cpu_info[2] & (1 << 20)) != 0; + cached_can_use_sse42 = (cpu_info[2] & (1 << 20)) != 0; +#else + unsigned int eax, ebx, ecx, edx; + cached_can_use_sse42 = __get_cpuid(1, &eax, &ebx, &ecx, &edx) && + ((ecx & (1 << 20)) != 0); +#endif + cached_can_use_sse42_initialized = true; + return cached_can_use_sse42; }Also applies to: 39-42
src/leveldb/db/log_writer.h (2)
40-40
: Document EmitPhysicalRecord parameters and error conditionsThe private method would benefit from documentation describing its parameters, return conditions, and any error cases.
+ // Writes a physical record to the underlying file. + // Parameters: + // type: The type of record to write + // ptr: Pointer to the data to write + // length: Length of the data in bytes + // Returns: Status::OK() on success, otherwise an error status Status EmitPhysicalRecord(RecordType type, const char* ptr, size_t length);
42-43
: Consider initializing block_offset_ in the class definitionThe member variable
block_offset_
should be initialized in the class definition to ensure it's properly initialized regardless of which constructor is used.WritableFile* dest_; - int block_offset_; // Current offset in block + int block_offset_ = 0; // Current offset in blocksrc/crc32c/src/crc32c_prefetch.h (1)
28-42
: Consider adding documentation for performance implicationsThe prefetch implementation is well-structured, but it would be beneficial to document:
- The expected performance impact
- The recommended usage patterns
- The cache line size assumptions
src/leveldb/db/leveldbutil.cc (1)
16-19
: Consider buffering stdout writesThe current implementation writes directly to stdout for each Append call, which could be inefficient for frequent small writes. Consider implementing buffering to improve performance.
src/leveldb/db/builder.cc (3)
59-60
: Fix indentation in NewIterator callThe second parameter of NewIterator is over-indented.
- Iterator* it = table_cache->NewIterator(ReadOptions(), meta->number, - meta->file_size); + Iterator* it = table_cache->NewIterator(ReadOptions(), meta->number, + meta->file_size);
40-43
: Consider adding error details to assertionThe assertion could be more informative by including the actual file size.
- assert(meta->file_size > 0); + assert(meta->file_size > 0 && "Built table file size must be positive");
Line range hint
17-55
: Consider using RAII for resource managementThe current implementation manually manages resources (file and builder). Consider using smart pointers or RAII wrappers to prevent resource leaks in case of exceptions.
Example approach:
std::unique_ptr<WritableFile> file; s = env->NewWritableFile(fname, &file); if (!s.ok()) return s; std::unique_ptr<TableBuilder> builder(new TableBuilder(options, file.get()));src/crc32c/src/crc32c_capi_unittest.c (1)
13-66
: Consider enhancing the test framework structureWhile the tests are functional, consider these improvements for better maintainability:
- Isolate test cases into separate functions
- Add test case counting
- Enhance error messages with expected vs actual values
Example refactored structure:
static int test_count = 0; static int failed_count = 0; static void assert_crc32c(const char* test_name, uint32_t expected, const uint8_t* data, size_t length) { test_count++; uint32_t actual = crc32c_value(data, length); if (expected != actual) { printf("%s failed: expected 0x%08x, got 0x%08x\n", test_name, expected, actual); failed_count++; return 1; } return 0; } int main() { // Test cases here using assert_crc32c printf("%d tests run, %d failed\n", test_count, failed_count); return failed_count > 0 ? 1 : 0; }src/Makefile.qttest.include (1)
51-53
: Consider organizing library dependencies by categoryThe library dependencies list is quite long and could benefit from better organization.
Consider grouping related libraries in variables:
# Core libraries CORE_LIBS = $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) # Crypto libraries CRYPTO_LIBS = $(LIBZEROCOIN) $(LIBBITCOIN_CRYPTO) $(LIBFIRO_SIGMA) $(LIBLELANTUS) $(LIBSPARK) # External dependencies EXTERNAL_LIBS = $(BOOST_LIBS) $(QT_LIBS) $(SSL_LIBS) qt_test_test_bitcoin_qt_LDADD += $(CORE_LIBS) $(CRYPTO_LIBS) $(EXTERNAL_LIBS)src/crc32c/include/crc32c/crc32c.h (1)
30-35
: Add parameter validation documentationThe C API functions should document their behavior with null pointers and zero counts. Consider adding:
- Preconditions for input parameters
- Return value documentation
- Error handling behavior
src/leveldb/db/memtable.h (2)
77-77
: Enhance destructor documentationThe comment could be more explicit about the reference counting contract:
- ~MemTable(); // Private since only Unref() should be used to delete it + ~MemTable(); // Private: Object lifetime is managed through reference counting. + // Use Unref() instead of direct deletion.
56-57
: Consider documenting thread safety guaranteesThe
Add
method should document its thread safety properties, especially given the reference-counted nature of the class.src/Makefile.crc32c.include (1)
11-17
: Consider adding version checks for compiler features.While the preprocessor flags are comprehensive, consider adding version checks for compiler features to ensure compatibility across different compiler versions.
CRC32C_CPPFLAGS_INT += -DHAVE_BUILTIN_PREFETCH=@HAVE_BUILTIN_PREFETCH@ CRC32C_CPPFLAGS_INT += -DHAVE_MM_PREFETCH=@HAVE_MM_PREFETCH@ +CRC32C_CPPFLAGS_INT += -DHAVE_COMPILER_VERSION=@COMPILER_VERSION@
src/leveldb/db/autocompact_test.cc (2)
84-85
: Consider improving readability with named constantsThe magic number
100
in the assertion could be replaced with a named constant to improve code maintainability and readability.+ static const int kMaxCompactionAttempts = 100; for (int read = 0; true; read++) { - ASSERT_LT(read, 100) << "Taking too long to compact"; + ASSERT_LT(read, kMaxCompactionAttempts) << + "Database failed to compact after " << kMaxCompactionAttempts << " attempts";
92-93
: Consider using constants for size conversionsThe magic number
1048576.0
(1MB in bytes) appears multiple times. Consider extracting it to a named constant for better maintainability.+ static const double kMegabyte = 1048576.0; fprintf(stderr, "iter %3d => %7.3f MB [other %7.3f MB]\n", read + 1, - size / 1048576.0, Size(Key(n), Key(kCount)) / 1048576.0); + size / kMegabyte, Size(Key(n), Key(kCount)) / kMegabyte);src/crc32c/src/crc32c_benchmark.cc (1)
45-47
: Consider documenting benchmark parameters and using named constantsThe block size range parameters could be more self-documenting with named constants and comments explaining the chosen values.
+ // Minimum block size: 256 bytes (typical small message size) + // Maximum block size: 16MB (covers typical large file operations) + static const int kMinBlockSize = 256; + static const int kMaxBlockSize = 16777216; + static const int kBlockSizeMultiplier = 16; BENCHMARK_REGISTER_F(CRC32CBenchmark, Public) - ->RangeMultiplier(16) - ->Range(256, 16777216); // Block size. + ->RangeMultiplier(kBlockSizeMultiplier) + ->Range(kMinBlockSize, kMaxBlockSize);src/crc32c/src/crc32c_extend_unittests.h (1)
65-84
: Consider adding performance regression testsWhile the current tests thoroughly verify correctness, consider adding performance regression tests to ensure optimal implementation across different architectures.
Example test case:
TYPED_TEST_P(ExtendTest, PerformanceBenchmark) { constexpr size_t kBufferSize = 1024 * 1024; // 1MB std::vector<uint8_t> buffer(kBufferSize); for (size_t i = 0; i < kBufferSize; i++) buffer[i] = static_cast<uint8_t>(i & 0xFF); auto start = std::chrono::high_resolution_clock::now(); uint32_t crc = TypeParam::Extend(0, buffer.data(), buffer.size()); auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start); // Ensure processing speed is above threshold (adjust based on architecture) EXPECT_GT(static_cast<double>(kBufferSize) / duration.count(), 100.0); // MB/s EXPECT_NE(crc, 0); // Prevent optimization }Also applies to: 86-102
src/crc32c/src/crc32c_unittest.cc (2)
59-79
: Consider using unsigned char for safer type handlingWhile the implementation works, casting to
char
might lead to implementation-defined behavior sincechar
signedness is platform-dependent. Consider usingunsigned char
for consistent behavior across platforms.- buf[i] = static_cast<char>(i); + buf[i] = static_cast<unsigned char>(i);
81-100
: Consider using const for loop indicesThe implementation is correct, but consider using
const
for loop indices to prevent accidental modifications.- for (size_t i = 0; i < 32; ++i) + for (const size_t i = 0; i < 32; ++i)src/leveldb/db/filename_test.cc (1)
47-68
: Consider grouping error cases by typeWhile the error cases are comprehensive, consider organizing them into groups with comments explaining the type of error being tested (e.g., invalid format, invalid characters, overflow cases).
src/leveldb/db/dbformat_test.cc (1)
47-59
: Consider using a test fixture for common test dataThe test data initialization in
InternalKey_EncodeDecode
could be moved to a test fixture to avoid duplication and improve maintainability.+class FormatTest : public testing::Test { + protected: + const char* keys_[4] = {"", "k", "hello", "longggggggggggggggggggggg"}; + const uint64_t seq_[13] = { + 1, 2, 3, + (1ull << 8) - 1, 1ull << 8, (1ull << 8) + 1, + (1ull << 16) - 1, 1ull << 16, (1ull << 16) + 1, + (1ull << 32) - 1, 1ull << 32, (1ull << 32) + 1 + }; +};src/leveldb/db/memtable.cc (1)
86-88
: Consider using std::size_t for size calculationsFor consistency with other size calculations in the code, consider using std::size_t for encoded_len calculation.
- const size_t encoded_len = VarintLength(internal_key_size) + - internal_key_size + VarintLength(val_size) + - val_size; + const std::size_t encoded_len = + static_cast<std::size_t>(VarintLength(internal_key_size)) + + internal_key_size + + static_cast<std::size_t>(VarintLength(val_size)) + + val_size;src/leveldb/CMakeLists.txt (3)
19-25
: Address the TODO comment for Windows UNICODE configuration.The TODO indicates that UNICODE configuration for Windows needs to be made configurable. This should be addressed to ensure proper Unicode support across different Windows configurations.
Would you like me to help implement configurable UNICODE support for Windows or create a GitHub issue to track this task?
52-74
: Document error handling strategy with exceptions disabled.While disabling exceptions and RTTI is a valid optimization, it's important to document the error handling strategy that should be used instead. Consider adding comments or documentation explaining the preferred error handling approach.
282-359
: Document test limitations for shared libraries.Some tests are only built when
BUILD_SHARED_LIBS
is OFF. Consider documenting why these tests are excluded for shared libraries or implement equivalent tests for shared library builds.src/crc32c/CMakeLists.txt (2)
141-144
: Address TODO for MSVC ARM CRC32C support.The TODO indicates missing ARM CRC32C support for MSVC. This should be addressed when Visual Studio adds support for ARM CRC32C instructions.
Would you like me to create a GitHub issue to track this task and update it when MSVC adds ARM CRC32C support?
268-273
: Consider updating minimum CMake version requirement.The TODO indicates waiting for CMake 3.9 to move TARGET_OBJECTS expressions. Since the leveldb CMakeLists.txt already requires 3.9, consider updating this file's minimum version to match and implementing the suggested change.
src/leveldb/db/c.cc (2)
260-274
: Improve readability of progress reporting logicThe nested if-else chain for progress reporting thresholds could be simplified.
Consider using a lookup table or helper function:
+struct ProgressThreshold { + int min_report; + int increment; +}; + +static const ProgressThreshold PROGRESS_THRESHOLDS[] = { + {0, 100}, + {1000, 500}, + {5000, 1000}, + {10000, 5000}, + {50000, 10000}, + {100000, 50000}, + {500000, 100000} +}; + if (done_ >= next_report_) { - if (next_report_ < 1000) - next_report_ += 100; - else if (next_report_ < 5000) - next_report_ += 500; - // ... more conditions - else - next_report_ += 100000; + for (const auto& threshold : PROGRESS_THRESHOLDS) { + if (next_report_ < threshold.min_report) { + next_report_ += threshold.increment; + break; + } + }
Line range hint
339-365
: Enhance WriteBatch iteration safetyThe WriteBatch iteration implementation could benefit from RAII principles for the handler.
Consider using a unique_ptr for automatic cleanup:
void leveldb_writebatch_iterate(const leveldb_writebatch_t* b, void* state, void (*put)(void*, const char* k, size_t klen, const char* v, size_t vlen), void (*deleted)(void*, const char* k, size_t klen)) { - class H : public WriteBatch::Handler { + class HandlerRAII : public WriteBatch::Handler { public: + ~HandlerRAII() override = default; void* state_; void (*put_)(void*, const char* k, size_t klen, const char* v, size_t vlen); void (*deleted_)(void*, const char* k, size_t klen); void Put(const Slice& key, const Slice& value) override { (*put_)(state_, key.data(), key.size(), value.data(), value.size()); } void Delete(const Slice& key) override { (*deleted_)(state_, key.data(), key.size()); } }; - H handler; - handler.state_ = state; - handler.put_ = put; - handler.deleted_ = deleted; - b->rep.Iterate(&handler); + auto handler = std::make_unique<HandlerRAII>(); + handler->state_ = state; + handler->put_ = put; + handler->deleted_ = deleted; + b->rep.Iterate(handler.get()); }src/leveldb/benchmarks/db_bench.cc (1)
231-244
: Consider using a more maintainable progression structureThe current implementation uses hard-coded values for progress reporting. Consider using a more maintainable approach.
Consider this alternative:
- if (next_report_ < 1000) - next_report_ += 100; - else if (next_report_ < 5000) - next_report_ += 500; - else if (next_report_ < 10000) - next_report_ += 1000; - else if (next_report_ < 50000) - next_report_ += 5000; - else if (next_report_ < 100000) - next_report_ += 10000; - else if (next_report_ < 500000) - next_report_ += 50000; - else - next_report_ += 100000; + const struct ProgressStep { + int threshold; + int increment; + } steps[] = { + {1000, 100}, + {5000, 500}, + {10000, 1000}, + {50000, 5000}, + {100000, 10000}, + {500000, 50000}, + {INT_MAX, 100000} + }; + for (const auto& step : steps) { + if (next_report_ < step.threshold) { + next_report_ += step.increment; + break; + } + }src/crc32c/src/crc32c_portable.cc (1)
253-285
: Consider replacing macros with inline functions for better maintainabilityThe use of macros like
STEP1
,STEP4
,STEP16
, andSTEP4W
can make debugging and maintenance more challenging. Replacing them withinline
functions can improve type safety, enable better debugging, and enhance code readability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (4)
src/crc32c/.appveyor.yml
is excluded by!**/*.yml
src/crc32c/.travis.yml
is excluded by!**/*.yml
src/leveldb/.appveyor.yml
is excluded by!**/*.yml
src/leveldb/.travis.yml
is excluded by!**/*.yml
📒 Files selected for processing (82)
configure.ac
(3 hunks)src/Makefile.am
(5 hunks)src/Makefile.bench.include
(1 hunks)src/Makefile.crc32c.include
(1 hunks)src/Makefile.leveldb.include
(1 hunks)src/Makefile.qt.include
(1 hunks)src/Makefile.qttest.include
(1 hunks)src/Makefile.test.include
(1 hunks)src/crc32c/.clang-format
(1 hunks)src/crc32c/.clang_complete
(1 hunks)src/crc32c/.gitignore
(1 hunks)src/crc32c/.ycm_extra_conf.py
(1 hunks)src/crc32c/AUTHORS
(1 hunks)src/crc32c/CMakeLists.txt
(1 hunks)src/crc32c/CONTRIBUTING.md
(1 hunks)src/crc32c/Crc32cConfig.cmake.in
(1 hunks)src/crc32c/LICENSE
(1 hunks)src/crc32c/README.md
(1 hunks)src/crc32c/include/crc32c/crc32c.h
(1 hunks)src/crc32c/src/crc32c.cc
(1 hunks)src/crc32c/src/crc32c_arm64.cc
(1 hunks)src/crc32c/src/crc32c_arm64.h
(1 hunks)src/crc32c/src/crc32c_arm64_check.h
(1 hunks)src/crc32c/src/crc32c_arm64_unittest.cc
(1 hunks)src/crc32c/src/crc32c_benchmark.cc
(1 hunks)src/crc32c/src/crc32c_capi_unittest.c
(1 hunks)src/crc32c/src/crc32c_config.h.in
(1 hunks)src/crc32c/src/crc32c_extend_unittests.h
(1 hunks)src/crc32c/src/crc32c_internal.h
(1 hunks)src/crc32c/src/crc32c_portable.cc
(1 hunks)src/crc32c/src/crc32c_portable_unittest.cc
(1 hunks)src/crc32c/src/crc32c_prefetch.h
(1 hunks)src/crc32c/src/crc32c_prefetch_unittest.cc
(1 hunks)src/crc32c/src/crc32c_read_le.h
(1 hunks)src/crc32c/src/crc32c_read_le_unittest.cc
(1 hunks)src/crc32c/src/crc32c_round_up.h
(1 hunks)src/crc32c/src/crc32c_round_up_unittest.cc
(1 hunks)src/crc32c/src/crc32c_sse42.cc
(1 hunks)src/crc32c/src/crc32c_sse42.h
(1 hunks)src/crc32c/src/crc32c_sse42_check.h
(1 hunks)src/crc32c/src/crc32c_sse42_unittest.cc
(1 hunks)src/crc32c/src/crc32c_test_main.cc
(1 hunks)src/crc32c/src/crc32c_unittest.cc
(1 hunks)src/leveldb/.clang-format
(1 hunks)src/leveldb/.gitignore
(1 hunks)src/leveldb/CMakeLists.txt
(1 hunks)src/leveldb/CONTRIBUTING.md
(1 hunks)src/leveldb/Makefile
(0 hunks)src/leveldb/README.md
(4 hunks)src/leveldb/WINDOWS.md
(0 hunks)src/leveldb/benchmarks/db_bench.cc
(25 hunks)src/leveldb/benchmarks/db_bench_sqlite3.cc
(21 hunks)src/leveldb/benchmarks/db_bench_tree_db.cc
(15 hunks)src/leveldb/build_detect_platform
(0 hunks)src/leveldb/cmake/leveldbConfig.cmake
(1 hunks)src/leveldb/db/autocompact_test.cc
(4 hunks)src/leveldb/db/builder.cc
(4 hunks)src/leveldb/db/builder.h
(1 hunks)src/leveldb/db/c.cc
(18 hunks)src/leveldb/db/c_test.c
(6 hunks)src/leveldb/db/corruption_test.cc
(10 hunks)src/leveldb/db/db_impl.cc
(55 hunks)src/leveldb/db/db_impl.h
(6 hunks)src/leveldb/db/db_iter.cc
(8 hunks)src/leveldb/db/db_iter.h
(2 hunks)src/leveldb/db/db_test.cc
(67 hunks)src/leveldb/db/dbformat.cc
(5 hunks)src/leveldb/db/dbformat.h
(10 hunks)src/leveldb/db/dbformat_test.cc
(5 hunks)src/leveldb/db/dumpfile.cc
(5 hunks)src/leveldb/db/fault_injection_test.cc
(17 hunks)src/leveldb/db/filename.cc
(3 hunks)src/leveldb/db/filename.h
(2 hunks)src/leveldb/db/filename_test.cc
(4 hunks)src/leveldb/db/leveldbutil.cc
(4 hunks)src/leveldb/db/log_reader.cc
(5 hunks)src/leveldb/db/log_reader.h
(3 hunks)src/leveldb/db/log_test.cc
(14 hunks)src/leveldb/db/log_writer.cc
(5 hunks)src/leveldb/db/log_writer.h
(2 hunks)src/leveldb/db/memtable.cc
(4 hunks)src/leveldb/db/memtable.h
(4 hunks)
⛔ Files not processed due to max files limit (55)
- src/leveldb/db/recovery_test.cc
- src/leveldb/db/repair.cc
- src/leveldb/db/skiplist.h
- src/leveldb/db/skiplist_test.cc
- src/leveldb/db/snapshot.h
- src/leveldb/db/table_cache.cc
- src/leveldb/db/table_cache.h
- src/leveldb/db/version_edit.cc
- src/leveldb/db/version_edit.h
- src/leveldb/db/version_edit_test.cc
- src/leveldb/db/version_set.cc
- src/leveldb/db/version_set.h
- src/leveldb/db/version_set_test.cc
- src/leveldb/db/write_batch.cc
- src/leveldb/db/write_batch_internal.h
- src/leveldb/db/write_batch_test.cc
- src/leveldb/doc/benchmark.html
- src/leveldb/doc/impl.md
- src/leveldb/doc/index.md
- src/leveldb/helpers/memenv/memenv.cc
- src/leveldb/helpers/memenv/memenv.h
- src/leveldb/helpers/memenv/memenv_test.cc
- src/leveldb/include/leveldb/c.h
- src/leveldb/include/leveldb/cache.h
- src/leveldb/include/leveldb/comparator.h
- src/leveldb/include/leveldb/db.h
- src/leveldb/include/leveldb/dumpfile.h
- src/leveldb/include/leveldb/env.h
- src/leveldb/include/leveldb/export.h
- src/leveldb/include/leveldb/filter_policy.h
- src/leveldb/include/leveldb/iterator.h
- src/leveldb/include/leveldb/options.h
- src/leveldb/include/leveldb/slice.h
- src/leveldb/include/leveldb/status.h
- src/leveldb/include/leveldb/table.h
- src/leveldb/include/leveldb/table_builder.h
- src/leveldb/include/leveldb/write_batch.h
- src/leveldb/issues/issue178_test.cc
- src/leveldb/issues/issue200_test.cc
- src/leveldb/issues/issue320_test.cc
- src/leveldb/port/README.md
- src/leveldb/port/atomic_pointer.h
- src/leveldb/port/port.h
- src/leveldb/port/port_config.h.in
- src/leveldb/port/port_example.h
- src/leveldb/port/port_posix.cc
- src/leveldb/port/port_posix.h
- src/leveldb/port/port_posix_sse.cc
- src/leveldb/port/port_stdcxx.h
- src/leveldb/port/port_win.cc
- src/leveldb/port/port_win.h
- src/leveldb/port/thread_annotations.h
- src/leveldb/port/win/stdint.h
- src/leveldb/table/block.cc
- src/leveldb/table/block.h
💤 Files with no reviewable changes (3)
- src/leveldb/Makefile
- src/leveldb/WINDOWS.md
- src/leveldb/build_detect_platform
✅ Files skipped from review due to trivial changes (14)
- src/crc32c/.clang-format
- src/crc32c/LICENSE
- src/leveldb/cmake/leveldbConfig.cmake
- src/crc32c/Crc32cConfig.cmake.in
- src/crc32c/.clang_complete
- src/leveldb/.clang-format
- src/crc32c/.gitignore
- src/crc32c/AUTHORS
- src/crc32c/src/crc32c_prefetch_unittest.cc
- src/leveldb/db/builder.h
- src/leveldb/db/db_iter.h
- src/crc32c/CONTRIBUTING.md
- src/crc32c/README.md
- src/crc32c/src/crc32c_config.h.in
🧰 Additional context used
🪛 cppcheck (2.10-2)
src/crc32c/src/crc32c_sse42_unittest.cc
[error] 23-23: syntax error
(syntaxError)
src/crc32c/src/crc32c_arm64_unittest.cc
[error] 23-23: syntax error
(syntaxError)
src/crc32c/src/crc32c_read_le_unittest.cc
[error] 24-24: syntax error
(syntaxError)
src/leveldb/db/autocompact_test.cc
[error] 106-106: syntax error
(syntaxError)
src/leveldb/db/log_test.cc
[error] 263-263: syntax error
(syntaxError)
src/crc32c/src/crc32c_unittest.cc
[error] 23-23: syntax error
(syntaxError)
src/crc32c/src/crc32c_round_up_unittest.cc
[error] 58-58: syntax error
(syntaxError)
src/leveldb/db/dbformat_test.cc
[error] 46-46: syntax error
(syntaxError)
src/crc32c/src/crc32c_benchmark.cc
[error] 39-39: There is an unknown macro here somewhere. Configuration is required. If BENCHMARK_DEFINE_F is a macro then please configure it.
(unknownMacro)
src/leveldb/db/corruption_test.cc
[error] 192-192: syntax error
(syntaxError)
src/leveldb/db/db_impl.cc
[error] 1058-1058: Member variable 'version' is initialized by itself.
(selfInitialization)
[error] 1058-1058: Member variable 'mem' is initialized by itself.
(selfInitialization)
[error] 1058-1058: Member variable 'imm' is initialized by itself.
(selfInitialization)
src/leveldb/benchmarks/db_bench.cc
[error] 295-295: Member variable 'total' is initialized by itself.
(selfInitialization)
src/leveldb/db/db_test.cc
[error] 541-541: syntax error
(syntaxError)
🪛 Ruff (0.8.0)
src/crc32c/.ycm_extra_conf.py
121-121: Use a context manager for opening files
(SIM115)
🪛 Markdownlint (0.35.0)
src/leveldb/README.md
6-6: null
Bare URL used
(MD034, no-bare-urls)
6-6: null
Bare URL used
(MD034, no-bare-urls)
34-34: Expected: h2; Actual: h3
Heading levels should only increment by one level at a time
(MD001, heading-increment)
26-26: Expected: 0; Actual: 2
Unordered list indentation
(MD007, ul-indent)
27-27: Expected: 0; Actual: 2
Unordered list indentation
(MD007, ul-indent)
28-28: Expected: 0; Actual: 2
Unordered list indentation
(MD007, ul-indent)
93-93: null
Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🪛 LanguageTool
src/leveldb/README.md
[misspelling] ~27-~27: This word is normally spelled as one.
Context: ...es. * Only a single process (possibly multi-threaded) can access a particular database at a ...
(EN_COMPOUNDS_MULTI_THREADED)
[duplication] ~52-~52: Possible typo: you repeated a word
Context: ... cmake -G "Visual Studio 15" .. ``` The default default will build for x86. For 64-bit run: ``...
(ENGLISH_WORD_REPEAT_RULE)
[style] ~79-~79: As an alternative to the over-used intensifier ‘very’, consider replacing this phrase.
Context: ...IX (for Linux and macOS) or Windows. Very small changes will sometimes be accepted, but...
(EN_WEAK_ADJECTIVE)
[grammar] ~80-~80: Did you mean “exception to”?
Context: ...cepted, but consider that more of an exception than the rule. 2. Stable API. We strive...
(EXCEPTION_PREPOSITION_THE_RULE)
[typographical] ~91-~91: Consider adding a comma here.
Context: ...sure your changes are properly formatted please run: ``` clang-format -i --style...
(PLEASE_COMMA)
[style] ~194-~194: ‘without warning’ might be wordy. Consider a shorter alternative.
Context: ...ge. Those internal APIs may be changed without warning. Guide to header files: * **include/l...
(EN_WORDINESS_PREMIUM_WITHOUT_WARNING)
src/leveldb/CONTRIBUTING.md
[style] ~34-~34: Consider using a different verb to strengthen your wording.
Context: ...your contribution contains code, please make sure that it follows [the style guide](http:...
(MAKE_SURE_ENSURE)
[uncategorized] ~35-~35: A comma may be missing after the conjunctive/linking adverb ‘Otherwise’.
Context: ...le.github.io/styleguide/cppguide.html). Otherwise we will have to ask you to make changes...
(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)
🔇 Additional comments (95)
src/leveldb/README.md (2)
4-4
: LGTM: Build status badge addition
The AppVeyor build status badge addition is appropriate given the new Windows platform support.
192-225
: Verify header path updates
The header paths have been updated to include the 'leveldb/' prefix. This change needs verification across the codebase to ensure consistency.
✅ Verification successful
Based on the output, I can generate the final response since I have enough information to verify the concern:
All leveldb headers exist at the documented paths
All the header files mentioned in the README.md are present at their expected locations under src/leveldb/include/leveldb/
. The script verified that each of the following headers exists:
- db.h
- options.h
- comparator.h
- iterator.h
- write_batch.h
- slice.h
- status.h
- env.h
- table.h
- table_builder.h
The documentation accurately reflects the header file paths and no updates are needed.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that all include directives use the new path format
# Check for any old-style includes without 'leveldb/' prefix
rg -g '*.{cpp,cc,h,hpp}' '#include.*".*\.h"' | grep -v 'leveldb/'
# Check if all listed header files exist in the new location
for header in db.h options.h comparator.h iterator.h write_batch.h slice.h status.h env.h table.h table_builder.h; do
if [ ! -f "src/leveldb/include/leveldb/$header" ]; then
echo "Missing header: $header"
fi
done
Length of output: 67342
🧰 Tools
🪛 LanguageTool
[style] ~194-~194: ‘without warning’ might be wordy. Consider a shorter alternative.
Context: ...ge. Those internal APIs may be changed without warning. Guide to header files: * **include/l...
(EN_WORDINESS_PREMIUM_WITHOUT_WARNING)
src/crc32c/src/crc32c.cc (1)
30-37
: 🛠️ Refactor suggestion
Consistent use of extern "C"
linkage in headers
The functions crc32c_extend
and crc32c_value
are declared with extern "C"
linkage in this source file. Ensure that the corresponding declarations in the header file crc32c/crc32c.h
also use extern "C"
to maintain linkage consistency when included in C++ projects and to prevent name mangling issues.
Run the following script to verify the declarations in the header file:
✅ Verification successful
Header file correctly declares functions with extern "C"
linkage
The header file src/crc32c/include/crc32c/crc32c.h
already properly declares both functions with extern "C"
linkage when included in C++ projects. The declarations are correctly wrapped in:
#if defined(__cplusplus)
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that the header file declares functions with correct linkage.
# Expected: Functions are declared with `extern "C"` linkage in C++.
grep -A 5 -E 'extern "C"' crc32c/crc32c.h
Length of output: 92
Script:
#!/bin/bash
# Let's first find the header file location
fd -e h -e hpp crc32c
Length of output: 388
Script:
#!/bin/bash
# Now let's check the content of the main header file
cat src/crc32c/include/crc32c/crc32c.h
Length of output: 2325
src/Makefile.leveldb.include (2)
145-147
: Conditional inclusion of platform-specific sources
The use of if TARGET_WINDOWS
and else
for including env_windows.cc
and env_posix.cc
should ensure that the correct environment file is compiled based on the target platform.
5-12
: Ensure proper linking of libtool archives
The change from .a
to .la
for LIBLEVELDB_INT
and LIBMEMENV_INT
means you're now using libtool archives. Ensure that your build system supports libtool and that all the dependencies are properly linked, especially when building for different platforms like Windows.
Run the following script to verify that the libtool archives are correctly generated and linked:
✅ Verification successful
Let me gather more information about the build system and libtool configuration.
Let me check the leveldb build configuration and libtool usage.
Based on the analysis of the Makefile.leveldb.include and build configuration, I can now provide a final response:
Libtool archive configuration is properly set up for leveldb
The change from .a
to .la
is correctly configured in the build system:
- The library is explicitly set to be built as a static library with
-static
flags in both CXXFLAGS and LDFLAGS - Proper libtool configuration is present in the build system through LT_INIT
- The library is correctly declared as a non-installed library with
noinst_LTLIBRARIES
- All necessary source files and dependencies are properly listed
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that libtool archives are correctly built and linked.
# Clean previous builds
make clean
# Build the project
make
# Check for the existence of .la files
if [ -f leveldb/libleveldb.la ] && [ -f leveldb/libmemenv.la ]; then
echo "Libtool archives generated successfully."
else
echo "Error: Libtool archives not found."
fi
Length of output: 323
Script:
#!/bin/bash
# Check for libtool configuration and dependencies
fd -e am -e in Makefile | xargs cat
# Check for any libtool-related configurations
rg -i "libtool|\.la" -A 3 -B 3
# Look for leveldb build configurations
fd leveldb.*\.mk$ | xargs cat
Length of output: 65680
Script:
#!/bin/bash
# Check leveldb build configuration
cat src/Makefile.leveldb.include
# Look for leveldb library references
rg "libleveldb" -A 2 -B 2
# Check for libtool configuration in build system
fd -e m4 -e ac . build-aux/m4/ | xargs cat
Length of output: 67029
src/crc32c/src/crc32c_portable_unittest.cc (2)
12-16
: LGTM! Clean test traits implementation.
The PortableTestTraits
implementation follows good testing practices by providing a clean abstraction for testing the portable CRC32C implementation.
18-18
: Verify test coverage for portable implementation
The test suite instantiation looks good. Let's verify the test coverage.
✅ Verification successful
Let me gather more information about the test coverage by examining the test files and implementation.
Test coverage for portable implementation is comprehensive
The portable implementation is thoroughly tested through the ExtendTest
test suite which includes:
- Standard test vectors from RFC3720 section B.4
- Concatenation tests with "hello world" string
- Extensive buffer slicing tests with various alignments
- Large buffer tests with 2048-byte input
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for additional test cases in the base test suite
rg -l "TEST[_P].*\bExtendTest\b" src/crc32c/src/
# Look for any untested public methods in the portable implementation
ast-grep --pattern 'uint32_t Extend.*\(.*\).*{.*}' src/crc32c/src/
Length of output: 317
Script:
#!/bin/bash
# Check the content of the base test suite file
cat src/crc32c/src/crc32c_extend_unittests.h
# Check the portable implementation file
cat src/crc32c/src/crc32c_portable.cc
# Check the portable test file
cat src/crc32c/src/crc32c_portable_unittest.cc
Length of output: 24205
src/crc32c/src/crc32c_test_main.cc (2)
15-22
: LGTM! Clean test main implementation.
The implementation follows Google Test best practices:
- Proper initialization of Google Test
- Conditional Google Logging setup
- Standard test execution pattern
5-7
: Verify CMake configuration consistency
The config header inclusion looks correct. Let's verify the CMake configuration ensures consistent defines.
✅ Verification successful
CMake configuration for CRC32C_HAVE_CONFIG_H is properly set up
The verification confirms that the configuration is consistent:
- The CMake build system correctly sets
CRC32C_HAVE_CONFIG_H
compile definition for all targets - The config header template (
crc32c_config.h.in
) is properly configured and installed to the correct location - The include guard in the generated header matches the conditional include in the test file
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check CMake configuration for CRC32C_HAVE_CONFIG_H
rg -l "CRC32C_HAVE_CONFIG_H" -g "CMakeLists.txt" src/crc32c/
# Check for config header generation
rg -l "configure_file.*crc32c_config.h" -g "CMakeLists.txt" src/crc32c/
Length of output: 156
Script:
#!/bin/bash
# Let's examine the CMake configuration more thoroughly
cat src/crc32c/CMakeLists.txt
Length of output: 14698
Script:
#!/bin/bash
# Let's check the config header template
cat src/crc32c/src/crc32c_config.h.in
Length of output: 1411
src/crc32c/src/crc32c_arm64.h (2)
1-16
: LGTM! Well-structured header with proper guards and includes.
The header follows best practices with:
- Clear copyright notice
- Proper include guards
- Necessary standard includes
- Conditional configuration include
17-24
: LGTM! Clean architecture-specific implementation.
Good practices observed:
- Proper use of HAVE_ARM64_CRC32C conditional compilation
- Clean namespace usage
- Clear function declaration with standard parameter types
src/crc32c/src/crc32c_arm64_unittest.cc (2)
14-18
: LGTM! Clean test traits implementation.
The test traits structure is well-designed:
- Simple and focused implementation
- Clear static method signature
- Direct delegation to architecture-specific function
20-20
: LGTM! Proper test suite instantiation.
Good use of Google Test's typed test suite functionality to reuse test cases across different implementations.
src/crc32c/src/crc32c_sse42_unittest.cc (2)
12-12
: LGTM! Comprehensive architecture detection.
Good use of conditional compilation to ensure the code only runs on supported platforms:
- Checks for SSE42 support
- Verifies x64/x86_64 architecture
14-20
: LGTM! Consistent test implementation.
The implementation follows the same pattern as the ARM64 tests:
- Clean test traits structure
- Direct delegation to SSE42-specific function
- Proper test suite instantiation
src/crc32c/src/crc32c_internal.h (2)
5-6
: LGTM: Header guard follows best practices
The header guard CRC32C_CRC32C_INTERNAL_H_
follows the recommended naming convention and provides proper include guard protection.
18-19
: LGTM: Well-defined constant with clear documentation
The constant definition is correct and the documentation clearly explains its purpose for pre- and post-conditioning CRCs.
src/crc32c/src/crc32c_read_le_unittest.cc (1)
24-30
: LGTM: Proper alignment check and test implementation
The test correctly:
- Uses alignas(8) for proper memory alignment
- Verifies alignment using RoundUp
- Tests a complex 64-bit value
🧰 Tools
🪛 cppcheck (2.10-2)
[error] 24-24: syntax error
(syntaxError)
src/crc32c/src/crc32c_round_up.h (2)
17-20
: LGTM: Robust implementation with compile-time safety checks
The implementation correctly:
- Uses static_assert to ensure N is a power of two
- Implements efficient bit manipulation for rounding
- Uses constexpr for compile-time evaluation
26-30
: Verify pointer arithmetic safety
While the implementation is correct, ensure that:
- All callers properly validate input pointers
- The reinterpret_cast operations are safe in the target environment
✅ Verification successful
Let me analyze the usage of RoundUp to make a final determination.
From the search results, I can see that RoundUp is used in several contexts:
-
In production code (crc32c_sse42.cc, crc32c_portable.cc, leveldb/util/crc32c.cc):
- Used after bounds checking (if (x <= e))
- Used in controlled pointer arithmetic within while loops
- Always used with proper alignment checks
-
In test code (crc32c_round_up_unittest.cc):
- Extensive testing of boundary conditions
- Tests with null pointers (zero_ptr)
- Tests with various alignments and pointer values
- Validation of power-of-two requirements
-
In read_le_unittest.cc:
- Used with alignment assertions
Based on this analysis, I can now provide the final response:
RoundUp implementation and usage verified as safe
The pointer arithmetic in RoundUp is properly safeguarded:
- All production code usages include bounds checking before dereferencing
- Alignment requirements are enforced via static_assert
- Extensive test coverage validates behavior with null pointers and boundary conditions
- Used consistently for memory alignment in controlled contexts
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for all usages of RoundUp to verify proper pointer validation
rg -A 3 "RoundUp<[0-9]+>\(" --type cpp
# Look for potential nullptr checks before RoundUp calls
ast-grep --pattern 'if ($pointer == nullptr) { $$$ }'
Length of output: 6617
src/crc32c/src/crc32c_sse42.h (2)
17-22
: Well-documented architectural decision
Excellent documentation explaining why the hardware-accelerated implementation is limited to 64-bit builds. This kind of reasoning in comments helps maintain institutional knowledge.
22-22
: Verify SSE4.2 detection across different build environments
The conditional compilation looks correct but should be verified across different build environments to ensure consistent behavior.
Also applies to: 31-31
✅ Verification successful
Let me analyze the SSE4.2 detection implementation further to ensure it's comprehensive.
SSE4.2 detection implementation is robust and well-handled
The verification shows that SSE4.2 detection is implemented comprehensively with:
- Proper compile-time checks through CMake configuration (
HAVE_SSE42
) - Architecture-specific checks (
_M_X64
or__x86_64__
) - Runtime CPU feature detection via
CanUseSse42()
usingcpuid
intrinsics - Graceful fallback to portable implementation when SSE4.2 is unavailable
The implementation follows best practices by:
- Separating SSE4.2 code into dedicated files for proper compiler flag handling
- Using platform-specific intrinsics (
_cpuid
for MSVC,__get_cpuid
for others) - Implementing proper runtime feature detection before using SSE4.2 instructions
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check how SSE4.2 detection is handled across the codebase
# Look for other SSE4.2-related checks
rg -l "HAVE_SSE42|_M_X64|__x86_64__"
# Check for any CMake-related SSE4.2 detection
fd -e cmake -e txt -x rg "SSE4.2|sse4.2|SSE42|sse42" {}
Length of output: 1508
Script:
#!/bin/bash
# Check the actual implementation of SSE4.2 detection and configuration
cat src/crc32c/src/crc32c_config.h.in
cat src/crc32c/src/crc32c_sse42_check.h
# Check how the SSE4.2 feature is used in the implementation
cat src/crc32c/src/crc32c_sse42.cc
# Look for any runtime checks for SSE4.2 support
rg "SSE4.2|sse4.2|SSE42|sse42" -A 5 src/crc32c/src/crc32c.cc
Length of output: 14086
src/crc32c/src/crc32c_sse42_check.h (1)
21-23
: Verify error handling for CPU feature detection
The code should handle potential failures in CPU feature detection intrinsics.
Also applies to: 34-36
src/leveldb/db/leveldbutil.cc (1)
20-23
: LGTM: Clean method implementations with proper override specifiers
The override specifiers are correctly added, improving code clarity and compile-time error detection.
src/Makefile.qttest.include (1)
51-51
: Verify LevelDB SSE42 support in CMake configuration
The removal of LIBLEVELDB_SSE42
suggests that SSE42 optimization for LevelDB needs to be handled in the new CMake configuration.
✅ Verification successful
Let me gather more information about the SSE42 configuration in the codebase.
Let me check the main CMake configuration for LevelDB.
Based on the gathered information, I can now provide the final response:
SSE4.2 support is properly handled in CMake configuration
The removal of LIBLEVELDB_SSE42
from the Makefile is not a concern as the SSE4.2 optimization is now properly managed in the CMake build system:
- LevelDB's CMake configuration inherits CRC32C's SSE4.2 support
- CRC32C library has dedicated SSE4.2 optimizations that are:
- Conditionally compiled with proper compiler flags (
-msse4.2
or/arch:AVX
) - Runtime-checked for CPU support
- Built as a separate object to avoid unsupported instruction issues
- Conditionally compiled with proper compiler flags (
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if SSE42 support is configured in CMake files
rg -l "SSE4_2|SSE42" --type cmake
# Check for LevelDB CMake configuration
fd -e cmake -e txt -g "CMakeLists.txt" | xargs rg "leveldb"
Length of output: 4790
Script:
#!/bin/bash
# Check the content of crc32c CMake file that mentions SSE4_2
cat src/crc32c/CMakeLists.txt
# Check if there are any other references to SSE4.2 in the codebase
rg -i "sse4.2|sse42" -A 3 -B 3
# Check how LevelDB is integrated in the main CMake configuration
cat CMakeLists.txt | rg -A 5 -B 5 "leveldb"
Length of output: 33110
Script:
#!/bin/bash
# Check the main CMake configuration
fd -e cmake -g "CMakeLists.txt" -d 1 | xargs cat
# Check if there are any SSE4.2 related flags in the main build system
rg -i "sse|simd" build-aux/m4
Length of output: 4182
src/crc32c/include/crc32c/crc32c.h (2)
1-89
: Well-structured implementation with good API design
The implementation demonstrates:
- Clean separation between C and C++ APIs
- Proper const-correctness
- Good use of modern C++ features
- Appropriate header guards and include management
53-60
: Consider adding bounds checking
The Crc32c
functions accept raw pointers without length validation. Consider adding:
- Debug assertions for null pointer checks
- Documentation about pointer lifetime requirements
src/leveldb/db/memtable.h (1)
26-27
: Good: Preventing accidental copies improves memory safety
The explicit deletion of copy operations is a good practice that:
- Prevents accidental copying of memory-intensive objects
- Makes the reference-counting ownership model more explicit
src/leveldb/db/filename.h (1)
35-80
: LGTM! Consistent cleanup of linkage specifications.
The systematic removal of extern
keywords from function declarations is a good cleanup. Since these functions are declared within a header file that's already part of the library's public interface, the extern
keyword is redundant. This change aligns well with modern C++ practices while maintaining the same functionality.
src/leveldb/db/log_writer.cc (4)
23-25
: LGTM! Improved constructor initialization style.
The constructor now uses the initialization list style, which is more efficient and follows modern C++ best practices.
32-32
: LGTM! Defaulted destructor.
Using = default
for the destructor is cleaner than an empty implementation.
50-50
: LGTM! Added compile-time safety check.
The static assertion ensures that the hard-coded value matches the expected header size at compile time.
82-106
: LGTM! Improved parameter naming in EmitPhysicalRecord.
The parameter rename from n
to length
improves code readability by making the parameter's purpose more explicit. The change is consistently applied throughout the method.
src/Makefile.crc32c.include (3)
38-43
: LGTM! Well-documented static library configuration.
The explicit specification of -static
in both CXXFLAGS and LDFLAGS is well-justified by the comment explaining Windows compatibility requirements.
18-34
: LGTM! Comprehensive platform-specific optimizations.
The conditional compilation blocks for SSE42, ARM CRC, and endianness are well-structured and provide proper platform-specific optimizations.
45-58
: Verify source file organization.
The source files are well-organized, but let's verify that all necessary files are included and accessible.
✅ Verification successful
Source files are correctly organized and all files are present
All source files listed in crc32c_libcrc32c_la_SOURCES
exist in the correct locations under src/crc32c/
:
- Header files are properly placed in
src/crc32c/include/crc32c/
andsrc/crc32c/src/
- Implementation files (.cc) are correctly placed in
src/crc32c/src/
- All files referenced in the Makefile are present and accounted for
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify the existence and organization of CRC32C source files
echo "Checking CRC32C source files..."
fd -t f . crc32c/src crc32c/include
Length of output: 269
Script:
#!/bin/bash
# Let's first check if the crc32c directory exists and its structure
echo "Checking repository structure..."
fd crc32c
# Also check if these files might be in a different location
echo -e "\nChecking for specific CRC32C files anywhere in the repo..."
fd -t f "crc32c\.h$|crc32c\.cc$|crc32c_portable\.cc$"
Length of output: 1494
src/leveldb/db/autocompact_test.cc (1)
46-50
: LGTM: Improved encapsulation
Moving member variables to the private section enhances encapsulation and follows good OOP practices.
src/crc32c/src/crc32c_benchmark.cc (2)
25-37
: LGTM: Well-structured benchmark fixture
The benchmark fixture is well-designed with proper setup and member organization.
61-65
: LGTM: Proper platform-specific error handling
Good practice to check for ARM CRC32C instruction availability and skip with an informative error message.
src/crc32c/src/crc32c_round_up_unittest.cc (1)
14-56
: LGTM: Comprehensive integer rounding tests
Excellent test coverage including edge cases and boundary conditions for integer rounding.
src/leveldb/db/log_reader.h (3)
Line range hint 35-42
: LGTM: Improved comment style consistency
Updated terminology from "non-NULL" to "non-null" aligns with modern C++ style.
46-47
: LGTM: Explicit deletion of copy operations
Good practice to explicitly delete copy operations for RAII classes that manage resources.
88-106
: LGTM: Well-structured member variables
Clear organization of member variables with const qualifiers where appropriate.
src/crc32c/src/crc32c_extend_unittests.h (2)
23-53
: LGTM: Comprehensive standard test vectors
Good coverage using test vectors from RFC3720, including edge cases like all-zeros and all-ones buffers.
55-63
: LGTM: Validates CRC32C concatenation property
Important test case verifying that CRC32C extension works correctly when concatenating buffers.
src/leveldb/db/filename.cc (4)
17-18
: LGTM: Improved function signature
Removal of extern keyword and consistent parameter naming.
20-25
: LGTM: Clear implementation with proper type casting
Good use of static_cast for number conversion.
28-40
: LGTM: Consistent parameter naming
Consistent use of 'dbname' parameter name across related functions improves code clarity.
78-80
: LGTM: Consistent parameter naming in ParseFileName
Maintains consistency with other function signatures in the file.
src/crc32c/src/crc32c_unittest.cc (2)
15-45
: Well-structured test implementation with good coverage!
The test cases are well-documented and cover important scenarios from RFC 3720, including edge cases with different buffer patterns.
🧰 Tools
🪛 cppcheck (2.10-2)
[error] 23-23: syntax error
(syntaxError)
49-53
: Clean trait implementation for test extensibility!
The ApiTestTraits struct provides a good abstraction for testing the Extend functionality.
src/leveldb/db/filename_test.cc (2)
27-37
: Comprehensive test coverage for filename parsing!
The test cases cover all file types and include important edge cases like maximum uint64 values.
116-126
: Well-integrated info log filename tests!
The new test cases follow the established pattern and provide good coverage for info log filename handling.
src/leveldb/db/dbformat.cc (3)
28-41
: Good modernization of string formatting!
The switch to std::ostringstream
is a good improvement, making the code more idiomatic C++ and eliminating potential buffer overflow issues.
Line range hint 66-78
: Improved code formatting enhances readability!
The formatting changes to the PutFixed64 calls make the code more readable while maintaining the same functionality.
100-100
: Good simplification of the Name method!
The single-line implementation is appropriate for this simple method.
src/leveldb/db/dbformat_test.cc (2)
68-72
: Good addition: Test case for empty key decoding
This test case improves coverage by verifying the behavior when decoding an empty internal key.
115-119
: Good addition: Debug string test cases
These test cases enhance coverage by verifying the string representation of keys, including edge cases with special characters.
Also applies to: 121-126
src/leveldb/db/memtable.cc (2)
48-53
: Good modernization: Explicit special member functions
The explicit deletion of copy operations and defaulted destructor follows modern C++ best practices.
55-62
: Good addition: Override specifiers
The addition of override specifiers improves code clarity and helps catch interface mismatches at compile-time.
src/leveldb/db/dumpfile.cc (2)
149-150
: LGTM! Good modernization of pointer initialization.
The change from NULL
to nullptr
aligns with modern C++ best practices, improving type safety and code clarity.
220-225
: LGTM! Improved switch case formatting.
The formatting changes enhance code readability while maintaining the same logical flow.
src/leveldb/db/dbformat.h (3)
8-10
: LGTM! Better header organization.
Replacing <stdio.h>
with specific C++ headers (<cstddef>
, <cstdint>
, <string>
) improves code organization and follows modern C++ practices.
144-147
: LGTM! Improved error handling in DecodeFrom.
The method now returns a boolean indicating success/failure of the decode operation, which is a better practice for error handling.
190-191
: LGTM! Properly prevented object copying.
Explicitly deleting copy constructor and assignment operator prevents accidental copying of LookupKey objects, which is good practice for resource-managing classes.
src/leveldb/db/log_reader.cc (2)
179-179
: LGTM! Enhanced error reporting.
Good improvements:
- Using
nullptr
instead ofNULL
follows modern C++ practices - Including the file name in corruption status provides better context for debugging
Also applies to: 183-186
98-99
: Verify the corruption reporting logic change.
The condition for reporting corruption has been inverted. Please verify that this change maintains the intended behavior for handling partial records.
Also applies to: 114-115
✅ Verification successful
The corruption reporting logic change is correct
The inverted condition if (!scratch->empty())
is the correct implementation, as verified by:
- The context shows this is handling a specific bug where empty
kFirstType
records could appear at block boundaries - The test cases in
log_test.cc
explicitly verify this behavior withMatchError("partial record without end")
- The same pattern is consistently used in two locations (with messages "partial record without end(1)" and "partial record without end(2)")
The corruption should only be reported when there's partial data in the scratch buffer (i.e., when it's not empty), which is exactly what the current condition !scratch->empty()
checks for.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for similar corruption reporting patterns in tests
rg -A 5 "ReportCorruption.*partial record" "src/leveldb/**/*test*.cc"
Length of output: 136
Script:
#!/bin/bash
# Search for similar corruption reporting patterns in the entire codebase
rg -A 5 "ReportCorruption.*partial record"
# Look for test cases or implementations related to log reader corruption
ast-grep --pattern 'ReportCorruption($_)'
# Search for the log reader implementation context
rg -B 5 -A 5 "partial record without end"
Length of output: 4039
src/leveldb/db/corruption_test.cc (1)
25-28
: LGTM! Good modernization of C++ code
The changes improve the code quality by:
- Using nullptr instead of NULL
- Better initialization in constructor
- Improved file operations with proper error handling
Also applies to: 39-40, 45-45, 129-130, 230-231
src/leveldb/db/c_test.c (3)
Line range hint 123-143
: LGTM! Good type modernization.
The change from unsigned char
to uint8_t
improves type clarity and is more idiomatic in modern C/C++.
229-234
: LGTM! Enhanced test coverage.
Good addition of test cases for write batch operations, covering delete operations and batch append functionality with proper cleanup.
Line range hint 238-251
: LGTM! Improved progress reporting intervals.
The changes provide better granularity in progress reporting, with smaller intervals for early progress and larger intervals for later stages.
src/leveldb/db/fault_injection_test.cc (2)
272-276
: LGTM! Good modernization of loop construct.
The change to a range-based for loop with improved error handling makes the code more idiomatic and maintainable.
345-352
: LGTM! Enhanced error handling.
Good improvements in error handling with proper use of std::move
and clear status management.
src/leveldb/benchmarks/db_bench_tree_db.cc (2)
399-410
: LGTM! Improved database configuration clarity.
Good organization of options configuration with explicit map size tuning and better readability.
513-516
: LGTM! Modernized pointer handling.
Good update to use nullptr
and improved path handling with clearer string construction.
src/leveldb/CMakeLists.txt (2)
5-18
: LGTM! Well-structured CMake configuration.
The configuration properly sets up:
- CMake minimum version requirement
- Project version (synced with db.h)
- C/C++ standard settings with appropriate decay behavior
27-51
: LGTM! Comprehensive feature detection setup.
The configuration includes:
- Well-defined build options
- Proper system feature detection
- Correct endianness checking
src/leveldb/db/log_test.cc (2)
41-45
: LGTM! Improved constructor formatting.
The constructor initialization is well-formatted and maintains the original functionality.
161-225
: LGTM! Modern C++ best practices applied.
Good use of:
override
keyword for virtual functions- Proper access specifiers
- Consistent formatting
src/leveldb/db/c.cc (2)
7-9
: LGTM: Modern C++ includes
The addition of <cstdint>
and <cstdlib>
headers is appropriate for modern C++ type safety and standard library functions.
Line range hint 146-156
: Verify error handling robustness
The error handling function has been updated to use nullptr
, but there might be potential memory leaks if strdup
fails.
Consider adding memory allocation failure checks:
static bool SaveError(char** errptr, const Status& s) {
assert(errptr != nullptr);
if (s.ok()) {
return false;
} else if (*errptr == nullptr) {
- *errptr = strdup(s.ToString().c_str());
+ char* new_error = strdup(s.ToString().c_str());
+ if (new_error == nullptr) {
+ // Handle allocation failure
+ return false;
+ }
+ *errptr = new_error;
} else {
free(*errptr);
- *errptr = strdup(s.ToString().c_str());
+ char* new_error = strdup(s.ToString().c_str());
+ if (new_error == nullptr) {
+ *errptr = nullptr;
+ return false;
+ }
+ *errptr = new_error;
}
return true;
}
src/Makefile.qt.include (1)
521-524
: Verify dependency changes impact
The removal of LIBLEVELDB_SSE42
from linking needs verification to ensure it doesn't break SSE4.2 optimizations.
✅ Verification successful
SSE4.2 optimizations are properly maintained despite LIBLEVELDB_SSE42 removal
The removal of LIBLEVELDB_SSE42
from linking does not impact SSE4.2 optimizations. The codebase handles SSE4.2 support through:
- Conditional compilation with
ENABLE_SSE42
flag - Separate compilation of SSE4.2-optimized code in
libcrc32c_sse42.la
- Proper linking of the SSE4.2-optimized library when SSE4.2 is enabled
The CRC32C implementation maintains SSE4.2 optimizations independently of the removed variable, ensuring optimal performance when SSE4.2 is available.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for SSE4.2 usage in the codebase
rg -l "SSE4\.2|sse4\.2|__SSE4_2__"
Length of output: 194
Script:
#!/bin/bash
# Check if LIBLEVELDB_SSE42 is still defined and used elsewhere
rg "LIBLEVELDB_SSE42" -A 3
# Check LevelDB's build configuration for SSE4.2
cat src/crc32c/CMakeLists.txt
# Check if there are alternative SSE4.2 optimizations in place
rg -l "CRC32C_USE_SSE42|HAVE_SSE42"
Length of output: 15048
Script:
#!/bin/bash
# Check the Makefile.crc32c.include to understand how SSE4.2 is handled in the build system
cat src/Makefile.crc32c.include
# Check if there are any other Makefile changes related to SSE4.2
rg "SSE4\.2|sse4\.2" src/Makefile*
Length of output: 3266
src/leveldb/benchmarks/db_bench_sqlite3.cc (1)
705-708
: LGTM: Proper fallback path handling
The fallback path for database location is well-implemented with proper null checks and path construction.
src/Makefile.am (4)
351-351
: LGTM: Addition of LevelDB compilation flags
The addition of $(LEVELDB_CPPFLAGS)
to libbitcoin_server_a_CPPFLAGS
is correct for proper LevelDB integration.
826-826
: LGTM: Memory environment library linkage
Adding $(LIBMEMENV)
to firo_cli_LDADD
is appropriate for memory environment support.
881-881
: LGTM: CRC32C cleanup targets
Addition of CRC32C-related cleanup targets ensures proper cleanup of generated files.
935-935
: LGTM: Modular build system organization
Including Makefile.crc32c.include
maintains good build system modularity.
src/leveldb/benchmarks/db_bench.cc (2)
281-282
: LGTM: Thread safety annotations
Good use of GUARDED_BY(mu)
annotations for thread-safe member variables:
- cv
- total
- num_initialized
- num_done
- start
Also applies to: 290-292
112-112
: LGTM: Modern C++ initialization patterns
Good modernization of code:
- Replaced NULL with nullptr
- Used member initializer lists
- Consistent initialization patterns
Also applies to: 117-117, 398-407
configure.ac (1)
1072-1207
: New system feature checks are properly implemented
The addition of checks for randomness gathering methods and file synchronization features enhances the build system's portability and configurability across different platforms.
src/leveldb/db/db_test.cc (2)
44-58
: Proper use of thread annotations for atomic operations
Adding LOCKS_EXCLUDED(mu_)
annotations to the AtomicCounter
methods improves thread safety by clearly indicating locking behavior and preventing potential concurrency issues.
1498-1505
: Verify the portability of fflush(nullptr)
usage
Using fflush(nullptr)
may not be portable across all platforms or standard-compliant in all environments. Consider checking whether passing a nullptr
to fflush
is supported on all target systems and, if necessary, use fflush(NULL)
or explicitly specify the streams to flush.
src/leveldb/db/db_iter.cc (2)
59-60
: Good practice by deleting copy constructor and assignment operator
Deleting the copy constructor and copy assignment operator prevents unintended copying of DBIter
instances, which is essential for classes managing resources like pointers or file handles.
63-84
: Use of override
specifier enhances code clarity
Adding the override
specifier to virtual method overrides improves code readability and helps catch errors where the base class method signature has changed, ensuring that the derived class methods are correctly overriding base class methods.
src/Makefile.test.include (1)
218-218
: Verify the order of libraries in LDADD
When adding $(BACKTRACE_LIB)
and $(BOOST_LIBS)
to test_test_bitcoin_LDADD
, ensure that the order of libraries satisfies all linker dependencies. Incorrect ordering can lead to linker errors or missing symbols during the build process.
uint32_t Extend(uint32_t crc, const uint8_t* data, size_t count) { | ||
#if HAVE_SSE42 && (defined(_M_X64) || defined(__x86_64__)) | ||
static bool can_use_sse42 = CanUseSse42(); | ||
if (can_use_sse42) return ExtendSse42(crc, data, count); | ||
#elif HAVE_ARM64_CRC32C | ||
static bool can_use_arm64_crc32 = CanUseArm64Crc32(); | ||
if (can_use_arm64_crc32) return ExtendArm64(crc, data, count); | ||
#endif // HAVE_SSE42 && (defined(_M_X64) || defined(__x86_64__)) | ||
|
||
return ExtendPortable(crc, data, count); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure thread-safe initialization of static local variables
The use of static
local variables can_use_sse42
and can_use_arm64_crc32
within the Extend
function might lead to thread safety issues in environments that do not guarantee thread-safe initialization of local static variables prior to C++11. Since the code includes headers like <cstdint>
, it suggests usage of C++11 or later. However, to ensure compatibility and thread safety across different compilers and standards, consider initializing these variables in a thread-safe manner or moving them to a scope where initialization is guaranteed to be thread-safe.
Apply this diff to address the potential thread safety issue:
uint32_t Extend(uint32_t crc, const uint8_t* data, size_t count) {
-#if HAVE_SSE42 && (defined(_M_X64) || defined(__x86_64__))
- static bool can_use_sse42 = CanUseSse42();
- if (can_use_sse42) return ExtendSse42(crc, data, count);
-#elif HAVE_ARM64_CRC32C
- static bool can_use_arm64_crc32 = CanUseArm64Crc32();
- if (can_use_arm64_crc32) return ExtendArm64(crc, data, count);
#endif // HAVE_SSE42 && (defined(_M_X64) || defined(__x86_64__))
+ // Initialize static flags in a thread-safe manner at program start-up.
+ static const bool can_use_sse42 = CanUseSse42();
+ static const bool can_use_arm64_crc32 = CanUseArm64Crc32();
+ if (can_use_sse42) {
+ return ExtendSse42(crc, data, count);
+ } else if (can_use_arm64_crc32) {
+ return ExtendArm64(crc, data, count);
+ }
Committable suggestion skipped: line range outside the PR's diff.
inline bool CanUseArm64Crc32() { | ||
#if defined (__linux__) && (HAVE_STRONG_GETAUXVAL || HAVE_WEAK_GETAUXVAL) | ||
// From 'arch/arm64/include/uapi/asm/hwcap.h' in Linux kernel source code. | ||
constexpr unsigned long kHWCAP_PMULL = 1 << 4; | ||
constexpr unsigned long kHWCAP_CRC32 = 1 << 7; | ||
unsigned long hwcap = | ||
#if HAVE_STRONG_GETAUXVAL | ||
// Some compilers warn on (&getauxval != nullptr) in the block below. | ||
getauxval(AT_HWCAP); | ||
#elif HAVE_WEAK_GETAUXVAL | ||
(&getauxval != nullptr) ? getauxval(AT_HWCAP) : 0; | ||
#else | ||
#error This is supposed to be nested inside a check for HAVE_*_GETAUXVAL. | ||
#endif // HAVE_STRONG_GETAUXVAL | ||
return (hwcap & (kHWCAP_PMULL | kHWCAP_CRC32)) == | ||
(kHWCAP_PMULL | kHWCAP_CRC32); | ||
#elif defined(__APPLE__) | ||
int val = 0; | ||
size_t len = sizeof(val); | ||
return sysctlbyname("hw.optional.armv8_crc32", &val, &len, nullptr, 0) == 0 | ||
&& val != 0; | ||
#else | ||
return false; | ||
#endif // HAVE_STRONG_GETAUXVAL || HAVE_WEAK_GETAUXVAL | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handle potential null pointer dereference for getauxval
In the CanUseArm64Crc32
function, when getauxval
is a weak symbol (i.e., may be nullptr
), there is a potential null pointer dereference if getauxval
is not available at runtime. The check (&getauxval != nullptr)
prevents calling a null function pointer but might not be sufficient on some platforms or compilers.
Apply this diff to ensure safe usage:
#elif HAVE_WEAK_GETAUXVAL
- (&getauxval != nullptr) ? getauxval(AT_HWCAP) : 0;
+ unsigned long hwcap = 0;
+ if (&getauxval != nullptr) {
+ hwcap = getauxval(AT_HWCAP);
+ }
+ else {
+ // getauxval not available; cannot determine hardware capabilities
+ return false;
+ }
This change ensures that if getauxval
is not available, the function safely returns false
without attempting to use a null function pointer.
Committable suggestion skipped: line range outside the PR's diff.
std::memcpy(&d64, data, sizeof(d64)); | ||
crc = __crc32cd(crc3, d64); | ||
data += sizeof(uint64_t); | ||
crc ^= __crc32cd(0, t2); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential out-of-bounds access in memory copy
At line 95, std::memcpy(&d64, data, sizeof(d64));
is used after processing 1024 bytes chunks. Ensure that there are at least 8 bytes remaining in data
to avoid out-of-bounds memory access. If less than 8 bytes remain, this could read beyond the buffer.
Apply this diff to add a bounds check:
+ if (length >= sizeof(uint64_t)) {
std::memcpy(&d64, data, sizeof(d64));
crc = __crc32cd(crc3, d64);
data += sizeof(uint64_t);
+ length -= sizeof(uint64_t);
+ } else {
+ // Handle remaining bytes safely
+ while (length > 0) {
+ crc = __crc32cb(crc, *data);
+ data++;
+ length--;
+ }
+ }
Committable suggestion skipped: line range outside the PR's diff.
std::atomic<bool> shutting_down_; | ||
port::CondVar background_work_finished_signal_ GUARDED_BY(mutex_); | ||
MemTable* mem_; | ||
MemTable* imm_; // Memtable being compacted | ||
port::AtomicPointer has_imm_; // So bg thread can detect non-NULL imm_ | ||
MemTable* imm_ GUARDED_BY(mutex_); // Memtable being compacted | ||
std::atomic<bool> has_imm_; // So bg thread can detect non-null imm_ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Possible data race with has_imm_
atomic variable
The variable has_imm_
is declared as std::atomic<bool>
, but is also annotated with GUARDED_BY(mutex_)
. Using atomic variables with mutex annotations can be confusing and may lead to incorrect assumptions about thread safety. Since has_imm_
is an atomic, access to it doesn't need to be protected by the mutex.
Consider removing the GUARDED_BY(mutex_)
annotation if has_imm_
is intended to be accessed atomically without the mutex. Alternatively, if all accesses are under the mutex, you may not need it to be atomic.
IterState(port::Mutex* mutex, MemTable* mem, MemTable* imm, Version* version) | ||
: mu(mutex), version(version), mem(mem), imm(imm) {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid self-initialization by renaming constructor parameters
In the IterState
constructor, the parameters version
, mem
, and imm
shadow the member variables of the same names, leading to self-initialization and potential issues.
Apply this diff to rename the constructor parameters and resolve the shadowing:
- IterState(port::Mutex* mutex, MemTable* mem, MemTable* imm, Version* version)
- : mu(mutex), version(version), mem(mem), imm(imm) {}
+ IterState(port::Mutex* mutex, MemTable* mem_ptr, MemTable* imm_ptr, Version* version_ptr)
+ : mu(mutex), version(version_ptr), mem(mem_ptr), imm(imm_ptr) {}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
IterState(port::Mutex* mutex, MemTable* mem, MemTable* imm, Version* version) | |
: mu(mutex), version(version), mem(mem), imm(imm) {} | |
IterState(port::Mutex* mutex, MemTable* mem_ptr, MemTable* imm_ptr, Version* version_ptr) | |
: mu(mutex), version(version_ptr), mem(mem_ptr), imm(imm_ptr) {} |
🧰 Tools
🪛 cppcheck (2.10-2)
[error] 1058-1058: Member variable 'version' is initialized by itself.
(selfInitialization)
[error] 1058-1058: Member variable 'mem' is initialized by itself.
(selfInitialization)
[error] 1058-1058: Member variable 'imm' is initialized by itself.
(selfInitialization)
TEST(CRC32CTest, Crc32cStdStringView) { | ||
uint8_t buf[32]; | ||
std::string_view view(reinterpret_cast<const char*>(buf), sizeof(buf)); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider safer type casting for string_view creation
Using reinterpret_cast
with raw buffer pointers can be unsafe. Consider using static_cast<const char*>
after ensuring proper alignment and type safety.
- std::string_view view(reinterpret_cast<const char*>(buf), sizeof(buf));
+ std::string_view view(static_cast<const char*>(static_cast<const void*>(buf)), sizeof(buf));
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
TEST(CRC32CTest, Crc32cStdStringView) { | |
uint8_t buf[32]; | |
std::string_view view(reinterpret_cast<const char*>(buf), sizeof(buf)); | |
TEST(CRC32CTest, Crc32cStdStringView) { | |
uint8_t buf[32]; | |
std::string_view view(static_cast<const char*>(static_cast<const void*>(buf)), sizeof(buf)); | |
clang_complete_path = FindNearest('.clang_complete', file_path, build_root) | ||
if clang_complete_path is None: | ||
return None | ||
clang_complete_flags = open(clang_complete_path, 'r').read().splitlines() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use context manager for file operations
Using a context manager ensures proper file handling and resource cleanup.
- clang_complete_flags = open(clang_complete_path, 'r').read().splitlines()
+ with open(clang_complete_path, 'r') as f:
+ clang_complete_flags = f.read().splitlines()
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
clang_complete_flags = open(clang_complete_path, 'r').read().splitlines() | |
with open(clang_complete_path, 'r') as f: | |
clang_complete_flags = f.read().splitlines() |
🧰 Tools
🪛 Ruff (0.8.0)
121-121: Use a context manager for opening files
(SIM115)
def FindNearest(target, path, build_root): | ||
"""Looks for a file with a specific name closest to a project path. | ||
|
||
This is similar to the logic used by a version-control system (like git) to | ||
find its configuration directory (.git) based on the current directory when a | ||
command is invoked. | ||
|
||
Args: | ||
target: The file name to search for. | ||
path: The directory where the search starts. The search will explore the | ||
given directory's ascendants using the parent relationship. Should be an | ||
absolute path. | ||
build_root: A directory that acts as a fence for the search. If the search | ||
reaches this directory, it will not advance to its parent. Should be an | ||
absolute path. | ||
|
||
Returns: | ||
The path to a file with the desired name. None if the search failed. | ||
""" | ||
candidate = os.path.join(path, target) | ||
if os.path.isfile(candidate): | ||
return candidate | ||
|
||
if path == build_root: | ||
return None | ||
|
||
parent = os.path.dirname(path) | ||
if parent == path: | ||
return None | ||
|
||
return FindNearest(target, parent, build_root) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add error handling for path operations
The FindNearest
function should handle potential OS errors during path operations.
def FindNearest(target, path, build_root):
+ try:
candidate = os.path.join(path, target)
if os.path.isfile(candidate):
return candidate
if path == build_root:
return None
parent = os.path.dirname(path)
if parent == path:
return None
return FindNearest(target, parent, build_root)
+ except OSError as e:
+ print(f"Error accessing path {path}: {e}")
+ return None
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
def FindNearest(target, path, build_root): | |
"""Looks for a file with a specific name closest to a project path. | |
This is similar to the logic used by a version-control system (like git) to | |
find its configuration directory (.git) based on the current directory when a | |
command is invoked. | |
Args: | |
target: The file name to search for. | |
path: The directory where the search starts. The search will explore the | |
given directory's ascendants using the parent relationship. Should be an | |
absolute path. | |
build_root: A directory that acts as a fence for the search. If the search | |
reaches this directory, it will not advance to its parent. Should be an | |
absolute path. | |
Returns: | |
The path to a file with the desired name. None if the search failed. | |
""" | |
candidate = os.path.join(path, target) | |
if os.path.isfile(candidate): | |
return candidate | |
if path == build_root: | |
return None | |
parent = os.path.dirname(path) | |
if parent == path: | |
return None | |
return FindNearest(target, parent, build_root) | |
def FindNearest(target, path, build_root): | |
"""Looks for a file with a specific name closest to a project path. | |
This is similar to the logic used by a version-control system (like git) to | |
find its configuration directory (.git) based on the current directory when a | |
command is invoked. | |
Args: | |
target: The file name to search for. | |
path: The directory where the search starts. The search will explore the | |
given directory's ascendants using the parent relationship. Should be an | |
absolute path. | |
build_root: A directory that acts as a fence for the search. If the search | |
reaches this directory, it will not advance to its parent. Should be an | |
absolute path. | |
Returns: | |
The path to a file with the desired name. None if the search failed. | |
""" | |
try: | |
candidate = os.path.join(path, target) | |
if os.path.isfile(candidate): | |
return candidate | |
if path == build_root: | |
return None | |
parent = os.path.dirname(path) | |
if parent == path: | |
return None | |
return FindNearest(target, parent, build_root) | |
except OSError as e: | |
print(f"Error accessing path {path}: {e}") | |
return None |
while ((status = sqlite3_step(read_stmt)) == SQLITE_ROW) { | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential infinite loop risk
The while loop for reading rows doesn't have a safety limit and could potentially loop indefinitely.
Add a safety limit:
+ int row_count = 0;
+ const int MAX_ROWS = 1000000; // Adjust based on expected maximum
while ((status = sqlite3_step(read_stmt)) == SQLITE_ROW) {
+ if (++row_count > MAX_ROWS) {
+ fprintf(stderr, "Error: Exceeded maximum row count\n");
+ break;
+ }
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
while ((status = sqlite3_step(read_stmt)) == SQLITE_ROW) { | |
} | |
int row_count = 0; | |
const int MAX_ROWS = 1000000; // Adjust based on expected maximum | |
while ((status = sqlite3_step(read_stmt)) == SQLITE_ROW) { | |
if (++row_count > MAX_ROWS) { | |
fprintf(stderr, "Error: Exceeded maximum row count\n"); | |
break; | |
} | |
} |
SharedState(int total) | ||
: cv(&mu), total(total), num_initialized(0), num_done(0), start(false) {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix self-initialization in SharedState constructor
The constructor has a potential self-initialization issue with the total
member variable.
Apply this fix:
- SharedState(int total)
- : cv(&mu), total(total), num_initialized(0), num_done(0), start(false) {}
+ SharedState(int t)
+ : cv(&mu), total(t), num_initialized(0), num_done(0), start(false) {}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
SharedState(int total) | |
: cv(&mu), total(total), num_initialized(0), num_done(0), start(false) {} | |
SharedState(int t) | |
: cv(&mu), total(t), num_initialized(0), num_done(0), start(false) {} |
🧰 Tools
🪛 cppcheck (2.10-2)
[error] 295-295: Member variable 'total' is initialized by itself.
(selfInitialization)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 60
🧹 Nitpick comments (51)
cmake/module/WarnAboutGlobalProperties.cmake (3)
7-26
: LGTM! Well-structured property checks with clear guidance.The implementation consistently checks for discouraged directory-wide properties and provides clear guidance on target-specific alternatives. The use of
AUTHOR_WARNING
is appropriate for build-time developer notifications.Consider adding a function to reduce code duplication across the three similar property checks:
+function(warn_if_global_property property_name property_type) + get_directory_property(global_property ${property_type}) + if(global_property) + message(AUTHOR_WARNING "The directory's ${property_name} property is not empty: ${global_property}") + endif() +endfunction() + +warn_if_global_property("COMPILE_DEFINITIONS" COMPILE_DEFINITIONS) +warn_if_global_property("COMPILE_OPTIONS" COMPILE_OPTIONS) +warn_if_global_property("LINK_OPTIONS" LINK_OPTIONS)
28-36
: Consider enhancing the link libraries check implementation.The approach to detect globally linked libraries using a dummy target is clever. However, there are a few potential improvements:
- Add cleanup of the dummy file:
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/dummy_cxx_source.cpp "#error") +set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_CLEAN_FILES + "${CMAKE_CURRENT_BINARY_DIR}/dummy_cxx_source.cpp")
- Enhance the warning message to be more descriptive:
- message(AUTHOR_WARNING "There are libraries linked with `link_libraries` commands: ${global_linked_libraries}") + message(AUTHOR_WARNING "Found libraries linked with deprecated `link_libraries` command. \ + Use target_link_libraries() instead for: ${global_linked_libraries}")
1-36
: Well-designed module for enforcing modern CMake practices.This module plays a crucial role in the transition to a modern CMake build system by:
- Detecting usage of deprecated directory-wide properties
- Guiding developers towards target-specific commands
- Helping maintain a clean and maintainable build system
This aligns well with the PR's objective of introducing CMake build system support for the Firo project.
Consider integrating this module early in your CMake configuration to catch property issues before they propagate through the build system. You might want to include it in your root CMakeLists.txt after project() declaration.
cmake/module/CheckSourceCompilesAndLinks.cmake (3)
9-10
: Good optimization for compilation checks!Setting
CMAKE_TRY_COMPILE_TARGET_TYPE
toSTATIC_LIBRARY
is an excellent optimization as it avoids unnecessary linking steps during compilation checks. This can significantly improve the configuration phase performance, especially in large projects.
12-16
: Consider adding documentation and using state management.While the macro's implementation is correct, consider these improvements:
- Add documentation explaining the macro's purpose, parameters, and usage.
- Use cmake_push_check_state/cmake_pop_check_state for safer state management.
+# check_cxx_source_links(<source> <variable>) +# +# Check if the given source code can be compiled and linked into an executable. +# The result will be stored in the specified variable. macro(check_cxx_source_links source) - set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE) + cmake_push_check_state(RESET) + set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE) check_cxx_source_compiles("${source}" ${ARGN}) - set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) + cmake_pop_check_state() endmacro()
18-39
: Add documentation and consider reducing code duplication.The utility macros are well-implemented with proper state management, but consider these improvements:
- Add documentation for each macro explaining its purpose, parameters, and usage.
- Consider extracting the common flag-setting logic to reduce duplication between
check_cxx_source_compiles_with_flags
andcheck_cxx_source_links_with_flags
.Example documentation and refactoring:
+# check_cxx_source_compiles_with_flags(<flags> <source> <variable>) +# +# Check if the given source code compiles with the specified flags. +# The result will be stored in the specified variable. macro(check_cxx_source_compiles_with_flags flags source) cmake_push_check_state(RESET) set(CMAKE_REQUIRED_FLAGS ${flags}) list(JOIN CMAKE_REQUIRED_FLAGS " " CMAKE_REQUIRED_FLAGS) check_cxx_source_compiles("${source}" ${ARGN}) cmake_pop_check_state() endmacro() +# check_cxx_source_links_with_flags(<flags> <source> <variable>) +# +# Check if the given source code compiles and links with the specified flags. +# The result will be stored in the specified variable. macro(check_cxx_source_links_with_flags flags source) cmake_push_check_state(RESET) set(CMAKE_REQUIRED_FLAGS ${flags}) list(JOIN CMAKE_REQUIRED_FLAGS " " CMAKE_REQUIRED_FLAGS) check_cxx_source_links("${source}" ${ARGN}) cmake_pop_check_state() endmacro() +# check_cxx_source_links_with_libs(<libs> <source> <variable>) +# +# Check if the given source code compiles and links with the specified libraries. +# The result will be stored in the specified variable. macro(check_cxx_source_links_with_libs libs source) cmake_push_check_state(RESET) set(CMAKE_REQUIRED_LIBRARIES "${libs}") check_cxx_source_links("${source}" ${ARGN}) cmake_pop_check_state() endmacro()cmake/script/macos_zip.sh (2)
8-10
: Consider error handling for invalid SOURCE_DATE_EPOCHWhile the reproducible build handling is good, the script should validate the SOURCE_DATE_EPOCH value.
if [ -n "$SOURCE_DATE_EPOCH" ]; then + if ! expr "$SOURCE_DATE_EPOCH" : '^[0-9][0-9]*$' >/dev/null; then + echo "Error: SOURCE_DATE_EPOCH must be a positive integer" >&2 + exit 1 + fi find . -exec touch -d "@$SOURCE_DATE_EPOCH" {} + fi
1-12
: Add script documentationThe script would benefit from a header comment explaining its purpose, usage, and integration with the CMake build system.
#!/bin/sh # Copyright (c) 2024-present The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or https://opensource.org/license/mit/. +# This script creates deterministic zip archives for macOS builds. +# It ensures reproducible builds by: +# 1. Using a consistent locale (C) for sorting +# 2. Supporting SOURCE_DATE_EPOCH for consistent file timestamps +# 3. Sorting files deterministically +# +# Usage: macos_zip.sh <zip_command> <exclusion_pattern> +# +# Integration: This script is called from CMake during the packaging phase +# to create consistent distribution archives. + export LC_ALL=Ccmake/module/FindQt.cmake (5)
1-15
: Consider enhancing the module documentation.While the current documentation clearly states the purpose, it would be more helpful to add:
- Required and optional input variables (e.g.,
Qt_FIND_VERSION
,Qt_FIND_COMPONENTS
)- Output variables that users should expect
- Example usage
17-28
: Enhance error handling and logging for Homebrew detection.Consider the following improvements:
- Log the detected Qt prefix using
message(DEBUG "Found Qt Homebrew prefix: ${_qt_homebrew_prefix}")
for debugging- Validate the homebrew command output before using it
- Consider logging errors instead of silently ignoring them with
ERROR_QUIET
43-48
: Consider adding more platform-specific search paths.While the current implementation handles OpenBSD and Homebrew paths, consider adding:
- Common Windows Qt installation paths
- Additional Unix-like system paths (e.g.,
/usr/lib/qt${Qt_FIND_VERSION_MAJOR}
)
64-66
: Clarify the purpose of empty ITEMS in foreach loop.The empty
ITEMS ""
in the foreach loop seems unnecessary. If it's intended to handle the case when no components are specified, consider making this more explicit in the code comments.-foreach(component IN LISTS Qt_FIND_COMPONENTS ITEMS "") +# Include empty string to ensure the loop runs at least once even with no components +foreach(component IN LISTS Qt_FIND_COMPONENTS ITEMS "")
1-66
: Consider adding integration tests for the FindQt module.As this is part of a larger CMake build system implementation, it would be valuable to:
- Add test cases that verify Qt detection across different platforms
- Document common troubleshooting steps in case Qt is not found
- Consider adding a test that verifies the module works with both system Qt and custom Qt installations
cmake/tests.cmake (1)
1-4
: Update copyright notice for Firo projectThe copyright notice currently references Bitcoin Core developers. Since this is being added to the Firo project, consider updating the copyright notice to reflect the correct ownership.
-# Copyright (c) 2023-present The Bitcoin Core developers +# Copyright (c) 2023-present The Firo Core developerscmake/module/AddWindowsResources.cmake (1)
7-14
: Consider enhancing the macro with parameter validation and documentationThe macro implementation is correct but could benefit from some improvements for robustness and maintainability.
Consider applying these enhancements:
+# Adds Windows resource files to the specified target +# Parameters: +# target - The target to add resources to +# rc_file - The resource file to add macro(add_windows_resources target rc_file) + if(NOT TARGET ${target}) + message(FATAL_ERROR "Target '${target}' does not exist") + endif() + if(NOT EXISTS "${rc_file}") + message(FATAL_ERROR "Resource file '${rc_file}' does not exist") + endif() if(WIN32) target_sources(${target} PRIVATE ${rc_file}) set_property(SOURCE ${rc_file} APPEND PROPERTY COMPILE_DEFINITIONS WINDRES_PREPROC ) endif() endmacro()The suggested improvements add:
- Documentation explaining the macro's purpose and parameters
- Validation to ensure the target exists
- Validation to ensure the resource file exists
cmake/module/FindQRencode.cmake (4)
22-37
: Consider adding version extraction from header file.While the basic library and header discovery is well-implemented, consider adding version extraction directly from the header file as a fallback when pkg-config is not available.
Add this after the header discovery:
if(QRencode_INCLUDE_DIR AND NOT PC_QRencode_VERSION) file(STRINGS "${QRencode_INCLUDE_DIR}/qrencode.h" qrencode_version_str REGEX "^#define[\t ]+QRENCODE_VERSION[\t ]+\".*\"") if(qrencode_version_str) string(REGEX REPLACE "^#define[\t ]+QRENCODE_VERSION[\t ]+\"([^\"]*)\".*" "\\1" QRencode_VERSION "${qrencode_version_str}") endif() endif()
38-42
: Consider using extracted version when pkg-config version is unavailable.If you implement the header version extraction suggested above, update this section to use the extracted version as a fallback.
Modify the find_package_handle_standard_args call:
find_package_handle_standard_args(QRencode REQUIRED_VARS QRencode_LIBRARY QRencode_INCLUDE_DIR - VERSION_VAR PC_QRencode_VERSION + VERSION_VAR QRencode_VERSION )
44-67
: Consider adding IMPORTED_LINK_INTERFACE_LANGUAGES property.While the target setup is good, specifying the link interface language can help CMake better understand the library type.
Add this property setting:
set_target_properties(QRencode::QRencode PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${QRencode_INCLUDE_DIR}" + IMPORTED_LINK_INTERFACE_LANGUAGES "C" )
69-71
: Consider marking additional variables as advanced.To reduce CMake GUI clutter, consider marking the library variables as advanced as well.
Add these variables to mark_as_advanced:
mark_as_advanced( QRencode_INCLUDE_DIR + QRencode_LIBRARY + QRencode_LIBRARY_RELEASE + QRencode_LIBRARY_DEBUG )cmake/module/FindUSDT.cmake (3)
1-25
: Consider enhancing the module documentation.The documentation is well-structured, but could be more comprehensive by adding:
- CMake version requirements
- Platform support information (e.g., Linux-specific)
- Cache variables that might affect the module's behavior
27-30
: Consider adding search hints and version detection.The header search could be more flexible by:
- Adding hints for custom installation paths:
find_path(USDT_INCLUDE_DIR NAMES sys/sdt.h + HINTS + ENV USDT_ROOT + ENV SYSTEMTAP_ROOT + PATH_SUFFIXES include )
- Implementing version detection if required for compatibility.
32-54
: Enhance the compilation test for better coverage.The current test verifies basic functionality, but consider:
- Testing more USDT macros (e.g.,
DTRACE_PROBE*
)- Adding error messages for failed compilation:
check_cxx_source_compiles(" #define SDT_USE_VARIADIC 1 #include <sys/sdt.h> int main() { STAP_PROBEV(context, event); int a, b, c, d, e, f, g; STAP_PROBEV(context, event, a, b, c, d, e, f, g); + // Test DTRACE macros + DTRACE_PROBE1(context, event, a); + return 0; } - " HAVE_USDT_H + " HAVE_USDT_H + FAIL_REGEX "SDT_USE_VARIADIC.*not declared" )cmake/script/CoverageFuzz.cmake (2)
11-14
: Consider adding validation for the JOBS parameter.While the JOBS parameter handling is functional, it might benefit from validation to ensure a positive integer value.
if(DEFINED JOBS) + if(NOT JOBS MATCHES "^[1-9][0-9]*$") + message(FATAL_ERROR "JOBS must be a positive integer") + endif() list(APPEND fuzz_test_runner -j ${JOBS}) endif()
1-53
: Consider restructuring for better maintainability.The script would benefit from being split into separate CMake functions for each major operation (test execution, coverage capture, report generation). This would improve:
- Reusability: Functions can be called from other CMake scripts
- Maintainability: Each function can have its own error handling and cleanup
- Testability: Functions can be tested independently
Consider creating a new file
CoverageFuzzFunctions.cmake
with these functions:
run_fuzz_tests()
capture_coverage()
generate_coverage_report()
Then this script would simply call these functions in sequence, making it easier to understand and maintain.
cmake/module/GenerateHeaders.cmake (2)
5-12
: Consider adding input validation and documentationThe function implementation is correct, but could benefit from some improvements:
- Add input parameter validation
- Add function documentation explaining usage and parameters
- Consider making the script path configurable
Consider adding this documentation and validation:
+# Generates a C++ header file from a JSON source file +# Parameters: +# json_source_relpath - Relative path to the JSON source file +# Output: +# Generated header file in the binary directory with .h extension function(generate_header_from_json json_source_relpath) + if(NOT json_source_relpath) + message(FATAL_ERROR "json_source_relpath is required") + endif() + if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${json_source_relpath}") + message(FATAL_ERROR "JSON source file not found: ${CMAKE_CURRENT_SOURCE_DIR}/${json_source_relpath}") + endif() add_custom_command(
1-21
: Consider adding target dependency managementThe header generation functions work well, but consider adding a helper function to manage target dependencies. This would ensure proper build ordering and dependency tracking.
Example implementation:
# Add generated headers as dependencies to a target function(add_generated_headers_to_target target) get_target_property(target_binary_dir ${target} BINARY_DIR) if(NOT target_binary_dir) set(target_binary_dir ${CMAKE_CURRENT_BINARY_DIR}) endif() target_include_directories(${target} PRIVATE ${target_binary_dir}) foreach(header IN LISTS ARGN) target_sources(${target} PRIVATE ${target_binary_dir}/${header}.h) endforeach() endfunction()Usage example:
add_library(mylib ...) generate_header_from_json("data/config.json") add_generated_headers_to_target(mylib "data/config")cmake/module/TestAppendRequiredLibraries.cmake (4)
49-51
: Avoid code duplication by creating a helper functionBoth
test_append_socket_library
andtest_append_atomic_library
check if the target exists and display a similar fatal error message if it doesn't. To improve maintainability and reduce code duplication, consider creating a helper function for this check.Apply this diff to introduce a helper function:
+function(ensure_target_exists target) + if (NOT TARGET ${target}) + message(FATAL_ERROR "${CMAKE_CURRENT_FUNCTION}() called with non-existent target \"${target}\".") + endif() +endfunction() + function(test_append_socket_library target) - if (NOT TARGET ${target}) - message(FATAL_ERROR "${CMAKE_CURRENT_FUNCTION}() called with non-existent target \"${target}\".") - endif() + ensure_target_exists(${target}) ... function(test_append_atomic_library target) - if (NOT TARGET ${target}) - message(FATAL_ERROR "${CMAKE_CURRENT_FUNCTION}() called with non-existent target \"${target}\".") - endif() + ensure_target_exists(${target}) ...Also applies to: 13-15
80-91
: Simplify conditional logicThe conditional logic in
test_append_atomic_library
can be simplified to improve readability. Since we return early ifSTD_ATOMIC_LINKS_WITHOUT_LIBATOMIC
is true, the subsequentif
block can be reorganized.Apply this diff to simplify the logic:
check_cxx_source_links("${check_atomic_source}" STD_ATOMIC_LINKS_WITHOUT_LIBATOMIC) - if(STD_ATOMIC_LINKS_WITHOUT_LIBATOMIC) - return() - endif() - - check_cxx_source_links_with_libs(atomic "${check_atomic_source}" STD_ATOMIC_NEEDS_LINK_TO_LIBATOMIC) - if(STD_ATOMIC_NEEDS_LINK_TO_LIBATOMIC) - target_link_libraries(${target} INTERFACE atomic) - else() + if(NOT STD_ATOMIC_LINKS_WITHOUT_LIBATOMIC) + check_cxx_source_links_with_libs(atomic "${check_atomic_source}" STD_ATOMIC_NEEDS_LINK_TO_LIBATOMIC) + if(STD_ATOMIC_NEEDS_LINK_TO_LIBATOMIC) + target_link_libraries(${target} INTERFACE atomic) + else() message(FATAL_ERROR "Cannot figure out how to use std::atomic.") + endif() endif()
12-40
: Add documentation comments for the functionsCurrently, the functions lack formal documentation in the form of CMake documentation comments. Adding these comments will improve readability and help other developers understand the purpose and usage of these functions.
Apply this diff to add documentation comments:
function(test_append_socket_library target) + # Tests if the target requires linking with -lsocket when using getifaddrs and freeifaddrs. + # + # Args: + # target: The CMake target to modify if necessary. + if (NOT TARGET ${target}) message(FATAL_ERROR "${CMAKE_CURRENT_FUNCTION}() called with non-existent target \"${target}\".") endif() ... function(test_append_atomic_library target) + # Tests if the target requires linking with -latomic when using std::atomic. + # + # Args: + # target: The CMake target to modify if necessary. + if (NOT TARGET ${target}) message(FATAL_ERROR "${CMAKE_CURRENT_FUNCTION}() called with non-existent target \"${target}\".") endif() ...Also applies to: 48-92
54-78
: Ensure the test code is minimal and effectiveThe test code in
check_atomic_source
includes more operations than necessary to check for linkage with-latomic
. Simplifying the test code can reduce compilation time during configuration.Consider reducing the test code to only what's needed to trigger the linkage requirement.
set(check_atomic_source " #include <atomic> - #include <cstdint> - #include <chrono> - - using namespace std::chrono_literals; - int main() { - std::atomic<bool> lock{true}; - lock.exchange(false); - - std::atomic<std::chrono::seconds> t{0s}; - t.store(2s); - auto t1 = t.load(); - t.compare_exchange_strong(t1, 3s); - - std::atomic<double> d{}; - d.store(3.14); - auto d1 = d.load(); - - std::atomic<int64_t> a{}; - int64_t v = 5; - int64_t r = a.fetch_add(v); - return static_cast<int>(r); + std::atomic<int> a{0}; + a.fetch_add(1); + return a.load(); } ")cmake/module/TryAppendLinkerFlag.cmake (2)
45-61
: Simplify nestedif
statements for improved readabilityThe deeply nested
if
statements within the function make the code harder to read and maintain. Refactoring the conditional logic can enhance clarity.Consider restructuring the conditions as follows:
if(${result}) if(DEFINED TALF_TARGET) if(DEFINED TALF_IF_CHECK_PASSED) target_link_options(${TALF_TARGET} INTERFACE ${TALF_IF_CHECK_PASSED}) else() target_link_options(${TALF_TARGET} INTERFACE ${flag}) endif() endif() if(DEFINED TALF_VAR) if(DEFINED TALF_IF_CHECK_PASSED) string(STRIP "${${TALF_VAR}} ${TALF_IF_CHECK_PASSED}" ${TALF_VAR}) else() string(STRIP "${${TALF_VAR}} ${flag}" ${TALF_VAR}) endif() endif() endif()
72-78
: Consider expanding platform supportThe current implementation handles MSVC, Darwin, and other systems in a generalized way. To enhance cross-platform compatibility, consider explicitly handling other platforms or compilers as needed.
cmake/ccache.cmake (2)
16-18
: Clarify the warning message about ccacheThe warning message may not be clear to users attempting to disable ccache. Providing more context will help users understand the situation.
Consider rephrasing the warning message:
list(APPEND configure_warnings - "Disabling ccache was attempted using -DWITH_CCACHE=${WITH_CCACHE}, but ccache masquerades as the compiler." + "ccache is detected as the compiler; disabling ccache with -DWITH_CCACHE=${WITH_CCACHE} has no effect." )
28-28
: MarkCCACHE_EXECUTABLE
as advanced only when foundCurrently,
CCACHE_EXECUTABLE
is marked as advanced regardless of whetherccache
is found. It's clearer to mark it as advanced only whenccache
is available.Modify the code as follows:
endif() + mark_as_advanced(CCACHE_EXECUTABLE) else() set(WITH_CCACHE OFF) endif() -mark_as_advanced(CCACHE_EXECUTABLE)cmake/script/CoverageInclude.cmake.in (1)
16-18
: AddWORLD_EXECUTE
permission to the scriptTo ensure that the generated
cov_tool_wrapper.sh
script is executable by all users, consider addingWORLD_EXECUTE
toFILE_PERMISSIONS
:FILE_PERMISSIONS OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ + WORLD_EXECUTE
cmake/module/TryAppendCXXFlags.cmake (4)
117-117
: Typographical error in warning messageThe warning message at line 117 contains a grammatical error:
message(WARNING "'${flags_as_string}' fail(s) to link.")The phrase "fail(s) to link" is incorrect grammar. It should be "failed to link" for proper English usage.
Consider updating the message for clarity. Apply the following diff:
-message(WARNING "'${flags_as_string}' fail(s) to link.") +message(WARNING "'${flags_as_string}' failed to link.")
8-40
: Clarify multi-line comment syntaxThe multi-line comment starting at line 8 uses the syntax
#[=[ ... ]=]
:#[=[ Add language-wide flags, which will be passed to all invocations of the compiler. ... ]=]While CMake supports bracket comments using
#[[ ... ]]
, the use of nested brackets with equal signs (#[=[ ... ]=]
) may not be universally supported across all versions of CMake.To ensure compatibility and clarity, consider using standard bracket comments. Apply the following diff:
-#[=[ ... ]=] +#[[ ... ]]
41-119
: Enhance error handling and loggingThe function
try_append_cxx_flags
performs several checks and conditionally applies flags. However, if the compiler or linker does not support the flags, the function may fail silently without providing enough context.Consider enhancing the error handling by adding more descriptive messages when flags are not supported. This helps users diagnose configuration issues more effectively. For example, you can modify the warnings:
-message(WARNING "'${flags_as_string}' fail(s) to link.") +message(WARNING "Linker does not support flags: '${flags_as_string}'.")Additionally, you can inform the user when compiler flags are not supported:
+else() + message(WARNING "Compiler does not support flags: '${flags_as_string}'.") endif()
69-85
: Simplify nested conditional statementsThe nested conditional statements between lines 69 and 85 increase complexity and may affect readability. Refactoring the code to reduce nesting can improve maintainability.
Consider simplifying the nested
if
statements by combining conditions or restructuring the logic. Here's a refactored version:if(${compiler_result}) - if(DEFINED TACXXF_IF_CHECK_PASSED) - set(flags_to_apply "${TACXXF_IF_CHECK_PASSED}") - else() - set(flags_to_apply "${flags}") - endif() + set(flags_to_apply "${flags}") + if(DEFINED TACXXF_IF_CHECK_PASSED) + set(flags_to_apply "${TACXXF_IF_CHECK_PASSED}") + endif() if(DEFINED TACXXF_TARGET) target_compile_options(${TACXXF_TARGET} INTERFACE ${flags_to_apply}) endif() if(DEFINED TACXXF_VAR) string(STRIP "${${TACXXF_VAR}} ${flags_to_apply}" ${TACXXF_VAR}) endif() endif()This refactoring reduces duplication and makes the code easier to follow.
cmake/script/GenerateBuildInfo.cmake (1)
44-50
: Use 'git update-index --refresh' to refresh index statusThe comment suggests that running
git diff
cleans the 'dirty' status, butgit diff
is read-only and doesn't modify the index. To refresh the index and accurately detect if the working tree is dirty, usegit update-index --refresh
instead.Apply this diff to update the command:
# Refresh index to update 'dirty' status of touched files that haven't been modified. - execute_process( - COMMAND ${GIT_EXECUTABLE} diff - WORKING_DIRECTORY ${WORKING_DIR} - OUTPUT_QUIET - ERROR_QUIET - ) + execute_process( + COMMAND ${GIT_EXECUTABLE} update-index --refresh + WORKING_DIRECTORY ${WORKING_DIR} + OUTPUT_QUIET + ERROR_QUIET + )cmake/module/GetTargetInterface.cmake (1)
15-23
: Enhance support for additional generator expressions inevaluate_generator_expressions
.The current implementation matches specific patterns of generator expressions. Consider extending support to handle a wider range of expressions or utilize CMake's built-in generator expression evaluation for more robust handling.
cmake/script/GenerateHeaderFromRaw.cmake (1)
7-10
: Handle large files more efficiently when formatting hex contentFor large raw files, the current method of reading and processing the entire content may consume significant memory and processing time.
Consider processing the file in chunks or using a stream-oriented approach to handle large files more efficiently. Alternatively, if large files are not expected, this can be accepted as is.
cmake/script/GenerateHeaderFromJson.cmake (1)
11-22
: Add header guards and improve namespace documentationThe generated header lacks header guards and namespace documentation.
Consider enhancing the header template:
set(header_content -"#include <string_view> +"#ifndef JSON_TESTS_${json_source_basename}_H +#define JSON_TESTS_${json_source_basename}_H + +#include <string_view> +/** + * @namespace json_tests + * @brief Namespace containing JSON test data converted to C++ string views + */ namespace json_tests { + inline constexpr char detail_${json_source_basename}_bytes[] { ${formatted_bytes} }; inline constexpr std::string_view ${json_source_basename}{std::begin(detail_${json_source_basename}_bytes), std::end(detail_${json_source_basename}_bytes)}; + } // namespace json_tests + +#endif // JSON_TESTS_${json_source_basename}_H ")cmake/module/FindZeroMQ.cmake (2)
31-41
: Add static/dynamic preference handlingThe pkg-config fallback should respect the project's preference for static/dynamic linking.
Add static linking support:
find_package(PkgConfig REQUIRED) + +# Handle static/dynamic preference +if(ZEROMQ_USE_STATIC_LIBS) + set(ZEROMQ_PKG_NAME "libzmq-static") +else() + set(ZEROMQ_PKG_NAME "libzmq") +endif() + pkg_check_modules(libzmq QUIET IMPORTED_TARGET - libzmq>=${ZeroMQ_FIND_VERSION} + ${ZEROMQ_PKG_NAME}${ZEROMQ_VERSION_REQ} )
1-15
: Enhance module documentationThe module documentation could be more comprehensive.
Add usage examples and more detailed documentation:
#[=======================================================================[ FindZeroMQ ---------- Finds the ZeroMQ headers and library. This is a wrapper around find_package()/pkg_check_modules() commands that: - facilitates searching in various build environments - prints a standard log message + +Result Variables +^^^^^^^^^^^^^^^ + + ZEROMQ_FOUND - System has ZeroMQ + ZEROMQ_INCLUDE_DIRS - ZeroMQ include directories + ZEROMQ_LIBRARIES - ZeroMQ libraries + +Hints +^^^^^ + + ZEROMQ_ROOT - ZeroMQ installation prefix + ZEROMQ_USE_STATIC_LIBS - Prefer static libraries + +Usage +^^^^^ + + find_package(ZeroMQ 4.3 REQUIRED) + target_link_libraries(myapp PRIVATE zeromq) #]=======================================================================]cmake/leveldb.cmake (1)
55-58
: Make Snappy compression support configurableCurrently,
HAVE_SNAPPY
is set to0
, disabling Snappy compression in LevelDB. Consider making this configurable through a CMake option to allow users to enable Snappy compression if desired.You can define a CMake option and update the compile definitions accordingly:
+option(ENABLE_SNAPPY "Enable Snappy compression in LevelDB" OFF) target_compile_definitions(leveldb PRIVATE - HAVE_SNAPPY=0 + HAVE_SNAPPY=$<IF:$<BOOL:${ENABLE_SNAPPY}>,1,0> HAVE_CRC32C=1cmake/module/Maintenance.cmake (2)
7-19
: Extendsetup_split_debug_script
for non-Linux platformsCurrently,
setup_split_debug_script
only configures the split-debug script for Linux. Consider extending support for other platforms or explicitly documenting that it's Linux-specific.
70-72
: Implement CPack NSIS Generator for Windows deploymentThere's a TODO comment suggesting the use of the CPack NSIS Generator. Implementing it could simplify the Windows deployment process.
Would you like assistance in integrating the CPack NSIS Generator for creating the Windows installer?
cmake/minisketch.cmake (3)
43-52
: Consider removingEXCLUDE_FROM_ALL
forminisketch_clmul
targetUsing
EXCLUDE_FROM_ALL
meansminisketch_clmul
will not be built unless explicitly requested. Ifminisketch
depends onminisketch_clmul
, ensure that it is included in the build process. Consider removingEXCLUDE_FROM_ALL
to include it by default.Apply the following change:
add_library(minisketch_clmul OBJECT ${PROJECT_SOURCE_DIR}/src/minisketch/src/fields/clmul_1byte.cpp # ... other source files ... )
65-75
: Consider removingEXCLUDE_FROM_ALL
forminisketch
targetThe
minisketch
library is likely a core component and should be included in the default build. RemovingEXCLUDE_FROM_ALL
ensures it is built without requiring explicit inclusion.Apply the following change:
-add_library(minisketch STATIC EXCLUDE_FROM_ALL +add_library(minisketch STATIC ${PROJECT_SOURCE_DIR}/src/minisketch/src/minisketch.cpp # ... other source files ... )
12-13
: Include<wmmintrin.h>
for PCLMUL intrinsicsFor portability and clarity, include
<wmmintrin.h>
when using PCLMUL intrinsics, as it specifically contains the declarations for these functions.Apply the following diff:
#include <immintrin.h> +#include <wmmintrin.h> #include <cstdint>
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (34)
cmake/bitcoin-build-config.h.in
(1 hunks)cmake/ccache.cmake
(1 hunks)cmake/cov_tool_wrapper.sh.in
(1 hunks)cmake/crc32c.cmake
(1 hunks)cmake/introspection.cmake
(1 hunks)cmake/leveldb.cmake
(1 hunks)cmake/minisketch.cmake
(1 hunks)cmake/module/AddBoostIfNeeded.cmake
(1 hunks)cmake/module/AddWindowsResources.cmake
(1 hunks)cmake/module/CheckSourceCompilesAndLinks.cmake
(1 hunks)cmake/module/FindBerkeleyDB.cmake
(1 hunks)cmake/module/FindLibevent.cmake
(1 hunks)cmake/module/FindQRencode.cmake
(1 hunks)cmake/module/FindQt.cmake
(1 hunks)cmake/module/FindUSDT.cmake
(1 hunks)cmake/module/FindZeroMQ.cmake
(1 hunks)cmake/module/FlagsSummary.cmake
(1 hunks)cmake/module/GenerateHeaders.cmake
(1 hunks)cmake/module/GenerateSetupNsi.cmake
(1 hunks)cmake/module/GetTargetInterface.cmake
(1 hunks)cmake/module/Maintenance.cmake
(1 hunks)cmake/module/ProcessConfigurations.cmake
(1 hunks)cmake/module/TestAppendRequiredLibraries.cmake
(1 hunks)cmake/module/TryAppendCXXFlags.cmake
(1 hunks)cmake/module/TryAppendLinkerFlag.cmake
(1 hunks)cmake/module/WarnAboutGlobalProperties.cmake
(1 hunks)cmake/script/Coverage.cmake
(1 hunks)cmake/script/CoverageFuzz.cmake
(1 hunks)cmake/script/CoverageInclude.cmake.in
(1 hunks)cmake/script/GenerateBuildInfo.cmake
(1 hunks)cmake/script/GenerateHeaderFromJson.cmake
(1 hunks)cmake/script/GenerateHeaderFromRaw.cmake
(1 hunks)cmake/script/macos_zip.sh
(1 hunks)cmake/tests.cmake
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- cmake/cov_tool_wrapper.sh.in
🔇 Additional comments (42)
cmake/module/WarnAboutGlobalProperties.cmake (1)
1-5
: LGTM! Proper license and include guard.
The file header is well-structured with appropriate copyright notice, license information, and a global include guard to prevent multiple inclusions.
cmake/module/CheckSourceCompilesAndLinks.cmake (1)
1-8
: LGTM! Well-structured file header with proper includes.
The file header includes appropriate copyright notice, license information, and necessary CMake module includes. The GLOBAL include guard prevents multiple inclusion issues.
cmake/script/macos_zip.sh (3)
6-7
: LGTM: Proper locale handling
Setting LC_ALL=C ensures consistent sorting behavior across different systems, which is crucial for reproducible builds.
1-5
: Ensure script has executable permissions
The script requires executable permissions to function in the build system.
✅ Verification successful
Script already has correct executable permissions (755)
The script cmake/script/macos_zip.sh
already has the proper executable permissions (-rwxr-xr-x
or 755
), allowing execution by owner, group, and others, which is appropriate for a build system script.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if the script has executable permissions
ls -l cmake/script/macos_zip.sh
Length of output: 107
1-12
: Verify integration with CMake build system
Ensure this script is properly integrated with the CMake build system and called at the appropriate build phase.
✅ Verification successful
Let me check the CMake integration details by examining the Maintenance.cmake file.
Script is properly integrated with CMake build system
The script is correctly integrated into the CMake build system through cmake/module/Maintenance.cmake
. It's used in a custom command that creates a macOS-specific zip archive during the deployment phase, with proper dependencies and target configuration:
- Used as part of the
deploy
target - Properly invoked with required ZIP_COMMAND parameter
- Executed in correct working directory (dist)
- Generates output in the expected binary directory
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check CMake files for references to this script
rg -l "macos_zip.sh" --type cmake
# Check if there are similar scripts for other platforms
fd -e sh -p "cmake/script/*_zip.sh"
Length of output: 102
Script:
#!/bin/bash
# Check how macos_zip.sh is used in the CMake file
rg -A 5 -B 5 "macos_zip.sh" cmake/module/Maintenance.cmake
Length of output: 446
cmake/module/FindQt.cmake (2)
30-41
: LGTM! Well-implemented state management.
The implementation properly handles the CMAKE_FIND_ROOT_PATH_MODE_LIBRARY state with clear documentation explaining the necessity of the changes.
50-56
: LGTM! Thorough state restoration.
The implementation properly handles all cases of state restoration and cleanup.
cmake/tests.cmake (2)
5-9
: Verify test script existence and add error handling
The test configuration assumes the existence of test/util/test_runner.py
. We should verify this and consider adding checks.
Consider adding a configuration-time check:
if(TARGET bitcoin-util AND TARGET bitcoin-tx AND PYTHON_COMMAND)
+ set(TEST_RUNNER_SCRIPT "${PROJECT_BINARY_DIR}/test/util/test_runner.py")
+ if(NOT EXISTS ${TEST_RUNNER_SCRIPT})
+ message(WARNING "test_runner.py not found at ${TEST_RUNNER_SCRIPT}")
+ else()
add_test(NAME util_test_runner
COMMAND ${CMAKE_COMMAND} -E env BITCOINUTIL=$<TARGET_FILE:bitcoin-util> BITCOINTX=$<TARGET_FILE:bitcoin-tx> ${PYTHON_COMMAND} ${PROJECT_BINARY_DIR}/test/util/test_runner.py
)
+ endif()
endif()
11-15
: Verify RPC auth test script and consider additional setup
The RPC authentication test might require additional environment setup. Also, we should verify the test script's existence.
Consider adding error handling and environment setup:
if(PYTHON_COMMAND)
+ set(RPCAUTH_TEST_SCRIPT "${PROJECT_BINARY_DIR}/test/util/rpcauth-test.py")
+ if(NOT EXISTS ${RPCAUTH_TEST_SCRIPT})
+ message(WARNING "rpcauth-test.py not found at ${RPCAUTH_TEST_SCRIPT}")
+ else()
add_test(NAME util_rpcauth_test
COMMAND ${PYTHON_COMMAND} ${PROJECT_BINARY_DIR}/test/util/rpcauth-test.py
)
+ # Consider setting test properties if needed
+ set_tests_properties(util_rpcauth_test PROPERTIES
+ ENVIRONMENT "PYTHONPATH=${PROJECT_SOURCE_DIR}/test/functional/test_framework"
+ )
+ endif()
endif()
cmake/module/AddWindowsResources.cmake (2)
1-5
: LGTM: Well-structured file header
The file properly starts with a copyright notice and includes a modern CMake include guard using include_guard(GLOBAL)
.
7-14
: Verify the macro's usage across the codebase
Let's ensure this macro is being used correctly in the project.
cmake/module/FindQRencode.cmake (3)
1-15
: LGTM! Well-documented module header.
The license header and documentation follow CMake's best practices, providing clear information about the module's purpose and functionality.
17-20
: LGTM! Robust package configuration setup.
The package configuration setup properly handles both pkg-config and non-pkg-config environments, following CMake best practices.
1-71
: Verify integration with the main build system.
Since this is part of a larger CMake build system implementation, we should verify its integration.
cmake/module/FindUSDT.cmake (2)
56-59
: LGTM! Package handling is properly implemented.
The use of FindPackageHandleStandardArgs
with appropriate required variables ensures robust package detection.
1-67
: Verify module integration with the build system.
Please ensure:
- The module is properly discoverable in CMake's module path
- The main CMakeLists.txt correctly uses this module
cmake/script/CoverageFuzz.cmake (2)
1-5
: LGTM! Proper license header and include directive.
The license header is correctly formatted with the current year, and the include directive uses the recommended CMAKE_CURRENT_LIST_DIR
variable.
7-9
: Verify the default corpora directory path.
The default path uses CMAKE_CURRENT_SOURCE_DIR
which points to the directory of the currently processed CMakeLists.txt file. Consider using PROJECT_SOURCE_DIR
instead to ensure the path is relative to the project root.
cmake/module/GenerateHeaders.cmake (2)
1-4
: LGTM: License header is properly formatted
The copyright notice and MIT license reference are correctly structured.
14-21
: Add validation, documentation, and verify namespace usage
Similar to the JSON function, this needs documentation and validation. Additionally, namespace usage should be verified across the codebase.
Consider adding documentation and validation:
+# Generates a C++ header file from a raw source file
+# Parameters:
+# raw_source_relpath - Relative path to the raw source file
+# raw_namespace - C++ namespace for the generated content
+# Output:
+# Generated header file in the binary directory with .h extension
function(generate_header_from_raw raw_source_relpath raw_namespace)
+ if(NOT raw_source_relpath)
+ message(FATAL_ERROR "raw_source_relpath is required")
+ endif()
+ if(NOT raw_namespace)
+ message(FATAL_ERROR "raw_namespace is required")
+ endif()
+ if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${raw_source_relpath}")
+ message(FATAL_ERROR "Raw source file not found: ${CMAKE_CURRENT_SOURCE_DIR}/${raw_source_relpath}")
+ endif()
add_custom_command(
Let's verify the namespace usage across the codebase:
cmake/bitcoin-build-config.h.in (6)
8-19
: LGTM: Version macros are well-structured
The version-related macros are properly defined using CMake variables and follow standard versioning practices.
20-31
: Update copyright macros for Firo project
While the structure is correct, ensure that the CMake variables (@COPYRIGHT_HOLDERS@
, @COPYRIGHT_HOLDERS_FINAL@
, etc.) are properly set in the CMake configuration to reflect Firo project information.
✅ Verification successful
Copyright macros are correctly configured for Firo project
The copyright macros in cmake/bitcoin-build-config.h.in
are properly set up and aligned with the Firo project configuration in configure.ac
. The values are correctly defined:
COPYRIGHT_HOLDERS
is set to "The %s developers"COPYRIGHT_HOLDERS_SUBSTITUTION
is set to "Firo Core"COPYRIGHT_YEAR
is set to 2024- These values are properly substituted to generate
COPYRIGHT_HOLDERS_FINAL
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if CMake variables are properly set for Firo
grep -r "set.*COPYRIGHT_HOLDERS" .
grep -r "set.*CLIENT_NAME" .
Length of output: 67
Script:
#!/bin/bash
# Let's check CMakeLists.txt files for these variables and their configuration
fd CMakeLists.txt
# Also check configure.ac as it might contain these settings
fd configure.ac
# Check any other build configuration files
fd -e cmake
Length of output: 1721
Script:
#!/bin/bash
# Let's check the main CMakeLists.txt in the root directory and cmake module files for copyright settings
cat cmake/module/ProcessConfigurations.cmake
cat cmake/module/GenerateHeaders.cmake
# Also check configure.ac as it might contain these values
cat configure.ac | grep -i "copyright\|client"
Length of output: 9523
135-149
: Validate optional feature requirements
Please verify:
- Whether Firo requires all these optional features (BDB, DBUS, QR code, SQLite)
- If there are any Firo-specific optional features missing
✅ Verification successful
Let me gather more information about these optional features to better understand their usage and dependencies.
Based on the results, I can now provide a conclusive response about the optional features:
Optional features are actively used and required
- BDB (Berkeley DB) is actively used in the wallet implementation for data storage
- DBUS notifications are implemented for Linux desktop notifications
- QR code functionality is used in the Qt GUI for generating payment request QR codes
- SQLite appears to be only referenced in benchmarking code, not in core functionality
The current set of optional features is appropriate for Firo as:
- BDB is essential for wallet functionality
- DBUS enables desktop integration on Linux
- QR codes are crucial for payment workflows
- SQLite can remain optional as it's not used in core functionality
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check usage of optional features
echo "=== Checking BDB usage ==="
rg -l "BerkeleyDB|BDB" src/
echo "=== Checking DBUS usage ==="
rg -l "DBus|DBUS" src/
echo "=== Checking QR code usage ==="
rg -l "QRCode|QR_" src/
echo "=== Checking SQLite usage ==="
rg -l "SQLite|sqlite3" src/
Length of output: 1988
Script:
#!/bin/bash
# Check deeper usage patterns and dependencies
echo "=== Checking BDB implementation details ==="
rg "BDB|BerkeleyDB" src/wallet/ -C 2
echo "=== Checking DBUS notification implementation ==="
rg "DBus|DBUS" src/qt/notificator.cpp -C 2
echo "=== Checking QR code integration ==="
rg "QRCode|QR_" src/qt/ -C 2
echo "=== Checking build system feature flags ==="
cat CMakeLists.txt | grep -A 2 -B 2 "option.*BDB\|option.*DBUS\|option.*QR\|option.*SQLITE"
Length of output: 6745
54-122
: Review necessity of system capability checks
The file includes a comprehensive set of system checks. Please verify:
- Which of these checks are actually required for Firo
- Whether any Firo-specific system requirements are missing
For example, checks like HAVE_BDB
might not be needed if Firo uses different database backends.
✅ Verification successful
Let me gather more information about the remaining system checks to get a complete picture.
Based on the comprehensive search results from both script executions, I can now generate the final response.
Most system capability checks are actively used and required
The system capability checks in the configuration are justified by actual usage in the codebase:
-
Core functionality checks are actively used:
fork
is used extensively in validation, mining, and script componentsfdatasync
andO_CLOEXEC
are used in leveldb and filesystem operationsposix_fallocate
is used in util.cppsys/prctl.h
is used in util.cppgetauxval
is used in CRC32C implementation
-
Unused or potentially removable checks:
HAVE_DECL_FREEIFADDRS
andHAVE_DECL_GETIFADDRS
HAVE_SYS_RESOURCES_H
HAVE_SYS_VMMETER_H
HAVE_VM_VM_PARAM_H
HAVE_GETENTROPY_RAND
andHAVE_GETRANDOM
The majority of these checks are essential for cross-platform compatibility and system-level operations. While a few checks appear unused, they might be needed for specific platforms or build configurations.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Find usage of these system capabilities in the codebase
for check in fork fdatasync getentropy getrandom malloc_info posix_fallocate sockaddr_un sysctl; do
echo "=== Checking usage of $check ==="
rg -l "\\b$check\\b" src/
done
Length of output: 3294
Script:
#!/bin/bash
# Check usage of remaining system capabilities and headers
echo "=== Checking HAVE_DECL_ macros usage ==="
rg -l "HAVE_DECL_(FORK|FREEIFADDRS|GETIFADDRS|PIPE2|SETSID)" src/
echo -e "\n=== Checking O_CLOEXEC usage ==="
rg -l "O_CLOEXEC" src/
echo -e "\n=== Checking sys/prctl.h includes ==="
rg -l '#include.*sys/prctl\.h' src/
echo -e "\n=== Checking sys/resources.h includes ==="
rg -l '#include.*sys/resources\.h' src/
echo -e "\n=== Checking sys/vmmeter.h includes ==="
rg -l '#include.*sys/vmmeter\.h' src/
echo -e "\n=== Checking vm/vm_param.h includes ==="
rg -l '#include.*vm/vm_param\.h' src/
echo -e "\n=== Checking getauxval usage ==="
rg -l '\bgetauxval\b' src/
Length of output: 1176
32-53
: Verify CPU optimization flags configuration
The CPU optimization flags are crucial for cryptographic performance. Ensure that:
- The CMake configuration properly detects and enables these optimizations based on the target architecture
- The flags are consistent with Firo's existing optimization strategy
✅ Verification successful
Let me gather more information about the CPU optimization configuration.
Let me gather more specific information about the CPU optimization implementations.
Based on the gathered information, I can now provide a final response:
CPU optimization flags are properly configured and implemented
The codebase shows proper configuration and implementation of CPU optimizations:
- CMake correctly detects CPU features through compiler checks (SSE4.1, AVX2, SHA-NI)
- Optimization flags are properly guarded with feature detection
- Implementation exists for optimized cryptographic operations (e.g., BLAKE2 using AVX2)
- The build system respects target architecture capabilities
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check CPU optimization detection in CMake files
rg "check_cpu|find_cpu|enable.*cpu" -A 5
# Check existing optimization flags in configure.ac for consistency
rg "SHA.*NI|AVX2|SSE4" configure.ac
Length of output: 165
Script:
#!/bin/bash
# Check CMake files for CPU feature detection and optimization flags
fd -e cmake -e txt . | xargs rg "SSE|AVX|SHA|CPU|ARCH" -A 3
# Check source files for usage of these optimizations
rg "#ifdef.*ENABLE_(ARM_SHANI|AVX2|SSE41|X86_SHANI)" -A 2
Length of output: 16031
Script:
#!/bin/bash
# Check for CPU optimization implementations in source files
rg -g "*.{cpp,h,c,cc}" "SHA.*NI|AVX2|SSE41" -B 2 -A 2
# Check CMake configuration and detection logic
fd "CMakeLists.txt" | xargs rg "check_cxx_source_compiles.*SSE|check_cxx_source_compiles.*AVX|check_cxx_source_compiles.*SHA"
Length of output: 4168
123-134
:
Update package information for Firo
The client metadata needs to be updated for Firo:
- Ensure
CLIENT_BUGREPORT
points to Firo's issue tracker - Update
CLIENT_NAME
to "Firo" - Set
PROJECT_HOMEPAGE_URL
to Firo's website
cmake/module/AddBoostIfNeeded.cmake (1)
6-18
:
Correct the multi-line comment syntax
The use of #[=[
and ]=]
for multi-line comments is not standard in CMake and may cause syntax errors.
CMake does not support block comments in this way.
To properly comment out multiple lines, prefix each line with #
on each line.
Apply this diff to correct the comments:
- #[=[
- TODO: Not all targets, which will be added in the future, require
- Boost. Therefore, a proper check will be appropriate here.
-
- Implementation notes:
- Although only Boost headers are used to build Bitcoin Core,
- we still leverage a standard CMake's approach to handle
- dependencies, i.e., the Boost::headers "library".
- A command target_link_libraries(target PRIVATE Boost::headers)
- will propagate Boost::headers usage requirements to the target.
- For Boost::headers such usage requirements is an include
- directory and other added INTERFACE properties.
- ]=]
+ # TODO: Not all targets, which will be added in the future, require
+ # Boost. Therefore, a proper check will be appropriate here.
+
+ # Implementation notes:
+ # Although only Boost headers are used to build Firo,
+ # we still leverage a standard CMake approach to handle
+ # dependencies, i.e., the Boost::headers "library".
+ # A command target_link_libraries(target PRIVATE Boost::headers)
+ # will propagate Boost::headers usage requirements to the target.
+ # For Boost::headers, such usage requirements include the include
+ # directory and other added INTERFACE properties.
Likely invalid or redundant comment.
cmake/module/TestAppendRequiredLibraries.cmake (1)
33-33
: Consider the appropriate linkage scope for libraries
In both target_link_libraries
calls, the INTERFACE
scope is used. Depending on how the targets are used in the build system, it might be more appropriate to use PRIVATE
or PUBLIC
linkage to ensure proper dependency propagation.
Please verify if INTERFACE
is the correct linkage scope for these libraries. If the target is an executable or if consumers of the target do not need to be aware of these libraries, PRIVATE
might be more appropriate.
Also applies to: 88-88
✅ Verification successful
Based on the search results, I can now make a determination about the socket library linkage:
The INTERFACE linkage scope is correct for the socket library
The socket library is used to provide getifaddrs/freeifaddrs functionality that may be needed by consumers of the core_interface target. The INTERFACE scope is appropriate here because:
- The library is added conditionally only when needed based on platform requirements (specifically for Illumos/SmartOS systems)
- It's linked to core_interface which is an INTERFACE library meant to propagate common requirements to other targets
- The functionality (getifaddrs/freeifaddrs) needs to be available to any target that uses the core_interface
The INTERFACE scope ensures that any target linking against core_interface will also get the socket library linked if it's required on that platform.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check where the target is used to determine proper linkage scope.
# Since CMakeLists.txt files are not provided, this script will search for usages of the target.
rg "add_library\|add_executable" -A 5
Length of output: 39
Script:
#!/bin/bash
# Let's try a different approach to find CMake files and their content
fd -e cmake . | xargs cat
Length of output: 78625
Script:
#!/bin/bash
# Search for any references to target_link_libraries
rg "target_link_libraries" -A 5 -B 5
Length of output: 23110
Script:
#!/bin/bash
# Search for any references to socket library
rg "socket" -A 5 -B 5 cmake/
Length of output: 4756
cmake/script/CoverageInclude.cmake.in (1)
6-7
: Verify the usage of llvm-cov
with gcov
In the Clang case, COV_TOOL
is set to "${LLVM_COV_EXECUTABLE} gcov"
. Please ensure that invoking llvm-cov
with the gcov
command works as intended in your build environment. This setup assumes that llvm-cov
can act as a drop-in replacement for gcov
.
If applicable, run the following script to verify that llvm-cov gcov
is available and functional:
✅ Verification successful
Let me check how this coverage tool is used in the codebase to provide a more informed response.
The llvm-cov gcov
configuration is correctly implemented
The code is correctly handling coverage tools by:
- Using
llvm-cov gcov
specifically for Clang compiler (if("@CMAKE_CXX_COMPILER_ID@" STREQUAL "Clang")
) - Falling back to regular
gcov
for other compilers - Properly integrating with LCOV through a wrapper script (
cov_tool_wrapper.sh
)
The setup is part of a well-structured coverage system that:
- Configures coverage tools based on the compiler being used
- Integrates with LCOV for report generation
- Handles both unit tests and fuzz testing coverage
- Includes appropriate filtering of system and third-party code
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that 'llvm-cov gcov' is a valid command.
if command -v llvm-cov >/dev/null 2>&1; then
llvm-cov gcov --version >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "'llvm-cov gcov' is available."
else
echo "Error: 'llvm-cov gcov' is not supported. Please check your LLVM installation."
fi
else
echo "Error: llvm-cov not found. Please install LLVM's coverage tools."
fi
Length of output: 163
Script:
#!/bin/bash
# Search for usage of COV_TOOL variable and coverage-related configurations
rg -l "COV_TOOL|llvm-cov" --type cmake
# Check if there are alternative coverage tools configured
rg -l "gcov|coverage" --type cmake
Length of output: 207
Script:
#!/bin/bash
# Check the content of coverage-related CMake files to understand the configuration
cat cmake/script/Coverage.cmake
cat cmake/script/CoverageFuzz.cmake
cat cmake/script/CoverageInclude.cmake.in
Length of output: 7490
cmake/script/GenerateBuildInfo.cmake (1)
110-113
: LGTM!
The logic for conditionally writing the header file only if necessary is sound and efficient.
cmake/module/GetTargetInterface.cmake (1)
5-6
: Verify compatibility of include_guard(GLOBAL)
with project's CMake version.
The include_guard(GLOBAL)
command requires CMake version 3.10 or higher. Please ensure that the project's minimum required CMake version supports this command.
Run the following script to check the minimum required CMake version in the project:
✅ Verification successful
include_guard(GLOBAL)
usage is compatible with project's CMake version
Based on the search results, the project's submodules require CMake versions 3.1, 3.16, and 3.9, with the highest requirement being 3.16. Since include_guard(GLOBAL)
was introduced in CMake 3.10, and at least one component requires CMake 3.16, this usage is compatible with the project's CMake requirements.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check the minimum required CMake version in the project.
# Expectation: The required version should be 3.10 or higher.
rg --include 'CMakeLists.txt' 'cmake_minimum_required\(\s*VERSION\s*([0-9]+\.[0-9]+)' -or '$1'
Length of output: 536
Script:
#!/bin/bash
# Description: Check the minimum required CMake version in the project.
# Fixed the ripgrep command syntax
# Search for cmake_minimum_required in CMakeLists.txt files
rg "cmake_minimum_required\s*\(.*VERSION.*\)" -g "CMakeLists.txt"
Length of output: 256
Script:
#!/bin/bash
# Let's check for the main/root CMakeLists.txt which would set the project-wide minimum version
# First, check if there's a CMakeLists.txt in the root
rg "cmake_minimum_required" CMakeLists.txt
# Also check the content of the cmake/module directory for any version requirements
fd CMakeLists.txt cmake/
Length of output: 124
cmake/module/FindBerkeleyDB.cmake (1)
1-133
: LGTM!
The module correctly locates Berkeley DB and defines the imported target BerkeleyDB::BerkeleyDB
appropriately. The handling of platform-specific nuances, such as Homebrew's keg-only packages on macOS, is well-implemented.
cmake/module/ProcessConfigurations.cmake (1)
7-7
: Ensure the inclusion of 'TryAppendCXXFlags' module
On line 7, the script includes TryAppendCXXFlags
. Please verify that this module exists in the project and is correctly included. If it's a custom module, ensure it's added to the CMake module path or the appropriate directory so that CMake can locate it during the build process.
To confirm the presence of the TryAppendCXXFlags.cmake
module, run the following script:
This script searches for the TryAppendCXXFlags.cmake
file in your project. If it's not found, you may need to add it or correct the include path.
✅ Verification successful
Module 'TryAppendCXXFlags' exists and is correctly located
The TryAppendCXXFlags.cmake
module is present in the expected location at cmake/module/TryAppendCXXFlags.cmake
, which is in the same directory as the including file. This confirms that the module exists and will be found by CMake during the build process.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that 'TryAppendCXXFlags.cmake' exists in the project directories.
# Search for 'TryAppendCXXFlags.cmake' in the project
fd 'TryAppendCXXFlags.cmake'
Length of output: 65
cmake/leveldb.cmake (4)
82-95
: Review and adjust warning suppression flags
The nowarn_leveldb_interface
target suppresses certain warnings. Ensure that these warning flags are appropriate for all compilers used. Some flags may be compiler-specific and could cause issues on unsupported compilers.
For example, -Wno-conditional-uninitialized
is Clang-specific, and -Wno-suggest-override
is GCC-specific. Consider using generator expressions to apply flags based on the compiler.
Update the compile options as follows:
target_compile_options(nowarn_leveldb_interface INTERFACE
$<$<CXX_COMPILER_ID:GNU>:-Wno-suggest-override>
$<$<CXX_COMPILER_ID:Clang>:-Wno-conditional-uninitialized>
)
10-10
: Verify detection of F_FULLFSYNC
symbol
Ensure that the check for F_FULLFSYNC
in fcntl.h
is necessary and correctly implemented. Confirm that HAVE_FULLFSYNC
is utilized appropriately in the codebase and that the symbol check is cross-platform compatible.
Run the following script to verify the usage of HAVE_FULLFSYNC
in the codebase:
✅ Verification successful
F_FULLFSYNC
check is correctly implemented and used
The symbol check for F_FULLFSYNC
is properly implemented and used in a platform-specific manner. The code in env_posix.cc
shows that:
- It's used specifically for macOS and iOS where
fsync()
doesn't guarantee durability past power failures - The implementation includes a fallback mechanism when
F_FULLFSYNC
is not supported - The check is part of a well-documented synchronization strategy in the
SyncFd
function
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Search for usage of 'HAVE_FULLFSYNC' in the source code.
# Test: Find all occurrences of 'HAVE_FULLFSYNC' in .cc and .h files.
# Expect: Confirm that the macro is used where needed.
rg 'HAVE_FULLFSYNC' --glob '**/*.{cc,h}'
Length of output: 145
Script:
#!/bin/bash
# Let's check the actual implementation around HAVE_FULLFSYNC
rg -A 10 -B 10 'HAVE_FULLFSYNC' src/leveldb/util/env_posix.cc
# Also check if F_FULLFSYNC is used in the code
rg 'F_FULLFSYNC' src/leveldb/util/env_posix.cc
# Check if there are any platform-specific conditions around this code
rg '#if.*HAVE_FULLFSYNC|#ifdef.*HAVE_FULLFSYNC' src/leveldb/util/env_posix.cc
Length of output: 1349
97-101
: Ensure linked libraries are defined and available
The leveldb
target links against core_interface
, nowarn_leveldb_interface
, and crc32c
. Verify that the core_interface
and crc32c
targets exist and are correctly defined before linking. This ensures that all dependencies are properly resolved during the build.
Run the following script to check if the targets exist:
✅ Verification successful
Based on the results from our verification scripts, I can now generate the final response:
Dependencies are properly defined and available
The verification shows that:
crc32c
is properly defined as a static library with its implementation files and dependenciesnowarn_leveldb_interface
is defined as an interface library with specific compiler optionscore_interface
is referenced multiple times and used as a dependency, though its exact definition point isn't shown, it's clearly a fundamental target that's used throughout the build system
The linking in leveldb.cmake
is safe as all required targets exist in the build system.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify that 'core_interface' and 'crc32c' targets are defined.
# Test: Use CMake's '--graphviz' option to output the target graph.
# Expect: 'core_interface' and 'crc32c' should appear as targets.
cmake --graphviz=cmake_target_graph.dot .
grep -E 'core_interface|crc32c' cmake_target_graph.dot
Length of output: 252
Script:
#!/bin/bash
# Let's search for the target definitions in CMake files
fd -e cmake -x cat {} | grep -A 5 -B 5 "add_library.*\(core_interface\|crc32c\)"
# Also search for any other references to these targets
fd -e cmake -x cat {} | grep -E "(core_interface|crc32c)"
Length of output: 3764
Script:
#!/bin/bash
# Let's search for the definition of core_interface target
fd -e cmake -x cat {} | grep -A 5 -B 5 "add_library.*core_interface"
# Also search for nowarn_leveldb_interface definition
fd -e cmake -x cat {} | grep -A 5 -B 5 "add_library.*nowarn_leveldb_interface"
Length of output: 486
63-63
: Ensure byte order detection is accurate
The variable CMAKE_CXX_BYTE_ORDER
is used to determine endianness. Confirm that CMAKE_CXX_BYTE_ORDER
is correctly set and that this approach is compatible across all target platforms.
Run the following script to check the value of CMAKE_CXX_BYTE_ORDER
:
✅ Verification successful
Byte order detection implementation is correct and well-supported
The codebase shows a robust approach to endianness detection:
- The main CMake files use standard CMake's
test_big_endian()
function for platform detection - The implementation in
cmake/leveldb.cmake
correctly usesCMAKE_CXX_BYTE_ORDER
to setLEVELDB_IS_BIG_ENDIAN
- The same approach is consistently used across different components (leveldb, crc32c)
- The codebase includes proper endianness handling headers (
src/compat/endian.h
,src/compat/byteswap.h
) for runtime support
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check the value of 'CMAKE_CXX_BYTE_ORDER' during the CMake configuration.
# Test: Print the byte order detected by CMake.
# Expect: Should output 'LITTLE_ENDIAN' or 'BIG_ENDIAN'.
cmake -LAH | grep CMAKE_CXX_BYTE_ORDER
Length of output: 136
Script:
#!/bin/bash
# Let's check how the byte order detection is implemented in CMake files
rg -A 5 "BYTE_ORDER|ENDIAN" --type cmake
Length of output: 1361
Script:
#!/bin/bash
# Check if there are any platform-specific endianness detection mechanisms
fd -e cmake -x cat {} | rg "(?i)(endian|byte.*order)"
Length of output: 201
Script:
#!/bin/bash
# Look for any test files or configuration that might deal with endianness
fd -e cpp -e h -x rg -l "(?i)(endian|byte.*order)" {}
Length of output: 1242
cmake/module/Maintenance.cmake (1)
112-112
: Verify the definition of CLIENT_NAME
The variable CLIENT_NAME
is used to generate the volume name but its value isn't shown here. Ensure that CLIENT_NAME
is correctly defined elsewhere in the project to represent Firo.
Run the following script to check the definition of CLIENT_NAME
:
cmake/minisketch.cmake (4)
27-31
: Approved
The use of an INTERFACE
library minisketch_common
with the specified compile definitions is appropriate and ensures that consuming targets receive the necessary definitions.
32-40
: Approved
The MSVC-specific compile options to suppress warnings are correctly applied, helping to maintain clean build outputs.
77-80
: Approved
The include directories for minisketch
are correctly specified, ensuring proper header file access.
11-25
: Verify CLMUL support detection works correctly on MSVC
The check_cxx_source_compiles_with_flags
function may not correctly detect CLMUL support on MSVC because CLMUL_CXXFLAGS
is empty. Ensure that the necessary compiler flags are included for accurate detection of CLMUL support on MSVC.
Run the following script to verify CLMUL support detection on MSVC:
find . -exec touch -d "@$SOURCE_DATE_EPOCH" {} + | ||
fi | ||
|
||
find . | sort | "$1" -X@ "$2" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add input validation and error handling
The script assumes $1 (zip command) and $2 (exclusion pattern) are provided correctly. Consider adding validation and documentation.
+if [ $# -lt 2 ]; then
+ echo "Usage: $0 <zip_command> <exclusion_pattern>" >&2
+ exit 1
+fi
+
+if ! command -v "$1" >/dev/null 2>&1; then
+ echo "Error: Command '$1' not found" >&2
+ exit 1
+fi
+
find . | sort | "$1" -X@ "$2"
Also, consider adding error handling for the find and zip operations:
-find . | sort | "$1" -X@ "$2"
+set -e # Exit on error
+find . | sort | "$1" -X@ "$2" || {
+ echo "Error: Zip operation failed" >&2
+ exit 1
+}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
find . | sort | "$1" -X@ "$2" | |
if [ $# -lt 2 ]; then | |
echo "Usage: $0 <zip_command> <exclusion_pattern>" >&2 | |
exit 1 | |
fi | |
if ! command -v "$1" >/dev/null 2>&1; then | |
echo "Error: Command '$1' not found" >&2 | |
exit 1 | |
fi | |
set -e # Exit on error | |
find . | sort | "$1" -X@ "$2" || { | |
echo "Error: Zip operation failed" >&2 | |
exit 1 | |
} |
# Copyright (c) 2023-present The Bitcoin Core developers | ||
# Distributed under the MIT software license, see the accompanying | ||
# file COPYING or https://opensource.org/license/mit/. | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update copyright notice for Firo project
The copyright notice currently references Bitcoin Core developers. This should be updated to reflect Firo's ownership.
Apply this diff to update the copyright notice:
-# Copyright (c) 2023-present The Bitcoin Core developers
+# Copyright (c) 2023-present The Firo Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://opensource.org/license/mit/.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
# Copyright (c) 2023-present The Bitcoin Core developers | |
# Distributed under the MIT software license, see the accompanying | |
# file COPYING or https://opensource.org/license/mit/. | |
# Copyright (c) 2023-present The Firo Core developers | |
# Distributed under the MIT software license, see the accompanying | |
# file COPYING or https://opensource.org/license/mit/. | |
set(CLIENT_TARNAME "bitcoin") | ||
set(BITCOIN_GUI_NAME "bitcoin-qt") | ||
set(BITCOIN_DAEMON_NAME "bitcoind") | ||
set(BITCOIN_CLI_NAME "bitcoin-cli") | ||
set(BITCOIN_TX_NAME "bitcoin-tx") | ||
set(BITCOIN_WALLET_TOOL_NAME "bitcoin-wallet") | ||
set(BITCOIN_TEST_NAME "test_bitcoin") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Update Bitcoin-specific naming to match Firo project
The current implementation uses Bitcoin-specific naming which is incorrect for the Firo project. This could lead to incorrect installer generation and confusion.
Apply this diff to update the naming:
- set(CLIENT_TARNAME "bitcoin")
- set(BITCOIN_GUI_NAME "bitcoin-qt")
- set(BITCOIN_DAEMON_NAME "bitcoind")
- set(BITCOIN_CLI_NAME "bitcoin-cli")
- set(BITCOIN_TX_NAME "bitcoin-tx")
- set(BITCOIN_WALLET_TOOL_NAME "bitcoin-wallet")
- set(BITCOIN_TEST_NAME "test_bitcoin")
+ set(CLIENT_TARNAME "firo")
+ set(FIRO_GUI_NAME "firo-qt")
+ set(FIRO_DAEMON_NAME "firod")
+ set(FIRO_CLI_NAME "firo-cli")
+ set(FIRO_TX_NAME "firo-tx")
+ set(FIRO_WALLET_TOOL_NAME "firo-wallet")
+ set(FIRO_TEST_NAME "test_firo")
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
set(CLIENT_TARNAME "bitcoin") | |
set(BITCOIN_GUI_NAME "bitcoin-qt") | |
set(BITCOIN_DAEMON_NAME "bitcoind") | |
set(BITCOIN_CLI_NAME "bitcoin-cli") | |
set(BITCOIN_TX_NAME "bitcoin-tx") | |
set(BITCOIN_WALLET_TOOL_NAME "bitcoin-wallet") | |
set(BITCOIN_TEST_NAME "test_bitcoin") | |
set(CLIENT_TARNAME "firo") | |
set(FIRO_GUI_NAME "firo-qt") | |
set(FIRO_DAEMON_NAME "firod") | |
set(FIRO_CLI_NAME "firo-cli") | |
set(FIRO_TX_NAME "firo-tx") | |
set(FIRO_WALLET_TOOL_NAME "firo-wallet") | |
set(FIRO_TEST_NAME "test_firo") |
function(generate_setup_nsi) | ||
set(abs_top_srcdir ${PROJECT_SOURCE_DIR}) | ||
set(abs_top_builddir ${PROJECT_BINARY_DIR}) | ||
set(CLIENT_URL ${PROJECT_HOMEPAGE_URL}) | ||
set(CLIENT_TARNAME "bitcoin") | ||
set(BITCOIN_GUI_NAME "bitcoin-qt") | ||
set(BITCOIN_DAEMON_NAME "bitcoind") | ||
set(BITCOIN_CLI_NAME "bitcoin-cli") | ||
set(BITCOIN_TX_NAME "bitcoin-tx") | ||
set(BITCOIN_WALLET_TOOL_NAME "bitcoin-wallet") | ||
set(BITCOIN_TEST_NAME "test_bitcoin") | ||
set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX}) | ||
configure_file(${PROJECT_SOURCE_DIR}/share/setup.nsi.in ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.nsi USE_SOURCE_PERMISSIONS @ONLY) | ||
endfunction() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve reusability by parameterizing the function
The function currently uses hardcoded values which limits its reusability. Consider parameterizing the function to make it more flexible.
Here's a suggested refactor:
-function(generate_setup_nsi)
+function(generate_setup_nsi
+ CLIENT_NAME
+ GUI_NAME
+ DAEMON_NAME
+ CLI_NAME
+ TX_NAME
+ WALLET_TOOL_NAME
+ TEST_NAME
+ HOMEPAGE_URL)
set(abs_top_srcdir ${PROJECT_SOURCE_DIR})
set(abs_top_builddir ${PROJECT_BINARY_DIR})
- set(CLIENT_URL ${PROJECT_HOMEPAGE_URL})
- set(CLIENT_TARNAME "bitcoin")
- set(BITCOIN_GUI_NAME "bitcoin-qt")
- set(BITCOIN_DAEMON_NAME "bitcoind")
- set(BITCOIN_CLI_NAME "bitcoin-cli")
- set(BITCOIN_TX_NAME "bitcoin-tx")
- set(BITCOIN_WALLET_TOOL_NAME "bitcoin-wallet")
- set(BITCOIN_TEST_NAME "test_bitcoin")
+ set(CLIENT_URL ${HOMEPAGE_URL})
+ set(CLIENT_TARNAME ${CLIENT_NAME})
+ set(GUI_NAME ${GUI_NAME})
+ set(DAEMON_NAME ${DAEMON_NAME})
+ set(CLI_NAME ${CLI_NAME})
+ set(TX_NAME ${TX_NAME})
+ set(WALLET_TOOL_NAME ${WALLET_TOOL_NAME})
+ set(TEST_NAME ${TEST_NAME})
set(EXEEXT ${CMAKE_EXECUTABLE_SUFFIX})
- configure_file(${PROJECT_SOURCE_DIR}/share/setup.nsi.in ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.nsi USE_SOURCE_PERMISSIONS @ONLY)
+ configure_file(${PROJECT_SOURCE_DIR}/share/setup.nsi.in ${PROJECT_BINARY_DIR}/${CLIENT_NAME}-win64-setup.nsi USE_SOURCE_PERMISSIONS @ONLY)
endfunction()
Committable suggestion skipped: line range outside the PR's diff.
if(USDT_FOUND AND NOT TARGET USDT::headers) | ||
add_library(USDT::headers INTERFACE IMPORTED) | ||
set_target_properties(USDT::headers PROPERTIES | ||
INTERFACE_INCLUDE_DIRECTORIES "${USDT_INCLUDE_DIR}" | ||
) | ||
set(ENABLE_TRACING TRUE) | ||
endif() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve target properties and variable scope.
Consider the following improvements:
- Add scope specifier for ENABLE_TRACING
- Set compile definitions for the target:
if(USDT_FOUND AND NOT TARGET USDT::headers)
add_library(USDT::headers INTERFACE IMPORTED)
set_target_properties(USDT::headers PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${USDT_INCLUDE_DIR}"
+ INTERFACE_COMPILE_DEFINITIONS "SDT_USE_VARIADIC=1"
)
- set(ENABLE_TRACING TRUE)
+ set(ENABLE_TRACING TRUE CACHE BOOL "Enable USDT tracing support" FORCE)
endif()
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if(USDT_FOUND AND NOT TARGET USDT::headers) | |
add_library(USDT::headers INTERFACE IMPORTED) | |
set_target_properties(USDT::headers PROPERTIES | |
INTERFACE_INCLUDE_DIRECTORIES "${USDT_INCLUDE_DIR}" | |
) | |
set(ENABLE_TRACING TRUE) | |
endif() | |
if(USDT_FOUND AND NOT TARGET USDT::headers) | |
add_library(USDT::headers INTERFACE IMPORTED) | |
set_target_properties(USDT::headers PROPERTIES | |
INTERFACE_INCLUDE_DIRECTORIES "${USDT_INCLUDE_DIR}" | |
INTERFACE_COMPILE_DEFINITIONS "SDT_USE_VARIADIC=1" | |
) | |
set(ENABLE_TRACING TRUE CACHE BOOL "Enable USDT tracing support" FORCE) | |
endif() |
set(macos_app "Bitcoin-Qt.app") | ||
# Populate Contents subdirectory. | ||
configure_file(${PROJECT_SOURCE_DIR}/share/qt/Info.plist.in ${macos_app}/Contents/Info.plist NO_SOURCE_PERMISSIONS) | ||
file(CONFIGURE OUTPUT ${macos_app}/Contents/PkgInfo CONTENT "APPL????") | ||
# Populate Contents/Resources subdirectory. | ||
file(CONFIGURE OUTPUT ${macos_app}/Contents/Resources/empty.lproj CONTENT "") | ||
configure_file(${PROJECT_SOURCE_DIR}/src/qt/res/icons/bitcoin.icns ${macos_app}/Contents/Resources/bitcoin.icns NO_SOURCE_PERMISSIONS COPYONLY) | ||
file(CONFIGURE OUTPUT ${macos_app}/Contents/Resources/Base.lproj/InfoPlist.strings | ||
CONTENT "{ CFBundleDisplayName = \"@CLIENT_NAME@\"; CFBundleName = \"@CLIENT_NAME@\"; }" | ||
) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update macOS application references from "Bitcoin-Qt.app" to "Firo-Qt.app"
The macOS deployment function uses hard-coded application names and icon files specific to Bitcoin. Please update macos_app
to "Firo-Qt.app" and replace "bitcoin.icns" with Firo's icon file.
Suggested changes:
- set(macos_app "Bitcoin-Qt.app")
+ set(macos_app "Firo-Qt.app")
...
- configure_file(${PROJECT_SOURCE_DIR}/src/qt/res/icons/bitcoin.icns ${macos_app}/Contents/Resources/bitcoin.icns NO_SOURCE_PERMISSIONS COPYONLY)
+ configure_file(${PROJECT_SOURCE_DIR}/src/qt/res/icons/firo.icns ${macos_app}/Contents/Resources/firo.icns NO_SOURCE_PERMISSIONS COPYONLY)
Ensure that the icon file firo.icns
exists in the specified location.
Committable suggestion skipped: line range outside the PR's diff.
OUTPUT ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.exe | ||
COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/release | ||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-qt> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-qt> | ||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoind> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoind> | ||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-cli> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-cli> | ||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-tx> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-tx> | ||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-wallet> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-wallet> | ||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-util> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-util> | ||
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:test_bitcoin> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:test_bitcoin> | ||
COMMAND makensis -V2 ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.nsi | ||
VERBATIM | ||
) | ||
add_custom_target(deploy DEPENDS ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.exe) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Replace hard-coded "bitcoin" references with "firo" in Windows deployment
The Windows deployment commands use hard-coded "bitcoin" in filenames and paths. Please update these references to "firo" to align with the project's name.
Apply this diff to update the filenames and paths:
- OUTPUT ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.exe
+ OUTPUT ${PROJECT_BINARY_DIR}/firo-win64-setup.exe
...
- COMMAND makensis -V2 ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.nsi
+ COMMAND makensis -V2 ${PROJECT_BINARY_DIR}/firo-win64-setup.nsi
...
- add_custom_target(deploy DEPENDS ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.exe)
+ add_custom_target(deploy DEPENDS ${PROJECT_BINARY_DIR}/firo-win64-setup.exe)
Also, update the target file names in the strip commands:
- COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-qt> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-qt>
+ COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-qt> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-qt>
- COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoind> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoind>
+ COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firod> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firod>
- COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-cli> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-cli>
+ COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-cli> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-cli>
- COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-tx> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-tx>
+ COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-tx> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-tx>
- COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-wallet> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-wallet>
+ COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-wallet> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-wallet>
- COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-util> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-util>
+ COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-util> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-util>
- COMMAND ${CMAKE_STRIP} $<TARGET_FILE:test_bitcoin> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:test_bitcoin>
+ COMMAND ${CMAKE_STRIP} $<TARGET_FILE:test_firo> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:test_firo>
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
OUTPUT ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.exe | |
COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/release | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-qt> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-qt> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoind> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoind> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-cli> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-cli> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-tx> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-tx> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-wallet> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-wallet> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:bitcoin-util> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:bitcoin-util> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:test_bitcoin> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:test_bitcoin> | |
COMMAND makensis -V2 ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.nsi | |
VERBATIM | |
) | |
add_custom_target(deploy DEPENDS ${PROJECT_BINARY_DIR}/bitcoin-win64-setup.exe) | |
OUTPUT ${PROJECT_BINARY_DIR}/firo-win64-setup.exe | |
COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/release | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-qt> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-qt> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firod> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firod> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-cli> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-cli> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-tx> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-tx> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-wallet> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-wallet> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:firo-util> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:firo-util> | |
COMMAND ${CMAKE_STRIP} $<TARGET_FILE:test_firo> -o ${PROJECT_BINARY_DIR}/release/$<TARGET_FILE_NAME:test_firo> | |
COMMAND makensis -V2 ${PROJECT_BINARY_DIR}/firo-win64-setup.nsi | |
VERBATIM | |
) | |
add_custom_target(deploy DEPENDS ${PROJECT_BINARY_DIR}/firo-win64-setup.exe) |
target_link_libraries(minisketch | ||
PRIVATE | ||
core_interface | ||
minisketch_common | ||
$<TARGET_NAME_IF_EXISTS:minisketch_clmul> | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct the generator expression for optional target linking
The generator expression $<TARGET_NAME_IF_EXISTS:minisketch_clmul>
is not valid in CMake. To conditionally link minisketch_clmul
if it exists, use the following correct expression:
$<$<TARGET_EXISTS:minisketch_clmul>:minisketch_clmul>
Apply the following diff to fix the generator expression:
target_link_libraries(minisketch
PRIVATE
core_interface
minisketch_common
- $<TARGET_NAME_IF_EXISTS:minisketch_clmul>
+ $<$<TARGET_EXISTS:minisketch_clmul>:minisketch_clmul>
)
set_target_properties(minisketch_clmul PROPERTIES | ||
EXPORT_COMPILE_COMMANDS OFF | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
EXPORT_COMPILE_COMMANDS
is not a valid target property
Setting EXPORT_COMPILE_COMMANDS
on targets (minisketch_clmul
and minisketch
) will have no effect because it's a directory-level property, not a target-level property. Consider removing these settings or adjusting them at the directory level if needed.
Apply the following change:
# For minisketch_clmul
set_target_properties(minisketch_clmul PROPERTIES
- EXPORT_COMPILE_COMMANDS OFF
)
# For minisketch
set_target_properties(minisketch PROPERTIES
- EXPORT_COMPILE_COMMANDS OFF
)
Also applies to: 89-91
if(MSVC) | ||
set(CLMUL_CXXFLAGS) | ||
else() | ||
set(CLMUL_CXXFLAGS -mpclmul) | ||
endif() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ensure CLMUL compiler flags are correctly set for MSVC
When using MSVC, CLMUL_CXXFLAGS
is left empty, which may not enable CLMUL instruction support. To properly enable CLMUL support on MSVC, you might need to set the appropriate compiler flag /arch:AVX
or /arch:AVX2
.
Apply the following change to set the correct compiler flags for MSVC:
if(MSVC)
- set(CLMUL_CXXFLAGS)
+ set(CLMUL_CXXFLAGS /arch:AVX)
else()
set(CLMUL_CXXFLAGS -mpclmul)
endif()
Committable suggestion skipped: line range outside the PR's diff.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
src/bench/bench.h (1)
Line range hint
1-89
: Consider adding runtime assertions for time/cycle comparisonsWhile the initialization using
std::numeric_limits
is correct, it would be beneficial to add runtime assertions in the benchmarking logic to ensure thatminTime <= maxTime
andminCycles <= maxCycles
always holds true after measurements.Example addition:
bool State::KeepRunning() { // ... existing code ... assert(minTime <= maxTime && "Time invariant violated"); assert(minCycles <= maxCycles && "Cycles invariant violated"); // ... rest of the code ... }src/bench/CMakeLists.txt (2)
5-6
: Document the purpose of block413567.raw data file.While the code correctly generates a header from the raw block data, it would be helpful to add a comment explaining why this specific block was chosen for benchmarking and what test scenarios it covers.
41-43
: Consider expanding test configurations and documentation.While the basic sanity check is good, consider:
- Documenting what the sanity check validates
- Adding tests with different priority levels
- Including additional benchmark-specific test configurations
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/bench/CMakeLists.txt
(1 hunks)src/bench/bench.h
(1 hunks)
🔇 Additional comments (5)
src/bench/bench.h (1)
10-10
: LGTM! Good practice using std::numeric_limits
The addition of <limits>
and the use of std::numeric_limits
for initializing min/max values is a robust approach, providing type-safe extreme values for the benchmarking metrics.
src/bench/CMakeLists.txt (4)
8-24
: LGTM! Well-organized benchmark executable definition.
The benchmark sources are clearly organized and include comprehensive test coverage for various components (crypto, mempool, script verification, etc.).
33-39
: LGTM! Clean wallet integration.
The wallet-specific benchmarks are properly isolated behind the ENABLE_WALLET flag, following CMake best practices.
45-47
: LGTM! Proper installation configuration.
The installation setup follows CMake best practices using CMAKE_INSTALL_BINDIR.
26-31
: Verify benchmark dependencies completeness.
Please ensure all required dependencies are included for the benchmarks, particularly for crypto operations and script verification.
✅ Verification successful
Let me analyze the benchmark dependencies based on the file search results and generate additional verification scripts to check the actual usage of libraries in the benchmark code.
Let's examine the actual content of these benchmark files to verify the dependencies.
Let's check the content of bench.h and look for any additional benchmark files that might show the dependency usage.
Based on the comprehensive analysis of the benchmark files and CMakeLists.txt, I can now provide a final response about the dependencies.
Dependencies are correctly configured for benchmarks.
The current dependencies are appropriate and complete for the following reasons:
core_interface
: Required for core functionality used across benchmarks (crypto, validation, etc.)test_util
: Needed for testing utilities and fixturesfiro_node
: Required for node-level functionality being benchmarkedBoost::headers
: Used directly in bench.h for boost::function and preprocessor macros- Optional
firo_wallet
dependency when ENABLE_WALLET is set
The benchmark files (*.cpp) cover various aspects like crypto operations, script verification, mempool, and wallet functionality, and all their dependencies are properly captured by these library linkages.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for library dependencies in benchmark source files
echo "Searching for potential missing dependencies in benchmark sources..."
rg -l "using namespace|#include" bench_bitcoin.cpp bench.cpp base58.cpp ccoins_caching.cpp checkblock.cpp checkqueue.cpp crypto_hash.cpp Examples.cpp lockedpool.cpp mempool_eviction.cpp perf.cpp rollingbloom.cpp verify_script.cpp | xargs rg "using namespace|#include"
Length of output: 74541
Script:
#!/bin/bash
# Search for benchmark source files to analyze their dependencies
echo "Searching for benchmark source files..."
fd -t f "bench_.*\.cpp$|bench.*\.cpp$" src/bench/
# Search for actual library usage in benchmark files
echo -e "\nSearching for library usage in benchmark files..."
fd -t f "bench_.*\.cpp$|bench.*\.cpp$" src/bench/ -x rg -l "using |#include|BOOST_|core_interface|test_util|firo_node"
Length of output: 472
Script:
#!/bin/bash
# Check the content of benchmark files for dependencies
echo "Content of bench.cpp:"
cat src/bench/bench.cpp
echo -e "\nContent of bench_bitcoin.cpp:"
cat src/bench/bench_bitcoin.cpp
# Also check for any other benchmark-related files that might show dependency usage
echo -e "\nChecking for other benchmark-related files:"
fd -t f ".*bench.*" src/bench/ -x rg -l "core_interface|test_util|firo_node|boost"
Length of output: 4485
Script:
#!/bin/bash
# Check the content of bench.h
echo "Content of bench.h:"
cat src/bench/bench.h
# Look for all files in bench directory
echo -e "\nAll files in bench directory:"
ls -la src/bench/
# Check CMakeLists.txt in bench directory for target dependencies
echo -e "\nContent of CMakeLists.txt in bench directory:"
cat src/bench/CMakeLists.txt
Length of output: 5030
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
CMakeLists.txt (4)
90-106
: Good BDB version check, but consider strengthening the warning.The Berkeley DB version check is crucial for wallet compatibility. Consider making this warning more prominent or failing the build when using an incompatible version in production builds.
if(NOT BerkeleyDB_VERSION VERSION_EQUAL 4.8) - message(WARNING "Found Berkeley DB (BDB) other than 4.8.\n" - "BDB (legacy) wallets opened by this build will not be portable!" + if(CMAKE_BUILD_TYPE STREQUAL "Release") + message(FATAL_ERROR "Production builds must use Berkeley DB 4.8 for wallet compatibility") + else() + message(WARNING "WARNING: Found Berkeley DB (BDB) other than 4.8\n" + "WARNING: BDB (legacy) wallets opened by this build will not be portable!\n" + "WARNING: This could lead to permanent wallet corruption in production.") + endif()
430-488
: Consider additional modern hardening flags.While the current hardening flags are good, consider adding these modern security options:
- Control-flow integrity for supported compilers
- Memory tagging for ARM64
if(ENABLE_HARDENING) + # Add Control-flow integrity for Clang + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + try_append_cxx_flags("-fsanitize=cfi" TARGET hardening_interface) + endif() + + # Add Memory tagging for ARM64 + if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64") + try_append_cxx_flags("-fsanitize=memtag" TARGET hardening_interface) + endif()
540-546
: Track TODO for RPATH configuration.The TODO comment indicates that RPATH settings need to be revisited after reordering Guix script commands.
Would you like me to create a GitHub issue to track this TODO for future cleanup?
564-612
: Enhance configuration summary with system information.Consider adding more system information to the configuration summary for better build reproducibility:
message("Configure summary") message("=================") +message("System information:") +message(" OS .............................. ${CMAKE_SYSTEM_NAME}") +message(" Architecture .................... ${CMAKE_SYSTEM_PROCESSOR}") +message(" Compiler features:") +message(" C++ standard .................. ${CMAKE_CXX_STANDARD}") +message(" Sanitizers .................... ${SANITIZERS}") message("Executables:")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
CMakeLists.txt
(1 hunks)
🔇 Additional comments (2)
CMakeLists.txt (2)
1-58
: LGTM! Well-structured project setup.
The basic project configuration follows CMake best practices:
- Appropriate minimum CMake version with justification
- Prevention of in-source builds
- Clear version and metadata management
59-71
: Verify C++20 support across target platforms.
While C++20 is set as the standard, we should verify compatibility across all target platforms and toolchains.
✅ Verification successful
Let me analyze the search results and generate a final response.
C++20 support appears to be properly configured and safe to use
The codebase shows no usage of advanced C++20 features that might cause compatibility issues. The configuration is properly set up with:
- Explicit C++20 requirement via
CMAKE_CXX_STANDARD 20
- Required standard enforcement via
CMAKE_CXX_STANDARD_REQUIRED ON
- Extensions disabled via
CMAKE_CXX_EXTENSIONS OFF
The code appears to use basic C++ features that are widely supported across modern compilers. No C++20-specific features like concepts, coroutines, ranges, or modules were found in the codebase.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check C++20 feature support across configured compilers
# Test: Look for C++20 feature usage that might cause issues
rg -A 3 "\\[\[likely\\]\\]|\\[\[unlikely\\]\\]|concept|requires|co_await|ranges::|views::|<span>|<concepts>|format"
Length of output: 65899
c49ada0
to
3245d44
Compare
3245d44
to
07e7b50
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
♻️ Duplicate comments (7)
cmake/module/ProcessConfigurations.cmake (1)
123-129
:⚠️ Potential issueDefine core_interface_debug target before use
The target
core_interface_debug
is used before being defined. This will cause CMake configuration errors.Add this before line 123:
add_library(core_interface_debug INTERFACE)cmake/module/TestAppendRequiredLibraries.cmake (1)
38-39
:⚠️ Potential issueFix unconditional setting of HAVE_DECL variables
The variables should only be set when the functions are actually available.
- set(HAVE_DECL_GETIFADDRS TRUE PARENT_SCOPE) - set(HAVE_DECL_FREEIFADDRS TRUE PARENT_SCOPE) + if(IFADDR_LINKS_WITHOUT_LIBSOCKET OR IFADDR_NEEDS_LINK_TO_LIBSOCKET) + set(HAVE_DECL_GETIFADDRS TRUE PARENT_SCOPE) + set(HAVE_DECL_FREEIFADDRS TRUE PARENT_SCOPE) + endif()cmake/crc32c.cmake (2)
45-61
:⚠️ Potential issueReplace non-standard CMake function with standard alternatives
The
check_cxx_source_compiles_with_flags
is not a standard CMake function. Usecheck_cxx_source_compiles
withCMAKE_REQUIRED_FLAGS
instead.Also applies to: 65-79
83-85
:⚠️ Potential issueFix undefined variables in compile definitions
The following variables are used but not defined:
- HAVE_STRONG_GETAUXVAL
- CMAKE_CXX_BYTE_ORDER
This could lead to incorrect compile-time configurations.
cmake/introspection.cmake (3)
1-3
:⚠️ Potential issueUpdate project attribution and license URL
The file header needs to be updated to reflect the Firo project and correct MIT license URL.
11-11
:⚠️ Potential issueFix incorrect header file name
The header file
sys/resources.h
should besys/resource.h
.
163-227
:⚠️ Potential issueReplace non-standard CMake functions and improve SIMD detection
The SIMD detection code uses non-standard CMake functions and could be improved.
🧹 Nitpick comments (16)
cmake/module/FindQRencode.cmake (5)
1-15
: Update copyright notice and enhance documentationThe copyright notice should be updated to reflect the Firo project. Additionally, consider enhancing the documentation with:
- Required and optional dependencies
- Usage example
- Expected variables set by the module
Apply this diff:
-# Copyright (c) 2024-present The Bitcoin Core developers +# Copyright (c) 2024-present The Firo Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or https://opensource.org/license/mit/. #[=======================================================================[ FindQRencode ------------ Finds the QRencode header and library. +Result Variables: + QRencode_FOUND - System has QRencode + QRencode_INCLUDE_DIR - QRencode include directories + QRencode_LIBRARY - QRencode library + QRencode_VERSION - QRencode version string + +Imported Targets: + QRencode::QRencode - Imported target for using QRencode + +Example Usage: + find_package(QRencode REQUIRED) + target_link_libraries(myapp PRIVATE QRencode::QRencode) This is a wrapper around find_package()/pkg_check_modules() commands that: - facilitates searching in various build environments - prints a standard log message
17-34
: Add Windows-specific search pathsThe current implementation might miss QRencode installations on Windows. Consider adding Windows-specific search paths.
Apply this diff:
find_path(QRencode_INCLUDE_DIR NAMES qrencode.h - PATHS ${PC_QRencode_INCLUDE_DIRS} + PATHS + ${PC_QRencode_INCLUDE_DIRS} + "$ENV{PROGRAMFILES}/qrencode/include" + "$ENV{PROGRAMFILES\(X86\)}/qrencode/include" ) find_library(QRencode_LIBRARY_RELEASE NAMES qrencode - PATHS ${PC_QRencode_LIBRARY_DIRS} + PATHS + ${PC_QRencode_LIBRARY_DIRS} + "$ENV{PROGRAMFILES}/qrencode/lib" + "$ENV{PROGRAMFILES\(X86\)}/qrencode/lib" )
38-42
: Consider adding minimum version requirementTo ensure compatibility, consider adding a minimum version requirement for QRencode.
Apply this diff:
find_package_handle_standard_args(QRencode REQUIRED_VARS QRencode_LIBRARY QRencode_INCLUDE_DIR VERSION_VAR PC_QRencode_VERSION + FAIL_MESSAGE "QRencode >= 4.0.0 not found" ) +if(QRencode_FOUND AND PC_QRencode_VERSION VERSION_LESS "4.0.0") + message(FATAL_ERROR "QRencode version >= 4.0.0 is required") +endif()
44-67
: Add system libraries handlingConsider adding support for system libraries that QRencode might depend on.
Apply this diff:
set_target_properties(QRencode::QRencode PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${QRencode_INCLUDE_DIR}" ) + if(PC_QRencode_LIBRARIES) + set_target_properties(QRencode::QRencode PROPERTIES + INTERFACE_LINK_LIBRARIES "${PC_QRencode_LIBRARIES}" + ) + endif() endif()
69-71
: Mark additional variables as advancedConsider marking library-related variables as advanced to clean up the CMake GUI.
Apply this diff:
mark_as_advanced( QRencode_INCLUDE_DIR + QRencode_LIBRARY + QRencode_LIBRARY_RELEASE + QRencode_LIBRARY_DEBUG )cmake/module/Maintenance.cmake (1)
70-72
: Consider implementing the CPack NSIS Generator suggestionThe TODO comment suggests using CPack NSIS Generator. This would be a valuable improvement as it:
- Provides better integration with CMake
- Reduces maintenance overhead
- Offers more standardized packaging options
Would you like assistance in implementing this change?
cmake/module/TestAppendRequiredLibraries.cmake (2)
35-35
: Enhance error message with troubleshooting hintsThe current error message could be more helpful by suggesting potential solutions.
- message(FATAL_ERROR "Cannot figure out how to use getifaddrs/freeifaddrs.") + message(FATAL_ERROR "Cannot figure out how to use getifaddrs/freeifaddrs. Ensure development packages for networking libraries are installed (e.g., libc6-dev on Debian/Ubuntu).")
53-78
: Consider organizing test cases into separate functionsThe test code combines multiple atomic operation tests in a single function. Consider splitting them for better maintainability and clearer failure diagnosis.
set(check_atomic_source " #include <atomic> #include <cstdint> #include <chrono> + #include <cstdlib> using namespace std::chrono_literals; + bool test_bool_atomic() { + std::atomic<bool> lock{true}; + return lock.exchange(false); + } + + bool test_chrono_atomic() { + std::atomic<std::chrono::seconds> t{0s}; + t.store(2s); + auto t1 = t.load(); + return t.compare_exchange_strong(t1, 3s); + } + + bool test_floating_atomic() { + std::atomic<double> d{}; + d.store(3.14); + return d.load() == 3.14; + } + + bool test_integer_atomic() { + std::atomic<int64_t> a{}; + int64_t v = 5; + return a.fetch_add(v) == 0; + } int main() { - std::atomic<bool> lock{true}; - lock.exchange(false); - - std::atomic<std::chrono::seconds> t{0s}; - t.store(2s); - auto t1 = t.load(); - t.compare_exchange_strong(t1, 3s); - - std::atomic<double> d{}; - d.store(3.14); - auto d1 = d.load(); - - std::atomic<int64_t> a{}; - int64_t v = 5; - int64_t r = a.fetch_add(v); - return static_cast<int>(r); + return (test_bool_atomic() && + test_chrono_atomic() && + test_floating_atomic() && + test_integer_atomic()) ? EXIT_SUCCESS : EXIT_FAILURE; } ")cmake/bitcoin-build-config.h.in (3)
32-53
: Verify feature flags match Firo's requirementsPlease ensure these feature flags align with Firo's needs:
- CPU optimizations (ARM SHA-NI, AVX2, SSE4.1, x86 SHA-NI)
- External signer support
- Wallet functionality
- Tracing capabilities
Consider adding Firo-specific features like:
- Lelantus protocol support
- Sigma protocol support
- Dandelion++ protocol support
54-122
: Review and optimize system capability checksThe current set of system checks is inherited from Bitcoin Core. Consider:
- Removing checks for unused features
- Adding checks specific to Firo's requirements
- Documenting why each check is needed
For example, if Firo doesn't use DBus, the related checks could be removed.
135-150
: Review and update build options for FiroPlease verify:
- If BDB is still needed or if it can be replaced with a more modern alternative
- If DBus support is required for Firo
- If QR code support is needed
- If SQLite support is required
Consider adding Firo-specific build options for:
- Privacy protocol implementations
- Network protocol features
- GUI wallet features
doc/CMakeLists.txt (1)
11-14
: Consider tracking the TODO as a GitHub issueThe TODO comment mentions a potential improvement using CMake 3.27's
doxygen_add_docs()
command. This should be tracked for future enhancement.Would you like me to create a GitHub issue to track this improvement task?
CMakeLists.txt (4)
67-70
: Document C++20 requirement rationale.While C++20 is a good choice, it would be helpful to document why this specific version is required, as it might limit compatibility with older compilers and systems.
430-488
: Enhance security hardening flags.Consider adding these modern security features:
- Control-flow integrity for supported compilers
- Additional ARM-specific security features
if(ENABLE_HARDENING) add_library(hardening_interface INTERFACE) target_link_libraries(core_interface INTERFACE hardening_interface) if(MSVC) + # Enable Control Flow Guard + try_append_cxx_flags("/guard:cf" TARGET hardening_interface) + try_append_linker_flag("/GUARD:CF" TARGET hardening_interface) try_append_linker_flag("/DYNAMICBASE" TARGET hardening_interface) try_append_linker_flag("/HIGHENTROPYVA" TARGET hardening_interface) try_append_linker_flag("/NXCOMPAT" TARGET hardening_interface) else() + # Enable Intel Control-flow Enforcement Technology (CET) + try_append_cxx_flags("-fcf-protection=full" TARGET hardening_interface) + # For ARM64 if(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64") if(CMAKE_SYSTEM_NAME STREQUAL "Darwin") try_append_cxx_flags("-mbranch-protection=bti" TARGET hardening_interface SKIP_LINK) else() - try_append_cxx_flags("-mbranch-protection=standard" TARGET hardening_interface SKIP_LINK) + # Enable both BTI and PAC + try_append_cxx_flags("-mbranch-protection=pac-ret+bti" TARGET hardening_interface SKIP_LINK) endif() endif() endif() endif()
509-516
: Document Python version requirement.The minimum Python version (3.10) requirement should be documented with the rationale for choosing this specific version.
563-610
: Enhance build configuration summary.Consider adding estimated build time and disk space requirements to the configuration summary, especially helpful for first-time builders.
message("Configure summary") message("=================") +message("Build requirements:") +message(" Estimated build time ............... ${ESTIMATED_BUILD_TIME}") +message(" Required disk space ................ ${REQUIRED_DISK_SPACE}") +message("") message("Executables:")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (38)
CMakeLists.txt
(1 hunks)cmake/bitcoin-build-config.h.in
(1 hunks)cmake/ccache.cmake
(1 hunks)cmake/cov_tool_wrapper.sh.in
(1 hunks)cmake/crc32c.cmake
(1 hunks)cmake/introspection.cmake
(1 hunks)cmake/leveldb.cmake
(1 hunks)cmake/minisketch.cmake
(1 hunks)cmake/module/AddBoostIfNeeded.cmake
(1 hunks)cmake/module/AddWindowsResources.cmake
(1 hunks)cmake/module/CheckSourceCompilesAndLinks.cmake
(1 hunks)cmake/module/FindBerkeleyDB.cmake
(1 hunks)cmake/module/FindLibevent.cmake
(1 hunks)cmake/module/FindQRencode.cmake
(1 hunks)cmake/module/FindQt.cmake
(1 hunks)cmake/module/FindUSDT.cmake
(1 hunks)cmake/module/FindZeroMQ.cmake
(1 hunks)cmake/module/FlagsSummary.cmake
(1 hunks)cmake/module/GenerateHeaders.cmake
(1 hunks)cmake/module/GenerateSetupNsi.cmake
(1 hunks)cmake/module/GetTargetInterface.cmake
(1 hunks)cmake/module/Maintenance.cmake
(1 hunks)cmake/module/ProcessConfigurations.cmake
(1 hunks)cmake/module/TestAppendRequiredLibraries.cmake
(1 hunks)cmake/module/TryAppendCXXFlags.cmake
(1 hunks)cmake/module/TryAppendLinkerFlag.cmake
(1 hunks)cmake/module/WarnAboutGlobalProperties.cmake
(1 hunks)cmake/script/Coverage.cmake
(1 hunks)cmake/script/CoverageFuzz.cmake
(1 hunks)cmake/script/CoverageInclude.cmake.in
(1 hunks)cmake/script/GenerateBuildInfo.cmake
(1 hunks)cmake/script/GenerateHeaderFromJson.cmake
(1 hunks)cmake/script/GenerateHeaderFromRaw.cmake
(1 hunks)cmake/script/macos_zip.sh
(1 hunks)cmake/tests.cmake
(1 hunks)doc/CMakeLists.txt
(1 hunks)src/bench/CMakeLists.txt
(1 hunks)src/bench/bench.h
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (29)
- cmake/cov_tool_wrapper.sh.in
- cmake/module/AddWindowsResources.cmake
- src/bench/bench.h
- cmake/module/GenerateSetupNsi.cmake
- cmake/script/macos_zip.sh
- cmake/tests.cmake
- cmake/module/FindZeroMQ.cmake
- src/bench/CMakeLists.txt
- cmake/script/GenerateHeaderFromJson.cmake
- cmake/module/GenerateHeaders.cmake
- cmake/script/GenerateHeaderFromRaw.cmake
- cmake/module/FindLibevent.cmake
- cmake/script/CoverageInclude.cmake.in
- cmake/module/FlagsSummary.cmake
- cmake/script/GenerateBuildInfo.cmake
- cmake/leveldb.cmake
- cmake/module/AddBoostIfNeeded.cmake
- cmake/module/TryAppendLinkerFlag.cmake
- cmake/module/CheckSourceCompilesAndLinks.cmake
- cmake/module/FindUSDT.cmake
- cmake/module/WarnAboutGlobalProperties.cmake
- cmake/minisketch.cmake
- cmake/module/FindQt.cmake
- cmake/script/CoverageFuzz.cmake
- cmake/module/TryAppendCXXFlags.cmake
- cmake/module/FindBerkeleyDB.cmake
- cmake/module/GetTargetInterface.cmake
- cmake/ccache.cmake
- cmake/script/Coverage.cmake
🔇 Additional comments (24)
cmake/module/ProcessConfigurations.cmake (6)
1-8
: Specify minimum required CMake version
The script uses several CMake commands that require specific minimum versions:
IN_LIST
operator requires CMake 3.3+list(FILTER ...)
requires CMake 3.6+string(PREPEND ...)
requires CMake 3.2+
Add this at the beginning of the file:
cmake_minimum_required(VERSION 3.6)
9-12
: LGTM: String normalization implementation is clean and efficient
The macro effectively handles whitespace normalization using appropriate CMake string operations.
14-34
: LGTM: Well-implemented flag management functions
The implementation is particularly clever in deduplicate_flags
, using list reversal to preserve the last occurrence of duplicate flags while maintaining relative order.
37-90
: LGTM: Comprehensive configuration management implementation
Excellent implementation with:
- Proper handling of both single and multi-config generators
- Clear error messages and user feedback
- Thorough documentation explaining the functionality
92-118
: LGTM: Robust flag manipulation implementation
The functions effectively handle flag manipulation with proper cache variable management and regex-based replacement.
166-175
: LGTM: Well-implemented coverage configuration
Good implementation of coverage settings with:
- Appropriate compiler and linker flags
- Proper handling of multi-config generators
- Correct integration with existing configurations
cmake/module/FindQRencode.cmake (1)
35-37
: LGTM!
The library configuration selection is properly implemented using CMake's SelectLibraryConfigurations
module.
cmake/module/Maintenance.cmake (7)
1-3
: Update License Header to Reflect Firo Project
The license header refers to "The Bitcoin Core developers". Please update it to reflect the Firo project and its contributors.
7-19
: LGTM: Well-structured debug symbol configuration
The function correctly handles debug symbol splitting configuration with appropriate file permissions.
45-49
: Replace Bitcoin-specific targets with Firo equivalents
The list of targets includes Bitcoin-specific executables. Please update these to match Firo's executable names.
34-42
: LGTM: Well-documented compiler configuration
The compiler command construction is well-documented and properly handles complex compiler configurations.
69-87
: Replace hard-coded "bitcoin" references with "firo" in Windows deployment
The Windows deployment commands use hard-coded "bitcoin" in filenames and paths. Please update these references to "firo" to align with the project's name.
93-103
: Update macOS application references from "Bitcoin-Qt.app" to "Firo-Qt.app"
The macOS deployment function uses hard-coded application names and icon files specific to Bitcoin.
21-151
: Verify coverage of Firo-specific maintenance requirements
While the maintenance functions cover standard build and deployment tasks, please verify if there are any Firo-specific maintenance requirements that should be added.
✅ Verification successful
Based on the search results, I can now generate a final response since I have sufficient information about the maintenance scripts and TODOs in the codebase.
Maintenance targets are complete and well-structured for Firo
The current maintenance targets implementation is comprehensive and includes all necessary functionality for Firo:
- Security checks (security-check.py, symbol-check.py)
- Platform-specific deployment (Windows NSIS installer, macOS bundle)
- Development tools (optimization, formatting, documentation)
- Translation management (update-translations.py)
The only notable TODO is about potentially replacing the Windows NSIS installer code with CMake's CPack, which is an optimization rather than a missing requirement.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for existing maintenance scripts in the codebase
echo "Searching for existing maintenance scripts..."
fd -e sh -e py --full-path "contrib/(devtools|macdeploy)" -x echo "Found maintenance script: {}"
# Search for TODO/FIXME comments related to maintenance
echo -e "\nSearching for maintenance-related TODOs..."
rg -i "todo|fixme|hack|xxx" -g "contrib/**" -g "cmake/**"
Length of output: 3154
cmake/module/TestAppendRequiredLibraries.cmake (2)
1-6
: LGTM! Well-structured module header
The file follows CMake best practices with proper copyright notice, license information, and global include guard.
82-84
: LGTM! Efficient early return
Good practice to return early when no additional linking is required.
cmake/bitcoin-build-config.h.in (4)
1-7
: Update copyright and namespace for Firo project
The file header still contains Bitcoin Core references that need to be updated for the Firo project.
20-31
: Update copyright configuration for Firo
The copyright configuration needs to be updated with Firo-specific values in the CMakeLists.txt file:
COPYRIGHT_HOLDERS
should include Firo contributorsCOPYRIGHT_HOLDERS_FINAL
should reflect Firo's copyright noticeCOPYRIGHT_YEAR
should be updated to the current year
123-134
: Update package information with Firo details
Please update the following in CMakeLists.txt:
CLIENT_BUGREPORT
should point to Firo's issue trackerCLIENT_NAME
should be set to "Firo"CLIENT_URL
should point to Firo's homepageCLIENT_VERSION_STRING
should follow Firo's version format
8-19
: Verify version configuration matches Firo's versioning scheme
Please ensure these version macros align with Firo's versioning scheme and are properly configured in the root CMakeLists.txt file.
✅ Verification successful
Version configuration is properly defined and follows project standards
The version configuration in cmake/bitcoin-build-config.h.in
correctly maps to the version variables defined in the root CMakeLists.txt:
- MAJOR (0)
- MINOR (14)
- BUILD (0)
- IS_RELEASE (false)
These values align with Firo's versioning scheme as evidenced by:
- The project's latest release badge in README.md
- The standard semantic versioning structure (MAJOR.MINOR.BUILD)
- The proper configuration of version variables in the root CMakeLists.txt
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if version variables are defined in CMakeLists.txt
rg -A 1 "set\((CLIENT_VERSION_(BUILD|IS_RELEASE|MAJOR|MINOR))" CMakeLists.txt
Length of output: 255
Script:
#!/bin/bash
# Check for version information in other common locations
rg -l "version|Version" README.md CHANGELOG.md CONTRIBUTING.md docs/
Length of output: 179
Script:
#!/bin/bash
# Check git tags for version pattern
git tag | grep -E "v[0-9]+\.[0-9]+" | sort -V | tail -n 5
Length of output: 59
Script:
#!/bin/bash
# Look for any other version-related configuration
rg "version" -i --type cmake
Length of output: 10386
Script:
#!/bin/bash
# Check README.md for version information
cat README.md
Length of output: 9372
Script:
#!/bin/bash
# Look for any version-related files in the repository
fd -t f "version|VERSION"
Length of output: 478
doc/CMakeLists.txt (1)
15-20
: LGTM! Well-structured documentation target
The documentation target is well-configured with:
- Proper working directory setting
- Clear progress feedback via COMMENT
- Terminal output enabled for better visibility
cmake/crc32c.cmake (1)
81-92
: LGTM! Well-structured interface library
The crc32c_common
interface library is well-organized with clear compile definitions and dependencies.
cmake/introspection.cmake (1)
105-160
: LGTM! Well-structured OS randomness checks
The checks for various OS randomness sources are well-implemented with:
- Clear separation between different methods
- Proper error handling for Linux-specific cases
- Comprehensive coverage of different platforms
CMakeLists.txt (1)
1-58
: LGTM! Well-structured project setup.
The initial setup follows CMake best practices:
- Appropriate minimum CMake version with justification
- Prevention of in-source builds
- Comprehensive project metadata and versioning
set(check_socket_source " | ||
#include <sys/types.h> | ||
#include <ifaddrs.h> | ||
|
||
int main() { | ||
struct ifaddrs* ifaddr; | ||
getifaddrs(&ifaddr); | ||
freeifaddrs(ifaddr); | ||
} | ||
") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add error handling in the test code
The test code should check for NULL return from getifaddrs to ensure proper error handling.
set(check_socket_source "
#include <sys/types.h>
#include <ifaddrs.h>
+ #include <stdlib.h>
int main() {
struct ifaddrs* ifaddr;
- getifaddrs(&ifaddr);
+ if (getifaddrs(&ifaddr) == -1) {
+ return EXIT_FAILURE;
+ }
freeifaddrs(ifaddr);
+ return EXIT_SUCCESS;
}
")
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
set(check_socket_source " | |
#include <sys/types.h> | |
#include <ifaddrs.h> | |
int main() { | |
struct ifaddrs* ifaddr; | |
getifaddrs(&ifaddr); | |
freeifaddrs(ifaddr); | |
} | |
") | |
set(check_socket_source " | |
#include <sys/types.h> | |
#include <ifaddrs.h> | |
#include <stdlib.h> | |
int main() { | |
struct ifaddrs* ifaddr; | |
if (getifaddrs(&ifaddr) == -1) { | |
return EXIT_FAILURE; | |
} | |
freeifaddrs(ifaddr); | |
return EXIT_SUCCESS; | |
} | |
") |
if(WITH_BDB) | ||
find_package(BerkeleyDB 4.8 MODULE REQUIRED) | ||
set(USE_BDB ON) | ||
if(NOT BerkeleyDB_VERSION VERSION_EQUAL 4.8) | ||
message(WARNING "Found Berkeley DB (BDB) other than 4.8.\n" | ||
"BDB (legacy) wallets opened by this build will not be portable!" | ||
) | ||
if(WARN_INCOMPATIBLE_BDB) | ||
message(WARNING "If this is intended, pass \"-DWARN_INCOMPATIBLE_BDB=OFF\".\n" | ||
"Passing \"-DWITH_BDB=OFF\" will suppress this warning." | ||
) | ||
endif() | ||
endif() | ||
endif() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider stricter Berkeley DB version enforcement.
Currently, the build only warns about Berkeley DB version mismatches. Consider making this a hard error when the version is incompatible, as wallet compatibility issues could lead to serious problems.
if(WITH_BDB)
find_package(BerkeleyDB 4.8 MODULE REQUIRED)
set(USE_BDB ON)
if(NOT BerkeleyDB_VERSION VERSION_EQUAL 4.8)
- message(WARNING "Found Berkeley DB (BDB) other than 4.8.\n"
- "BDB (legacy) wallets opened by this build will not be portable!"
- )
- if(WARN_INCOMPATIBLE_BDB)
- message(WARNING "If this is intended, pass \"-DWARN_INCOMPATIBLE_BDB=OFF\".\n"
- "Passing \"-DWITH_BDB=OFF\" will suppress this warning."
- )
- endif()
+ if(NOT ALLOW_INCOMPATIBLE_BDB)
+ message(FATAL_ERROR "Found Berkeley DB (BDB) version ${BerkeleyDB_VERSION}, but version 4.8 is required.\n"
+ "BDB (legacy) wallets opened by this build will not be portable!\n"
+ "If you understand the risks, pass \"-DALLOW_INCOMPATIBLE_BDB=ON\" to proceed anyway."
+ )
+ else()
+ message(WARNING "Building with incompatible Berkeley DB version ${BerkeleyDB_VERSION}.\n"
+ "BDB (legacy) wallets opened by this build will not be portable!")
+ endif()
endif()
endif()
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if(WITH_BDB) | |
find_package(BerkeleyDB 4.8 MODULE REQUIRED) | |
set(USE_BDB ON) | |
if(NOT BerkeleyDB_VERSION VERSION_EQUAL 4.8) | |
message(WARNING "Found Berkeley DB (BDB) other than 4.8.\n" | |
"BDB (legacy) wallets opened by this build will not be portable!" | |
) | |
if(WARN_INCOMPATIBLE_BDB) | |
message(WARNING "If this is intended, pass \"-DWARN_INCOMPATIBLE_BDB=OFF\".\n" | |
"Passing \"-DWITH_BDB=OFF\" will suppress this warning." | |
) | |
endif() | |
endif() | |
endif() | |
if(WITH_BDB) | |
find_package(BerkeleyDB 4.8 MODULE REQUIRED) | |
set(USE_BDB ON) | |
if(NOT BerkeleyDB_VERSION VERSION_EQUAL 4.8) | |
if(NOT ALLOW_INCOMPATIBLE_BDB) | |
message(FATAL_ERROR "Found Berkeley DB (BDB) version ${BerkeleyDB_VERSION}, but version 4.8 is required.\n" | |
"BDB (legacy) wallets opened by this build will not be portable!\n" | |
"If you understand the risks, pass \"-DALLOW_INCOMPATIBLE_BDB=ON\" to proceed anyway." | |
) | |
else() | |
message(WARNING "Building with incompatible Berkeley DB version ${BerkeleyDB_VERSION}.\n" | |
"BDB (legacy) wallets opened by this build will not be portable!") | |
endif() | |
endif() | |
endif() |
PR intention
This is mage PR containing development for CMake build system.
Status
Firo build graph:
Firo-build-tree.pdf
Phase 1
Internal libraries.
Phase 2
Required external libraries with
vcpkg
for Windows.Autogenerating
Toolchain.cmake
viadepends
.