[Bug libstdc++/102592] [11/12 Regression] heap-use-after-free when constructing std::filesystem::path from iterator pair

cvs-commit at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Wed Oct 13 19:39:50 GMT 2021


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102592

--- Comment #2 from CVS Commits <cvs-commit at gcc dot gnu.org> ---
The master branch has been updated by Jonathan Wakely <redi@gcc.gnu.org>:

https://gcc.gnu.org/g:85b24e32dc27ec2e70b853713e0713cbc1ff08c3

commit r12-4380-g85b24e32dc27ec2e70b853713e0713cbc1ff08c3
Author: Jonathan Wakely <jwakely@redhat.com>
Date:   Wed Oct 13 17:02:59 2021 +0100

    libstdc++: Fix dangling string_view in filesystem::path [PR102592]

    When creating a path from a pair of non-contiguous iterators we pass the
    iterators to _S_convert(Iter, Iter). That function passes the iterators
    to __string_from_range to get a contiguous sequence of characters, and
    then calls _S_convert(const C*, const C*) to perform the encoding
    conversions. If the value type, C, is char8_t, then no conversion is
    needed and the _S_convert<char8_t>(const char8_t*, const char8_t*)
    specialization casts the pointer to const char* and returns a
    std::string_view that refs to the char8_t sequence. However, that
    sequence is owned by the std::u8string rvalue returned by
    __string_from_range, which goes out of scope when _S_convert(Iter, Iter)
    returns. That means the std::string_view is dangling and we get
    undefined behaviour when parsing it as a path.

    The same problem does not exist for the path members taking a "Source"
    argument, because those functions all convert a non-contiguous range
    into a basic_string<C> immediately, using __effective_range(__source).
    That means that the rvalue string returned by that function is still in
    scope for the full expression, so the string_view does not dangle.

    The solution for the buggy functions is to do the same thing, and call
    __string_from_range immediately, so that the returned rvalue is still in
    scope for the lifetime of the string_view returned by _S_convert. To
    avoid reintroducing the same problem, remove the _S_convert(Iter, Iter)
    overload that calls __string_from_range and returns a dangling view.

    libstdc++-v3/ChangeLog:

            PR libstdc++/102592
            * include/bits/fs_path.h (path::path(Iter, Iter, format))
            (path::append(Iter, Iter), path::concat(Iter, Iter)): Call
            __string_from_range directly, instead of two-argument overload
            of _S_convert.
            (path::_S_convert(Iter, Iter)): Remove.
            * testsuite/27_io/filesystem/path/construct/102592.C: New test.


More information about the Gcc-bugs mailing list