1 // RUN: %clang_scudo %s -o %t
2 // RUN: %run %t valid 2>&1
3 // RUN: not %run %t invalid 2>&1 | FileCheck --check-prefix=CHECK-align %s
4 // RUN: %env_scudo_opts=allocator_may_return_null=1 %run %t invalid 2>&1
5 // RUN: not %run %t double-free 2>&1 | FileCheck --check-prefix=CHECK-double-free %s
6 // RUN: %env_scudo_opts=DeallocationTypeMismatch=1 not %run %t realloc 2>&1 | FileCheck --check-prefix=CHECK-realloc %s
7 // RUN: %env_scudo_opts=DeallocationTypeMismatch=0 %run %t realloc 2>&1
9 // Tests that the various aligned allocation functions work as intended. Also
10 // tests for the condition where the alignment is not a power of 2.
20 // Sometimes the headers may not have this...
21 void *aligned_alloc(size_t alignment
, size_t size
);
23 int main(int argc
, char **argv
) {
25 size_t alignment
= 1U << 12;
26 size_t size
= 1U << 12;
31 if (!strcmp(argv
[1], "valid")) {
32 posix_memalign(&p
, alignment
, size
);
34 assert(((uintptr_t)p
& (alignment
- 1)) == 0);
36 p
= aligned_alloc(alignment
, size
);
38 assert(((uintptr_t)p
& (alignment
- 1)) == 0);
40 // Tests various combinations of alignment and sizes
41 for (int i
= (sizeof(void *) == 4) ? 3 : 4; i
< 19; i
++) {
43 for (int j
= 1; j
< 33; j
++) {
45 for (int k
= 0; k
< 3; k
++) {
46 p
= memalign(alignment
, size
- (2 * sizeof(void *) * k
));
48 assert(((uintptr_t)p
& (alignment
- 1)) == 0);
53 // For larger alignment, reduce the number of allocations to avoid running
54 // out of potential addresses (on 32-bit).
55 for (int i
= 19; i
<= 24; i
++) {
57 for (int k
= 0; k
< 3; k
++) {
58 p
= memalign(alignment
, 0x1000 - (2 * sizeof(void *) * k
));
60 assert(((uintptr_t)p
& (alignment
- 1)) == 0);
65 if (!strcmp(argv
[1], "invalid")) {
66 // Alignment is not a power of 2.
67 p
= memalign(alignment
- 1, size
);
68 // CHECK-align: Scudo ERROR: invalid allocation alignment
70 // Size is not a multiple of alignment.
71 p
= aligned_alloc(alignment
, size
>> 1);
73 void *p_unchanged
= (void *)0x42UL
;
75 // Alignment is not a power of 2.
76 err
= posix_memalign(&p
, 3, size
);
77 assert(p
== p_unchanged
);
78 assert(err
== EINVAL
);
79 // Alignment is a power of 2, but not a multiple of size(void *).
80 err
= posix_memalign(&p
, 2, size
);
81 assert(p
== p_unchanged
);
82 assert(err
== EINVAL
);
84 if (!strcmp(argv
[1], "double-free")) {
86 posix_memalign(&p
, 0x100, sizeof(int));
91 if (!strcmp(argv
[1], "realloc")) {
92 // We cannot reallocate a memalign'd chunk.
93 void *p
= memalign(16, 16);
101 // CHECK-double-free: ERROR: invalid chunk state
102 // CHECK-realloc: ERROR: allocation type mismatch when reallocating address