1// REQUIRES: asan-64-bits
2// RUN: %clangxx_asan -O3 %s -o %t
3// RUN: %env_asan_opts=poison_array_cookie=1 not %run %t 2>&1 | FileCheck %s --check-prefix=COOKIE
4// RUN: %env_asan_opts=poison_array_cookie=0 not %run %t 2>&1 | FileCheck %s --check-prefix=NO_COOKIE
5
6// UNSUPPORTED: ios
7
8#include <stdio.h>
9#include <stdlib.h>
10#include <assert.h>
11int dtor_counter;
12struct C {
13 int x;
14 ~C() {
15 dtor_counter++;
16 fprintf(stderr, format: "DTOR %d\n", dtor_counter);
17 }
18};
19
20__attribute__((noinline)) void Delete(C *c) { delete[] c; }
21__attribute__((no_sanitize_address)) void Write42ToCookie(C *c) {
22 long *p = reinterpret_cast<long*>(c);
23 p[-1] = 42;
24}
25
26int main(int argc, char **argv) {
27 C *buffer = new C[argc];
28 delete [] buffer;
29 Write42ToCookie(c: buffer);
30 delete [] buffer;
31// COOKIE: DTOR 1
32// COOKIE-NOT: DTOR 2
33// COOKIE: AddressSanitizer: loaded array cookie from free-d memory
34// COOKIE: AddressSanitizer: attempting double-free
35// NO_COOKIE: DTOR 1
36// NO_COOKIE: DTOR 43
37// NO_COOKIE-NOT: DTOR 44
38// NO_COOKIE-NOT: AddressSanitizer: loaded array cookie from free-d memory
39// NO_COOKIE: AddressSanitizer: attempting double-free
40
41}
42

source code of compiler-rt/test/asan/TestCases/Posix/new_array_cookie_uaf_test.cpp