span: diagnose dangling views from MakeByteSpan/MakeUCharSpan #36183

Open
kevkevinpal wants to merge 2 commits from span-lifetimebound-make-byte-uchar into master AGit
kevkevinpal commented 2026-09-07 14:35:44 +00:00 (Migrated from github.com)

Follow-up to #36164, as suggested in https://github.com/bitcoin/bitcoin/pull/36164#issuecomment-5541268260.

Tracked in https://github.com/kevkevinpal/bitcoin/issues/550.

Problem: MakeByteSpan and MakeUCharSpan return views into their input. A temporary container can leave those views dangling.

Fix: Add LIFETIMEBOUND to the overload taking non-borrowed_range types, so Clang diagnoses the misuse on owning containers without flagging correct code that passes a view. leveldb::Slice is opted into borrowed_range so dbwrapper can keep using the helper. Matching the util/string.h helpers from #36164.

Follow-up to #36164, as suggested in https://github.com/bitcoin/bitcoin/pull/36164#issuecomment-5541268260. Tracked in https://github.com/kevkevinpal/bitcoin/issues/550. **Problem:** `MakeByteSpan` and `MakeUCharSpan` return views into their input. A temporary container can leave those views dangling. **Fix:** Add `LIFETIMEBOUND` to the overload taking non-`borrowed_range` types, so Clang diagnoses the misuse on owning containers without flagging correct code that passes a view. `leveldb::Slice` is opted into `borrowed_range` so `dbwrapper` can keep using the helper. Matching the `util/string.h` helpers from #36164.
DrahtBot commented 2026-09-07 14:35:51 +00:00 (Migrated from github.com)

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

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK jeanpablojp

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #34132 (coins,dbwrapper: make database point-read failures fatal by l0rinc)

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

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36183 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36183.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36183#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [jeanpablojp](https://github.com/bitcoin/bitcoin/pull/36183#pullrequestreview-5135551506) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#34132](https://github.com/bitcoin/bitcoin/pull/34132) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34132.svg"></sub> (coins,dbwrapper: make database point-read failures fatal by l0rinc) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
jeanpablojp (Migrated from github.com) reviewed 2026-09-07 22:31:02 +00:00
jeanpablojp (Migrated from github.com) left a comment

Concept ACK

LIFETIMEBOUND on const V& claims the result borrows from v. True when V owns the bytes, false when V is a non-owning view, and MakeByteSpan takes both, so the annotation also fires on correct code. The four warnings this diff works around are all that case.

It also reaches a shape outside the diff, where a function returning MakeByteSpan of a local std::span or std::string_view now gets -Wreturn-stack-address.

Would a requires (!std::ranges::borrowed_range<V>) on the annotated overload work? Compiled both ways here, the constrained form keeps the temporary-container warning and drops the two in net_tests. leveldb::Slice is not a borrowed range, so dbwrapper needs its own handling regardless.

Concept ACK `LIFETIMEBOUND` on `const V&` claims the result borrows from `v`. True when `V` owns the bytes, false when `V` is a non-owning view, and `MakeByteSpan` takes both, so the annotation also fires on correct code. The four warnings this diff works around are all that case. It also reaches a shape outside the diff, where a function returning `MakeByteSpan` of a local `std::span` or `std::string_view` now gets `-Wreturn-stack-address`. Would a `requires (!std::ranges::borrowed_range<V>)` on the annotated overload work? Compiled both ways here, the constrained form keeps the temporary-container warning and drops the two in `net_tests`. `leveldb::Slice` is not a borrowed range, so `dbwrapper` needs its own handling regardless.
jeanpablojp (Migrated from github.com) commented 2026-09-07 22:31:02 +00:00

Neither form keeps the helper here. MakeByteSpan(m_impl_iter->iter->key()) warns because the Slice is a temporary, and binding it to a local only changes the warning to "address of stack memory associated with local variable 'key' returned".

Would opting the Slice in be worth it? On top of those overloads it brings both getters back to the helper, and a stored MakeByteSpan of a temporary std::vector still warns. On its own it changes nothing, since the annotation as it stands is unconditional.

template<> inline constexpr bool std::ranges::enable_borrowed_range<leveldb::Slice> = true;
Neither form keeps the helper here. `MakeByteSpan(m_impl_iter->iter->key())` warns because the `Slice` is a temporary, and binding it to a local only changes the warning to "address of stack memory associated with local variable 'key' returned". Would opting the `Slice` in be worth it? On top of those overloads it brings both getters back to the helper, and a stored `MakeByteSpan` of a temporary `std::vector` still warns. On its own it changes nothing, since the annotation as it stands is unconditional. ```cpp template<> inline constexpr bool std::ranges::enable_borrowed_range<leveldb::Slice> = true; ```
jeanpablojp (Migrated from github.com) commented 2026-09-07 22:31:02 +00:00

Concretely this, plus a #include <ranges> at the top:

template <typename V> requires std::ranges::borrowed_range<V>
auto MakeByteSpan(const V& v) noexcept
{
    return std::as_bytes(std::span{v});
}
template <typename V> requires (!std::ranges::borrowed_range<V>)
auto MakeByteSpan(const V& v LIFETIMEBOUND) noexcept
{
    return std::as_bytes(std::span{v});
}

The first overload takes whatever std::ranges::borrowed_range accepts, std::span and std::string_view among them, and everything else takes the second. MakeUCharSpan takes the same pair, with the requires sitting alongside its decltype return.

Concretely this, plus a `#include <ranges>` at the top: ```cpp template <typename V> requires std::ranges::borrowed_range<V> auto MakeByteSpan(const V& v) noexcept { return std::as_bytes(std::span{v}); } template <typename V> requires (!std::ranges::borrowed_range<V>) auto MakeByteSpan(const V& v LIFETIMEBOUND) noexcept { return std::as_bytes(std::span{v}); } ``` The first overload takes whatever `std::ranges::borrowed_range` accepts, `std::span` and `std::string_view` among them, and everything else takes the second. `MakeUCharSpan` takes the same pair, with the `requires` sitting alongside its `decltype` return.
jeanpablojp (Migrated from github.com) commented 2026-09-07 22:31:02 +00:00

UncopyableStream inherits the DataStream constructor that copies into vch, so no view is kept here. Reverted, the file still compiles clean.

    UncopyableStream stream{MakeByteSpan(std::string_view{"abc"})};
`UncopyableStream` inherits the `DataStream` constructor that copies into `vch`, so no view is kept here. Reverted, the file still compiles clean. ```suggestion UncopyableStream stream{MakeByteSpan(std::string_view{"abc"})}; ```
kevkevinpal (Migrated from github.com) reviewed 2026-09-17 20:32:15 +00:00
kevkevinpal (Migrated from github.com) commented 2026-09-17 20:32:15 +00:00

Reverted, thanks, you're right that UncopyableStream copies into vch, so
no view outlives the temporary.

Reverted, thanks, you're right that `UncopyableStream` copies into `vch`, so no view outlives the temporary.
kevkevinpal (Migrated from github.com) reviewed 2026-09-17 20:33:58 +00:00
kevkevinpal (Migrated from github.com) commented 2026-09-17 20:33:58 +00:00

Taken as-is, with #include <ranges> added. Only difference is that clang-format puts the requires-clause on its own line rather than inline with the decltype return for MakeUCharSpan.

Taken as-is, with `#include <ranges>` added. Only difference is that clang-format puts the requires-clause on its own line rather than inline with the `decltype` return for `MakeUCharSpan`.
kevkevinpal (Migrated from github.com) reviewed 2026-09-17 20:34:28 +00:00
kevkevinpal (Migrated from github.com) commented 2026-09-17 20:34:28 +00:00

Opted it in, and it turns out to be load-bearing rather than just a cleanup. With the constrained overloads but no specialization, clang gives -Wreturn-stack-address on both getters, since Slice is not a borrowed_range and lands on the annotated overload. With the specialization both getters go back to MakeByteSpan and the file is clean.

I kept it in dbwrapper.cpp rather than the header: dbwrapper.h deliberately doesn't pull in leveldb headers, and this is the only TU that pairs Slice with the span helpers.

Opted it in, and it turns out to be load-bearing rather than just a cleanup. With the constrained overloads but no specialization, clang gives `-Wreturn-stack-address` on both getters, since `Slice` is not a `borrowed_range` and lands on the annotated overload. With the specialization both getters go back to `MakeByteSpan` and the file is clean. I kept it in `dbwrapper.cpp` rather than the header: `dbwrapper.h` deliberately doesn't pull in leveldb headers, and this is the only TU that pairs `Slice` with the span helpers.
maflcko (Migrated from github.com) reviewed 2026-09-23 07:47:33 +00:00
maflcko (Migrated from github.com) left a comment

Just wondering about the great picture of this file here (left an unrelated comment).

Just wondering about the great picture of this file here (left an unrelated comment).
maflcko (Migrated from github.com) commented 2026-09-23 07:44:30 +00:00

unrelated: Seems odd to require BasicByte here for MakeUCharSpan, but not for MakeByteSpan.

Either it should be removed for both, or enforced for both.

Maybe it can be made explicit with something like:

#include <span>
#include <cstddef>

enum class EndianPolicy {
    Strict,
    Ignore
};

template <EndianPolicy Policy = EndianPolicy::Strict, typename V>
auto MakeByteSpan(const V& v) noexcept
{
    if constexpr (sizeof(typename decltype(std::span{v})::element_type) > 1) {
        static_assert(Policy == EndianPolicy::Ignore,
            "Cannot create byte span for multi-byte types: byte order is architecture-dependent. "
            "Use 'MakeByteSpan<EndianPolicy::Ignore>(...)' to acknowledge this.");
    }

    return std::as_bytes(std::span{v});
}

Also, UCharSpanCast is only called/used once, so maybe it can be renamed to UCharCast?

Afterwards, MakeUCharSpan(a) could even be removed and replaced by UCharCast(MakeByteSpan(a))?

unrelated: Seems odd to require BasicByte here for MakeUCharSpan, but not for MakeByteSpan. Either it should be removed for both, or enforced for both. Maybe it can be made explicit with something like: ```cpp #include <span> #include <cstddef> enum class EndianPolicy { Strict, Ignore }; template <EndianPolicy Policy = EndianPolicy::Strict, typename V> auto MakeByteSpan(const V& v) noexcept { if constexpr (sizeof(typename decltype(std::span{v})::element_type) > 1) { static_assert(Policy == EndianPolicy::Ignore, "Cannot create byte span for multi-byte types: byte order is architecture-dependent. " "Use 'MakeByteSpan<EndianPolicy::Ignore>(...)' to acknowledge this."); } return std::as_bytes(std::span{v}); } ``` Also, UCharSpanCast is only called/used once, so maybe it can be renamed to `UCharCast`? Afterwards, MakeUCharSpan(a) could even be removed and replaced by UCharCast(MakeByteSpan(a))?
maflcko (Migrated from github.com) reviewed 2026-09-23 10:28:15 +00:00
maflcko (Migrated from github.com) commented 2026-09-23 10:28:15 +00:00

also, reminds me that UCharCast will eat the annotation anyway right now. At least I don't get any warning for:

diff --git a/src/test/span_tests.cpp b/src/test/span_tests.cpp
index 42b62413aa..f0a22636d6 100644
--- a/src/test/span_tests.cpp
+++ b/src/test/span_tests.cpp
@@ -44,0 +45,6 @@ BOOST_AUTO_TEST_SUITE(span_tests)
+auto test_function()
+{
+    std::vector<std::byte> a;
+    return UCharSpanCast(std::span{a});
+}
+

So this pull is incomplete anyway

also, reminds me that UCharCast will eat the annotation anyway right now. At least I don't get any warning for: ```diff diff --git a/src/test/span_tests.cpp b/src/test/span_tests.cpp index 42b62413aa..f0a22636d6 100644 --- a/src/test/span_tests.cpp +++ b/src/test/span_tests.cpp @@ -44,0 +45,6 @@ BOOST_AUTO_TEST_SUITE(span_tests) +auto test_function() +{ + std::vector<std::byte> a; + return UCharSpanCast(std::span{a}); +} + ``` So this pull is incomplete anyway
First-time contributor

Earlier concerns remain unresolved; see the Run archive linked from the Review report.

🔵 Suggestion · Chained span conversions lose the new lifetime dependency

Chained conversions bypass the new Clang lifetime annotation; no current caller producing this input was found, and the underlying dangling-span behavior predates this PR.

Location: src/span.h:121 (head).

Review coverage was incomplete.


Reviewed: aa4bbd0c9b40 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:dc5ab9c247f7a4208471adc14ad7616ed67ce50a9e353d4b351d0bc273ed8e05:96b11b060163162106723c3b6f684428792dfa28110bbde7f4860e10f0618f25 --> <!-- ralph-base:ff90ca6cd56b59b803daa82d25145daaada5fb0b --> <!-- ralph-head:aa4bbd0c9b40ccb7960302b409344174aa2f8d49 --> <!-- ralph-case:384535a9e980f4e5b058ac27a4bc6580ec5a9b84dee5f8c39b5dfe8beb6fc289 --> Earlier concerns remain unresolved; see the Run archive linked from the Review report. **🔵 Suggestion · Chained span conversions lose the new lifetime dependency** Chained conversions bypass the new Clang lifetime annotation; no current caller producing this input was found, and the underlying dangling-span behavior predates this PR. Location: [`src/span.h:121`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/aa4bbd0c9b40ccb7960302b409344174aa2f8d49/src/span.h#L121>) (head). Review coverage was incomplete. <!-- Review tier: standard --> --- Reviewed: [`aa4bbd0c9b40`](<https://git.fish.foo/bitcoin/bitcoin/commit/aa4bbd0c9b40ccb7960302b409344174aa2f8d49>) · [Review report](<https://review.fish.foo/report/36183-aa4bbd0c9b40ccb7960302b409344174aa2f8d49-2601-2.html>) · [Previous reports](<https://review.fish.foo/traces/36183/>) [permalink](<https://review.fish.foo/report/36183-aa4bbd0c9b40ccb7960302b409344174aa2f8d49-2601-2.html>)
DrahtBot commented 2026-10-21 11:35:57 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
sedited commented 2026-11-12 10:11:35 +00:00 (Migrated from github.com)

Ping for rebase @kevkevinpal

Ping for rebase @kevkevinpal
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36183
No description provided.