Issue 238819
Summary [libc][GPU] calloc can allocate a wrapped size when num * size overflows
Labels libc
Assignees
Reporter 0z5a
    ## Problem

The GPU implementation of `calloc` multiplies `num * size` without checking whether the product fits in `size_t`. A wrapped, nonzero product is passed to the allocator, so the call can return a non-null pointer to a much smaller allocation instead of failing.

At llvm-project commit `e75c14a99104bed5ab2b5a8f6a0abdc6c39d3eee`, the following host harness compiles the actual GPU `calloc.cpp` with a mock `gpu::allocate`. It demonstrates the arithmetic independently of the NVPTX allocator mismatch in #238406:

```cpp
#include "src/stdlib/calloc.h"
#include <cstdint>
#include <cstdio>

static unsigned char buffer[16];
static uint64_t requested = 0;
namespace LIBC_NAMESPACE_DECL { namespace gpu {
void *allocate(uint64_t n) { requested = n; return buffer; }
}}
int main() {
  void *p = LIBC_NAMESPACE::calloc(SIZE_MAX / 2 + 2, 2);
 std::printf("requested=%llu null=%d\n",
 static_cast<unsigned long long>(requested), p == nullptr);
}
```

>From the llvm-project root:

```sh
clang++ -std=c++17 -O1 -fno-builtin -DLIBC_NAMESPACE=__llvm_libc \
  -Ilibc libc/src/stdlib/gpu/calloc.cpp /tmp/calloc-overflow.cpp -o /tmp/calloc-overflow
/tmp/calloc-overflow
```

On a 64-bit host, the observed result was `requested=2 null=0`. The expected result is a null pointer without calling the allocator, because the mathematical product is larger than `SIZE_MAX`.

This is a host-side harness for the GPU implementation; it does not claim a GPU execution result. A checked multiplication before allocation avoids returning a pointer for an overflowed request.

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

Reply via email to