1 // RUN: %clangxx_cfi -o %t1 %s
2 // RUN: %expect_crash %t1 2>&1 | FileCheck --check-prefix=CFI %s
3 // RUN: %expect_crash %t1 x 2>&1 | FileCheck --check-prefix=CFI %s
4 
5 // RUN: %clangxx_cfi -DB32 -o %t2 %s
6 // RUN: %expect_crash %t2 2>&1 | FileCheck --check-prefix=CFI %s
7 // RUN: %expect_crash %t2 x 2>&1 | FileCheck --check-prefix=CFI %s
8 
9 // RUN: %clangxx_cfi -DB64 -o %t3 %s
10 // RUN: %expect_crash %t3 2>&1 | FileCheck --check-prefix=CFI %s
11 // RUN: %expect_crash %t3 x 2>&1 | FileCheck --check-prefix=CFI %s
12 
13 // RUN: %clangxx_cfi -DBM -o %t4 %s
14 // RUN: %expect_crash %t4 2>&1 | FileCheck --check-prefix=CFI %s
15 // RUN: %expect_crash %t4 x 2>&1 | FileCheck --check-prefix=CFI %s
16 
17 // RUN: %clangxx -o %t5 %s
18 // RUN: %t5 2>&1 | FileCheck --check-prefix=NCFI %s
19 // RUN: %t5 x 2>&1 | FileCheck --check-prefix=NCFI %s
20 
21 // RUN: %clangxx_cfi_diag -o %t6 %s
22 // RUN: %t6 2>&1 | FileCheck --check-prefix=CFI-DIAG2 %s
23 // RUN: %t6 x 2>&1 | FileCheck --check-prefix=CFI-DIAG1 %s
24 
25 // Tests that the CFI mechanism is sensitive to multiple inheritance and only
26 // permits calls via virtual tables for the correct base class.
27 
28 // REQUIRES: cxxabi
29 
30 #include <stdio.h>
31 #include "utils.h"
32 
33 struct A {
34   virtual void f() = 0;
35 };
36 
37 struct B {
38   virtual void g() = 0;
39 };
40 
41 struct C : A, B {
42   virtual void f(), g();
43 };
44 
45 void C::f() {}
46 void C::g() {}
47 
48 int main(int argc, char **argv) {
49 #ifdef B32
50   break_optimization(new Deriver<A, 0>);
51   break_optimization(new Deriver<B, 0>);
52 #endif
53 
54 #ifdef B64
55   break_optimization(new Deriver<A, 0>);
56   break_optimization(new Deriver<A, 1>);
57   break_optimization(new Deriver<B, 0>);
58   break_optimization(new Deriver<B, 1>);
59 #endif
60 
61 #ifdef BM
62   break_optimization(new Deriver<A, 0>);
63   break_optimization(new Deriver<A, 1>);
64   break_optimization(new Deriver<A, 2>);
65   break_optimization(new Deriver<B, 0>);
66   break_optimization(new Deriver<B, 1>);
67   break_optimization(new Deriver<B, 2>);
68 #endif
69 
70   C *c = new C;
71   break_optimization(c);
72 
73   // CFI: 1
74   // NCFI: 1
75   fprintf(stderr, "1\n");
76 
77   if (argc > 1) {
78     A *a = c;
79     // CFI-DIAG1: runtime error: control flow integrity check for type 'B' failed during cast to unrelated type
80     // CFI-DIAG1-NEXT: note: vtable is of type '{{(struct )?}}C'
81     ((B *)a)->g(); // UB here
82   } else {
83     // CFI-DIAG2: runtime error: control flow integrity check for type 'A' failed during cast to unrelated type
84     // CFI-DIAG2-NEXT: note: vtable is of type '{{(struct )?}}C'
85     B *b = c;
86     ((A *)b)->f(); // UB here
87   }
88 
89   // CFI-NOT: {{^2$}}
90   // NCFI: {{^2$}}
91   fprintf(stderr, "2\n");
92 }
93