Skip to content

x3 unpack: do not reference non-contiguous input in reference mode - #1237

Open
Perennos wants to merge 2 commits into
msgpack:cpp_masterfrom
Perennos:fix-x3-reference-1225
Open

Perennos wants to merge 2 commits into
msgpack:cpp_masterfrom
Perennos:fix-x3-reference-1225

Conversation

@Perennos

Copy link
Copy Markdown

Fixes #1225. Related to #1236 (#1224), which touches different lines and is independent.

With MSGPACK_USE_X3_PARSE, msgpack::unpack(begin, end, f, ...) allows the reference function to return true, storing str/bin/ext pointers directly into the input instead of copying. For a buffering iterator such as boost::spirit::multi_pass, the backing storage is an internal std::vector<char> that reallocates during parsing. Pointers captured for earlier values become dangling before unpack returns, even though the caller keeps the source and iterators alive.

In detail::unpack_imp (include/msgpack/v2/x3_unpack.hpp, shared by the v2 and v3 unpack overloads), reference mode is now used only when the iterators are random-access and span a single contiguous block, verified by &*(last - 1) - &*first == last - first - 1. Otherwise, the reference function is ignored, data is copied into the zone as in copy mode, and referenced is set to false. Zero-copy behavior over const char*, std::string, and std::vector iterators is unchanged.

Tests added in test/msgpack_x3_parse.cpp (2 new cases):

  • reference_multi_pass: unpacks an array of eight 600-byte strings from a multi_pass wrapping an istreambuf_iterator with a reference function that always returns true, verifying that referenced is false and every element reads back intact.
  • reference_contiguous_still_zero_copy: verifies that for a const char* range and std::string::const_iterator, referenced is true and the resulting pointers lie within the source buffer.

Verification (GCC 13.5, Boost 1.74, -std=c++17 -fsanitize=address,undefined -DMSGPACK_USE_X3_PARSE):

  • Before the fix: reference_multi_pass fails with AddressSanitizer: heap-use-after-free (a memcpy read from the freed buffer) and check !referenced has failed. reference_contiguous_still_zero_copy passes.
  • After the fix: all 66 test cases in msgpack_x3_parse pass (the 64 existing cases pass both before and after). Also compiles and passes under -std=c++14 and -std=c++20 with -Wall -Wextra and no warnings.

Out of scope here: std::deque and std::list inputs are handled only for reference mode (falling back to copy). Reading str/bin/ext from such iterators in copy mode is the out-of-bounds read in #1224, fixed in #1236.

AI-assisted: drafted with an AI coding assistant; reproduced and tested locally before submitting.

@codecov-commenter

codecov-commenter commented Nov 25, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.10%. Comparing base (39cc081) to head (792744b).
⚠️ Report is 64 commits behind head on cpp_master.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@              Coverage Diff               @@
##           cpp_master    #1237      +/-   ##
==============================================
- Coverage       85.36%   80.10%   -5.27%     
==============================================
  Files              80       80              
  Lines            5099     5852     +753     
  Branches          507      649     +142     
==============================================
+ Hits             4353     4688     +335     
- Misses            746     1164     +418     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@redboltz

Copy link
Copy Markdown
Contributor

Thanks, this fixes #1225. I reproduced reference_multi_pass failing with heap-use-after-free on current cpp_master and passing with this PR, with all 66 cases green under ASan/UBSan; reference_contiguous_still_zero_copy confirms std::string and const char* input stays zero-copy.

Two requests before merging:

Perennos and others added 2 commits November 27, 2026 00:35
The check that tells whether a matched str/bin/ext range can be read in place
was a private member of app_specific. Make it a function of msgpack::detail, so
that the unpacker can use the same one, and document what it can and cannot
tell: before C++20 it is an O(1) test of the two end elements, which a
random-access container whose first and last blocks happen to be size - 1
bytes apart while a block between them lives elsewhere can fool.

With C++20 (std::contiguous_iterator is available) the answer is exact: only
an iterator that models it is read in place, and anything else, std::deque
included, is copied. std::string, std::vector and plain pointers stay
zero-copy.

Tests: the helper on a string, a vector, a pointer and a list, and, on C++20, a
random-access iterator over three blocks laid out to fool the endpoint check,
which must now be decoded through a copy.

AI assistance: the change and its tests were drafted with an AI coding assistant.
Reference mode hands out pointers into the input, which is only safe when
the whole input is one block the caller keeps alive. A buffering iterator
such as boost::spirit::multi_pass reallocates its storage while parsing,
so str, bin and ext objects pointed into freed memory (msgpack#1225).

unpack_imp now asks the shared is_contiguous helper and, when the input is
not contiguous, swaps the reference callback for one that always copies.
std::string, std::vector and raw pointers stay zero-copy.

AI assistance: the change and its tests were drafted with an AI coding assistant.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@Perennos
Perennos force-pushed the fix-x3-reference-1225 branch from 102238b to 792744b Compare November 27, 2026 09:33
@Perennos

Copy link
Copy Markdown
Author

Thanks for the review. The branch is rebased onto cpp_master (it now sits on the merge of #1236) and the two copies of the contiguity check are one.

Shared helper. is_contiguous(first, last) now lives once, in x3_parse.hpp. The parser's in-place read and unpack_imp's reference mode both call it, and is_contiguous_input is gone from x3_unpack.hpp. The change is two commits: the helper and its tests first, the unpacker fix on top.

C++20. When __cpp_lib_ranges >= 201911L the helper returns std::contiguous_iterator<It>, so the answer is exact. Before C++20 it is still the end-point test, and the comment now says what that test cannot see: a random-access range whose first and last blocks are size - 1 bytes apart while a block between them lives elsewhere is taken as contiguous, and the bytes after the first block are then read in place. That is the case you described for #1236 with the std::deque and the allocator.

One behaviour change comes with the exact answer: on C++20 an iterator that is contiguous in memory but does not model std::contiguous_iterator is now copied, so referenced is false for it where the end-point test let it through. std::string, std::vector and raw pointers model it and stay zero-copy; reference_contiguous_still_zero_copy covers the string and pointer cases.

Tests. is_contiguous_helper checks the helper on a string, a vector, a pointer and a list. On C++20 a small random-access segmented_iterator reproduces your case without allocator tricks: three blocks of eight bytes, the first and last at the two ends of one array, the middle one elsewhere, so the end points are exactly 23 bytes apart. non_contiguous_segmented_bin_cxx20 decodes a bin8 through it, and reference_segmented_cxx20 checks that reference mode copies it. reference_multi_pass and reference_contiguous_still_zero_copy are the ones already in this PR (with the earlier uint32_t fix to pack_array), merged with the new tests at the end of the file.

What I ran (ubuntu 24.04, gcc 13.3 and clang 18.1, -Wall -Wextra -Werror -fsanitize=address,undefined, target msgpack_x3_parse):

compiler C++17 C++20
gcc 13.3 73/73 cases, 138 assertions 75/75 cases, 143 assertions
clang 18.1 73/73 cases, 138 assertions 75/75 cases, 143 assertions

The first commit alone also builds and passes on all four (71/71 and 72/72). With the old x3_unpack.hpp and the new tests, reference_multi_pass fails with heap-use-after-free (and so does reference_segmented_cxx20 on C++20), while reference_contiguous_still_zero_copy passes.

Not run: libc++ (my Boost.Test link failed in that setup, so I have no result), MSVC, and macOS.

AI assistance: the change and its tests were drafted with an AI coding assistant; I reviewed and ran them as above.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants