xref: /llvm-project/compiler-rt/test/hwasan/TestCases/Linux/pvalloc-overflow.cpp (revision 71e5652f47b0d02a54aa9582319648bc4c23842c)
153770e78SNico Weber // RUN: %clangxx_hwasan -O0 %s -o %t
253770e78SNico Weber // RUN: %env_hwasan_opts=allocator_may_return_null=0 not %run %t m1 2>&1 | FileCheck %s
353770e78SNico Weber // RUN: %env_hwasan_opts=allocator_may_return_null=1     %run %t m1 2>&1 | FileCheck %s --check-prefix=CHECK-NULL
453770e78SNico Weber // RUN: %env_hwasan_opts=allocator_may_return_null=0 not %run %t psm1 2>&1 | FileCheck %s
553770e78SNico Weber // RUN: %env_hwasan_opts=allocator_may_return_null=1     %run %t psm1 2>&1 | FileCheck %s --check-prefix=CHECK-NULL
653770e78SNico Weber 
753770e78SNico Weber // UNSUPPORTED: android
853770e78SNico Weber 
953770e78SNico Weber // Checks that pvalloc overflows are caught. If the allocator is allowed to
1053770e78SNico Weber // return null, the errno should be set to ENOMEM.
1153770e78SNico Weber 
1253770e78SNico Weber #include <assert.h>
1353770e78SNico Weber #include <errno.h>
1453770e78SNico Weber #include <malloc.h>
1553770e78SNico Weber #include <stdint.h>
1653770e78SNico Weber #include <string.h>
1753770e78SNico Weber #include <unistd.h>
1853770e78SNico Weber 
main(int argc,char * argv[])1953770e78SNico Weber int main(int argc, char *argv[]) {
2053770e78SNico Weber   assert(argc == 2);
2153770e78SNico Weber   const char *action = argv[1];
2253770e78SNico Weber 
2353770e78SNico Weber   const size_t page_size = sysconf(_SC_PAGESIZE);
2453770e78SNico Weber 
2553770e78SNico Weber   void *p = nullptr;
2696a4167bSMatt Morehouse   if (!strcmp(action, "m1")) {
2753770e78SNico Weber     p = pvalloc((uintptr_t)-1);
2896a4167bSMatt Morehouse   } else if (!strcmp(action, "psm1")) {
2953770e78SNico Weber     p = pvalloc((uintptr_t)-(page_size - 1));
3053770e78SNico Weber   } else {
3153770e78SNico Weber     assert(0);
3253770e78SNico Weber   }
3353770e78SNico Weber 
3496a4167bSMatt Morehouse   fprintf(stderr, "errno: %d\n", errno);
3553770e78SNico Weber 
3653770e78SNico Weber   return p != nullptr;
3753770e78SNico Weber }
3853770e78SNico Weber 
3953770e78SNico Weber // CHECK: {{ERROR: HWAddressSanitizer: pvalloc parameters overflow: size .* rounded up to system page size .* cannot be represented in type size_t}}
4053770e78SNico Weber // CHECK: {{#0 0x.* in .*pvalloc}}
41efba6421SVitaly Buka // CHECK: {{#1 0x.* in main .*pvalloc-overflow.cpp:}}
42*71e5652fSVitaly Buka // CHECK: SUMMARY: HWAddressSanitizer: pvalloc-overflow {{.*}} in main
4353770e78SNico Weber 
4453770e78SNico Weber // CHECK-NULL: errno: 12
45