Issue 55525
Summary InstCombine strlen(x)==0 folding removes ASan heap-buffer-overflow failure
Labels compiler-rt:asan, llvm:optimizations
Assignees
Reporter Teemperor
    I have the following C++20 code containing a strlen call on a buffer without null terminator:

```cpp
#include <cstring>
#include <string_view>
#include <cstdlib>

char getFirstChar(std::string_view s) {
    if (s.empty())
      return ' ';
    return s.front();
}

int main(int argc, char **argv) {
  char *arg = argv[0];
  char *x = (char*)calloc(1, std::strlen(arg)); // This is not allocating the 0 terminator.
  memcpy(x, arg, strlen(arg));
  char res = getFirstChar(x);
  free(x);
  return res;
}
```
https://godbolt.org/z/GjvG537oG

This code above fails with an ASan report as expected on O0 with -fsanitize=address, but on O1 (which e.g. is what oss-fuzz is always using for fuzzing) this code passes with ASan enabled.

A minimal reproducer is:
```cpp
#include <string.h>
 
int main() {
    char x[2] = {'a', 'b'};
    return strlen(x) == 0;
}
```

https://godbolt.org/z/ea8zK93v6

The problem here seems to be in `LibCallSimplifier::optimizeStringLength` which folds `strlen(x)==0` to a load.
https://github.com/llvm/llvm-project/blob/6c81079edf26da23f977a82e82f72cc6abd9cafd/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp#L640



_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to