1 // RUN: %clangxx_cfi -o %t1 %s
2 // RUN: %expect_crash %t1 2>&1 | FileCheck --check-prefix=CFI %s
3 
4 // RUN: %clangxx_cfi -DB32 -o %t2 %s
5 // RUN: %expect_crash %t2 2>&1 | FileCheck --check-prefix=CFI %s
6 
7 // RUN: %clangxx_cfi -DB64 -o %t3 %s
8 // RUN: %expect_crash %t3 2>&1 | FileCheck --check-prefix=CFI %s
9 
10 // RUN: %clangxx_cfi -DBM -o %t4 %s
11 // RUN: %expect_crash %t4 2>&1 | FileCheck --check-prefix=CFI %s
12 
13 // RUN: %clangxx -o %t5 %s
14 // RUN: %t5 2>&1 | FileCheck --check-prefix=NCFI %s
15 
16 // RUN: %clangxx_cfi_diag -o %t6 %s
17 // RUN: %t6 2>&1 | FileCheck --check-prefix=CFI-DIAG %s
18 
19 // Tests that the CFI mechanism crashes the program when making a non-virtual
20 // call to an object of the wrong class, by casting a pointer to such an object
21 // and attempting to make a call through it.
22 
23 // REQUIRES: cxxabi
24 
25 #include <stdio.h>
26 #include "utils.h"
27 
28 struct A {
29   virtual void v();
30 };
31 
32 void A::v() {}
33 
34 struct B {
35   void f();
36   virtual void g();
37 };
38 
39 void B::f() {}
40 void B::g() {}
41 
42 int main() {
43 #ifdef B32
44   break_optimization(new Deriver<B, 0>);
45 #endif
46 
47 #ifdef B64
48   break_optimization(new Deriver<B, 0>);
49   break_optimization(new Deriver<B, 1>);
50 #endif
51 
52 #ifdef BM
53   break_optimization(new Deriver<B, 0>);
54   break_optimization(new Deriver<B, 1>);
55   break_optimization(new Deriver<B, 2>);
56 #endif
57 
58   A *a = new A;
59   break_optimization(a);
60 
61   // CFI: 1
62   // NCFI: 1
63   fprintf(stderr, "1\n");
64 
65   // CFI-DIAG: runtime error: control flow integrity check for type 'B' failed during non-virtual call
66   // CFI-DIAG-NEXT: note: vtable is of type '{{(struct )?}}A'
67   ((B *)a)->f(); // UB here
68 
69   // CFI-NOT: {{^2$}}
70   // NCFI: {{^2$}}
71   fprintf(stderr, "2\n");
72 }
73