1 // Test to make sure basic initialization order errors are caught.
2 
3 // RUN: %clangxx_asan %macos_min_target_10_11 -O0 %s %p/Helpers/initialization-bug-extra2.cpp -o %t-INIT-ORDER-EXE
4 // RUN: %env_asan_opts=check_initialization_order=true not %run %t-INIT-ORDER-EXE 2>&1 | FileCheck %s
5 
6 // Do not test with optimization -- the error may be optimized away.
7 
8 // FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=186
9 // XFAIL: windows-msvc
10 
11 // The test is expected to fail on OS X Yosemite and older
12 // UNSUPPORTED: osx-no-ld64-live_support
13 // UNSUPPORTED: ios
14 
15 #include <cstdio>
16 
17 // The structure of the test is:
18 // "x", "y", "z" are dynamically initialized globals.
19 // Value of "x" depends on "y", value of "y" depends on "z".
20 // "x" and "z" are defined in this TU, "y" is defined in another one.
21 // Thus we shoud stably report initialization order fiasco independently of
22 // the translation unit order.
23 
24 int initZ() {
25   return 5;
26 }
27 int z = initZ();
28 
29 // 'y' is a dynamically initialized global residing in a different TU.  This
30 // dynamic initializer will read the value of 'y' before main starts.  The
31 // result is undefined behavior, which should be caught by initialization order
32 // checking.
33 extern int y;
34 int __attribute__((noinline)) initX() {
35   return y + 1;
36   // CHECK: {{AddressSanitizer: initialization-order-fiasco}}
37   // CHECK: {{READ of size .* at 0x.* thread T0}}
38   // CHECK: {{0x.* is located 0 bytes inside of global variable .*(y|z).*}}
39   // CHECK: registered at:
40   // CHECK: 0x{{.*}} in __asan_register_globals
41 }
42 
43 // This initializer begins our initialization order problems.
44 static int x = initX();
45 
46 int main() {
47   // ASan should have caused an exit before main runs.
48   printf("PASS\n");
49   // CHECK-NOT: PASS
50   return 0;
51 }
52