1// RUN: %clang_hwasan -O1 %s -o %t
2// RUN: %env_hwasan_opts=stack_history_size=2048 not %run %t 2045 2>&1 | FileCheck %s --check-prefix=YES
3// RUN: %env_hwasan_opts=stack_history_size=2048 not %run %t 2047 2>&1 | FileCheck %s --check-prefix=NO
4
5// Run the same tests as above, but using the __hwasan_add_frame_record libcall.
6// The output should be the exact same.
7// RUN: %clang_hwasan -O1 %s -o %t -mllvm -hwasan-record-stack-history=libcall
8// RUN: %env_hwasan_opts=stack_history_size=2048 not %run %t 2045 2>&1 | FileCheck %s --check-prefix=YES
9// RUN: %env_hwasan_opts=stack_history_size=2048 not %run %t 2047 2>&1 | FileCheck %s --check-prefix=NO
10
11// Stack histories are currently not recorded on x86.
12// XFAIL: target=x86_64{{.*}}
13
14#include <assert.h>
15#include <sanitizer/hwasan_interface.h>
16#include <stdlib.h>
17
18void USE(void *x) { // pretend_to_do_something(void *x)
19 __asm__ __volatile__("" : : "r" (x) : "memory");
20}
21
22volatile int four = 4;
23__attribute__((noinline)) void FUNC0() { int x[4]; USE(x: &x[0]); }
24__attribute__((noinline)) void FUNC() { int x[4]; USE(x: &x[0]); }
25__attribute__((noinline)) void OOB() {
26 int x[4];
27 int y[4];
28 // With -hwasan-generate-tags-with-calls=false, stack tags can occasionally
29 // be zero, leading to a false negative
30 // (https://github.com/llvm/llvm-project/issues/69221). Work around it by
31 // using the neighboring variable, which is guaranteed by
32 // -hwasan-generate-tags-with-calls=false to have a different (hence
33 // non-zero) tag.
34 if (__hwasan_tag_pointer(p: x, tag: 0) == x) {
35 assert(__hwasan_tag_pointer(y, 0) != y);
36 y[four] = 0;
37 } else {
38 x[four] = 0;
39 }
40 USE(x: &x[0]);
41 USE(x: &y[0]);
42}
43
44int main(int argc, char **argv) {
45 int X = argc == 2 ? atoi(nptr: argv[1]) : 10;
46 // FUNC0 is X+2's element of the ring buffer.
47 // If runtime buffer size is less than it, FUNC0 record will be lost.
48 FUNC0();
49 for (int i = 0; i < X; ++i)
50 FUNC();
51 // Make at least one call to OOB where base tag != 0 so that the bug is caught
52 // at least once.
53 OOB();
54 OOB();
55}
56
57// YES: Previously allocated frames
58// YES: OOB
59// YES: FUNC
60// YES: FUNC0
61
62// NO: Previously allocated frames
63// NO: OOB
64// NO: FUNC
65// NO-NOT: FUNC0
66

source code of compiler-rt/test/hwasan/TestCases/stack-history-length.c