Skip to content

cm/filesystem: Fix crash with pre-C++11 std::string GNU ABI in C++17

Brad King requested to merge brad.king/cmake:filesystem-path-c++03-abi into master

The remove_filename and replace_extension methods compute an offset between the whole path in a std::string and a part of a path in a std::string_view. This is done by subtracting their .data() pointers. However, C++17 adds a non-const .data() through which modification of the string is allowed. This means the copy-on-write implementation used by the pre-C++11 std::string GNU ABI must reallocate if the string has been copied. Our subtraction then computes an offset between two different allocations, which is undefined behavior.

The workaround in !5969 (merged) avoided the problem by calling the non-const .data() to reallocate before constructing the string_view. Instead, explicitly call the const .data() method on the string, which does not reallocate.

Fixes: #22090 (closed), #23328 (closed)
Backport: release

Merge request reports