Skip to content

libshaderc_util: keep string_piece::find_last_* inside the piece - #1616

Open
b84330808 wants to merge 1 commit into
google:mainfrom
b84330808:string-piece-find-last-in-bounds
Open

b84330808 wants to merge 1 commit into
google:mainfrom
b84330808:string-piece-find-last-in-bounds

Conversation

@b84330808

Copy link
Copy Markdown

When pos is npos (the default) or past the end, find_last_of() and find_last_not_of() clamp it to size() and start the backward scan at begin_ + size(), one past the end. For a piece that ends at the end of its buffer that's a one-byte out-of-bounds read (ASan: heap-buffer-overflow). For a piece cut from a longer string, the next character can match: string_piece("abc.def").substr(0, 3).find_last_of('.') returned 3. find_last_not_of() returned size() for most pieces, since the terminating NUL never matches: string_piece("aaaaaa b").find_last_not_of("a") returned 8.

This clamps pos to size() - 1. It also defaults pos to npos in the char overload of find_last_not_of(), like the string_piece overload and std::string; with 0 it only looked at the first character. The only in-tree caller, glslc's GetFileExtension, passes std::string-backed pieces, so this doesn't change glslc output.

Tests added for both functions, including pieces taken from longer strings.

When pos is npos or past the end, find_last_of() and find_last_not_of()
clamped it to size() and then started the backward scan at
begin_ + size(), so the first character they looked at was the one just
past the end of the piece.

For a piece that ends at the end of its buffer this is a one-byte
out-of-bounds read (ASan reports a heap-buffer-overflow). For a piece
taken from a longer string, the character after the piece can match:
string_piece("abc.def").substr(0, 3).find_last_of('.') returned 3. And
find_last_not_of() returned size() for almost any piece, because the
terminating NUL of a std::string or literal does not match: for
"aaaaaa b", find_last_not_of("a") returned 8.

Clamp pos to size() - 1 instead. Also default pos to npos in the char
overload of find_last_not_of(), like the string_piece overload and
std::string; with 0 it only ever looked at the first character.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant