1 // RUN: %clangxx_cfi_dso -DSHARED_LIB %s -fPIC -shared -o %t1-so.so
2 // RUN: %clangxx_cfi_dso %s -o %t1 %t1-so.so
3 // RUN: %expect_crash %t1 2>&1 | FileCheck --check-prefix=CFI %s
4 // RUN: %expect_crash %t1 x 2>&1 | FileCheck --check-prefix=CFI-CAST %s
5
6 // RUN: %clangxx_cfi_dso -DB32 -DSHARED_LIB %s -fPIC -shared -o %t2-so.so
7 // RUN: %clangxx_cfi_dso -DB32 %s -o %t2 %t2-so.so
8 // RUN: %expect_crash %t2 2>&1 | FileCheck --check-prefix=CFI %s
9 // RUN: %expect_crash %t2 x 2>&1 | FileCheck --check-prefix=CFI-CAST %s
10
11 // RUN: %clangxx_cfi_dso -DB64 -DSHARED_LIB %s -fPIC -shared -o %t3-so.so
12 // RUN: %clangxx_cfi_dso -DB64 %s -o %t3 %t3-so.so
13 // RUN: %expect_crash %t3 2>&1 | FileCheck --check-prefix=CFI %s
14 // RUN: %expect_crash %t3 x 2>&1 | FileCheck --check-prefix=CFI-CAST %s
15
16 // RUN: %clangxx_cfi_dso -DBM -DSHARED_LIB %s -fPIC -shared -o %t4-so.so
17 // RUN: %clangxx_cfi_dso -DBM %s -o %t4 %t4-so.so
18 // RUN: %expect_crash %t4 2>&1 | FileCheck --check-prefix=CFI %s
19 // RUN: %expect_crash %t4 x 2>&1 | FileCheck --check-prefix=CFI-CAST %s
20
21 // RUN: %clangxx -DBM -DSHARED_LIB %s -fPIC -shared -o %t5-so.so
22 // RUN: %clangxx -DBM %s -o %t5 %t5-so.so
23 // RUN: %t5 2>&1 | FileCheck --check-prefix=NCFI %s
24 // RUN: %t5 x 2>&1 | FileCheck --check-prefix=NCFI %s
25
26 // Tests that the CFI mechanism crashes the program when making a virtual call
27 // to an object of the wrong class but with a compatible vtable, by casting a
28 // pointer to such an object and attempting to make a call through it.
29
30 // REQUIRES: cxxabi
31
32 #include <stdio.h>
33 #include <string.h>
34
35 struct A {
36 virtual void f();
37 };
38
39 void *create_B();
40
41 #ifdef SHARED_LIB
42
43 #include "../utils.h"
44 struct B {
45 virtual void f();
46 };
f()47 void B::f() {}
48
create_B()49 void *create_B() {
50 create_derivers<B>();
51 return (void *)(new B());
52 }
53
54 #else
55
f()56 void A::f() {}
57
main(int argc,char * argv[])58 int main(int argc, char *argv[]) {
59 void *p = create_B();
60 A *a;
61
62 // CFI: =0=
63 // CFI-CAST: =0=
64 // NCFI: =0=
65 fprintf(stderr, "=0=\n");
66
67 if (argc > 1 && argv[1][0] == 'x') {
68 // Test cast. BOOM.
69 a = (A*)p;
70 } else {
71 // Invisible to CFI. Test virtual call later.
72 memcpy(&a, &p, sizeof(a));
73 }
74
75 // CFI: =1=
76 // CFI-CAST-NOT: =1=
77 // NCFI: =1=
78 fprintf(stderr, "=1=\n");
79
80 a->f(); // UB here
81
82 // CFI-NOT: =2=
83 // CFI-CAST-NOT: =2=
84 // NCFI: =2=
85 fprintf(stderr, "=2=\n");
86 }
87 #endif
88