Skip to content
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

<format>: Detect some invalid contiguous ranges in range_formatter #5187

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

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.

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
Status: Final Review
Development

Successfully merging this pull request may close these issues.

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