summaryrefslogtreecommitdiff
path: root/include
diff options
context:
space:
mode:
authorJonathan Wakely <jwakely@redhat.com>2022-07-12 11:18:47 +0100
committerJonathan Wakely <jwakely@redhat.com>2022-07-12 23:35:28 +0100
commit5ae74944af1de032d4a27fad4a2287bd3a2163fd (patch)
tree787bb0eaf58c10b752a0f54a96ea53b1cc9de8b6 /include
parent6e9d5dfc2911e3acc6039ebfe3837e7ba4be197f (diff)
downloadgcc-5ae74944af1de032d4a27fad4a2287bd3a2163fd.tar.gz
libstdc++: Check for EOF if extraction avoids buffer overflow [PR106248]
In r11-2581-g17abcc77341584 (for LWG 2499) I added overflow checks to the pre-C++20 operator>>(istream&, char*) overload. Those checks can cause extraction to stop after filling the buffer, where previously it would have tried to extract another character and stopped at EOF. When that happens we no longer set eofbit in the stream state, which is consistent with the behaviour of the new C++20 overload, but is an observable and unexpected change in the C++17 behaviour. What makes it worse is that the behaviour change is dependent on optimization, because __builtin_object_size is used to detect the buffer size and that only works when optimizing. To avoid the unexpected and optimization-dependent change in behaviour, set eofbit manually if we stopped extracting because of the buffer size check, but had reached EOF anyway. If the stream's rdstate() != goodbit or width() is non-zero and smaller than the buffer, there's nothing to do. Otherwise, we filled the buffer and need to check for EOF, and maybe set eofbit. The new check is guarded by #ifdef __OPTIMIZE__ because otherwise __builtin_object_size is useless. There's no point compiling and emitting dead code that can't be eliminated because we're not optimizing. We could add extra checks that the next character in the buffer is not whitespace, to detect the case where we stopped early and prevented a buffer overflow that would have happened otherwise. That would allow us to assert or set badbit in the stream state when undefined behaviour was prevented. However, those extra checks would increase the size of the function, potentially reducing the likelihood of it being inlined, and so making the buffer size detection less reliable. It seems preferable to prevent UB and silently truncate, rather than miss the UB and allow the overflow to happen. libstdc++-v3/ChangeLog: PR libstdc++/106248 * include/std/istream [C++17] (operator>>(istream&, char*)): Set eofbit if we stopped extracting at EOF. * testsuite/27_io/basic_istream/extractors_character/char/pr106248.cc: New test. * testsuite/27_io/basic_istream/extractors_character/wchar_t/pr106248.cc: New test.
Diffstat (limited to 'include')
0 files changed, 0 insertions, 0 deletions