1// RUN: %clangxx %collect_stack_traces -O0 %s -o %t
2// RUN: %env_tool_opts=allocator_may_return_null=0 not %run %t m1 2>&1 | FileCheck %s
3// RUN: %env_tool_opts=allocator_may_return_null=1 %run %t m1 2>&1 | FileCheck %s --check-prefix=CHECK-NULL
4// RUN: %env_tool_opts=allocator_may_return_null=0 not %run %t psm1 2>&1 | FileCheck %s
5// RUN: %env_tool_opts=allocator_may_return_null=1 %run %t psm1 2>&1 | FileCheck %s --check-prefix=CHECK-NULL
6
7// REQUIRES: stable-runtime
8
9// UNSUPPORTED: android, target={{.*(freebsd|netbsd).*}}, ubsan
10
11// Checks that pvalloc overflows are caught. If the allocator is allowed to
12// return null, the errno should be set to ENOMEM.
13
14#include <assert.h>
15#include <errno.h>
16#include <malloc.h>
17#include <stdio.h>
18#include <stdint.h>
19#include <string.h>
20#include <unistd.h>
21
22int main(int argc, char *argv[]) {
23 assert(argc == 2);
24 const char *action = argv[1];
25
26 const size_t page_size = sysconf(_SC_PAGESIZE);
27
28 void *p = nullptr;
29 if (!strcmp(s1: action, s2: "m1")) {
30 p = pvalloc(size: (uintptr_t)-1);
31 } else if (!strcmp(s1: action, s2: "psm1")) {
32 p = pvalloc(size: (uintptr_t)-(page_size - 1));
33 } else {
34 assert(0);
35 }
36 // CHECK: {{ERROR: .*Sanitizer: pvalloc parameters overflow: size .* rounded up to system page size .* cannot be represented in type size_t}}
37 // CHECK: {{#0 .*pvalloc}}
38 // CHECK: {{#[12] .*main .*pvalloc-overflow.cpp:}}
39 // CHECK: {{SUMMARY: .*Sanitizer: pvalloc-overflow}}
40
41 // The NULL pointer is printed differently on different systems, while (long)0
42 // is always the same.
43 fprintf(stderr, format: "errno: %d, p: %lx\n", errno, (long)p);
44 // CHECK-NULL: errno: 12, p: 0
45
46 return 0;
47}
48

source code of compiler-rt/test/sanitizer_common/TestCases/Linux/pvalloc-overflow.cpp