Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@frederick-vs-ja
Copy link
Contributor

@frederick-vs-ja frederick-vs-ja commented Dec 12, 2024

The following code snippet detects some "impossible" huge range.

STL/stl/inc/format

Lines 3283 to 3290 in 89ca073

template <class _CharT, _RANGES input_range _Range, class _FormatContext>
void _Range_formatter_format_as_string(_Range&& _Rng, _FormatContext& _Ctx, const bool _Debug) {
if constexpr (_RANGES contiguous_range<_Range>) {
const auto _Size = _STD _To_unsigned_like(_RANGES distance(_Rng));
if (!_STD in_range<size_t>(_Size)) [[unlikely]] {
_Throw_format_error("Formatted range is too long.");
}

The semantic requirements of contiguous_iterator depend on pointer arithmetic, so when the underlying contiguous_range has more than 1 elements, the range must denote a contiguous element sequence of some array to be valid (otherwise, reaching from the beginning to the end causes UB). Moreover, the C++ object model doesn't permit an array object to have more than SIZE_MAX element. So we can infer that when the size of the contiguous range is too large to fit into size_t, the range must be invalid, and thus formatting it results in UB (per [iterator.requirements.general]/10, although the paragraph seemingly accidently makes infinite range invalid).

Fixes #5182.

@frederick-vs-ja frederick-vs-ja requested a review from a team as a code owner December 12, 2024 05:14
@StephanTLavavej StephanTLavavej added enhancement Something can be improved ranges C++20/23 ranges format C++20/23 format labels Dec 12, 2024
@StephanTLavavej StephanTLavavej self-assigned this Dec 12, 2024
@CaseyCarter CaseyCarter added bug Something isn't working and removed enhancement Something can be improved labels Dec 13, 2024
@StephanTLavavej
Copy link
Member

I haven't thought about this too deeply, but I'd recommend any pathological checks be controlled by _DEBUG or IDL=2, not CDL.

@StephanTLavavej
Copy link
Member

I'm mirroring this to the MSVC-internal repo - please notify me if any further changes are pushed.

@StephanTLavavej StephanTLavavej merged commit 3c31602 into microsoft:main Jan 14, 2025
39 checks passed
@StephanTLavavej
Copy link
Member

Thanks for fixing this obscure bug! 🛠️ 🐞 🪄

@frederick-vs-ja frederick-vs-ja deleted the contiguously-small branch January 14, 2025 13:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working format C++20/23 format ranges C++20/23 ranges

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

<format>: in_range apply on non-integrals triggers a static_assert

3 participants