<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/55525>55525</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            InstCombine strlen(x)==0 folding removes ASan heap-buffer-overflow failure
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            compiler-rt:asan,
            llvm:optimizations
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          Teemperor
      </td>
    </tr>
</table>

<pre>
    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



</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyVVV1vqzgQ_TXkxSoipoTwkIc22VRXW2kf2n1eGRiCrwxGtknS_Po9NkmbtL26uxHhwzOeOTNzDpS6flv9YK3YE3MtsUYrpQ-y37F1xB9x8IRVuiaceidk7y2CWWcU9awSSjHdY6Ecm4YMO0jX6tGxfoTBkelkL5w2UfoQJZsouZwXyXRU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