Skip to content

Commit

Permalink
[Path] Fix off-by-one in finding filename for win style paths (llvm#7…
Browse files Browse the repository at this point in the history
…8055)

This fixes a crash where `path::parent_path` causes an invalid access on
a string upon receiving a path that consists of a single colon.

On Windows machine, with runtime checks enabled build, upon `clang -I:
test.cc` produces:
```
Assertion failed: Index < Length && "Invalid index!", file llvm\include\llvm/ADT/StringRef.h, line 232
...
 #6 0x00007ff7816201eb `anonymous namespace'::parent_path_end llvm\lib\Support\Path.cpp:144:0
 #7 0x00007ff781620135 llvm::sys::path::parent_path(class llvm::StringRef, enum llvm::sys::path::Style) llvm\lib\Support\Path.cpp:470:0
```

Ideally, we can look for the last colon starting from the last
character, but we can instead start from second to last, and handle
empty paths by abusing `0 - 1 == npos`.
  • Loading branch information
mizvekov authored Jan 18, 2024
1 parent baaf0c9 commit 361016f
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 1 deletion.
2 changes: 1 addition & 1 deletion llvm/lib/Support/Path.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ namespace {

if (is_style_windows(style)) {
if (pos == StringRef::npos)
pos = str.find_last_of(':', str.size() - 2);
pos = str.find_last_of(':', str.size() - 1);
}

if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
Expand Down
1 change: 1 addition & 0 deletions llvm/unittests/Support/Path.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ TEST(Support, Path) {
paths.push_back("c:\\foo\\");
paths.push_back("c:\\foo/");
paths.push_back("c:/foo\\bar");
paths.push_back(":");

for (SmallVector<StringRef, 40>::const_iterator i = paths.begin(),
e = paths.end();
Expand Down

0 comments on commit 361016f

Please sign in to comment.