1 //===-------------------- test_exception_storage.cpp ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // FIXME: cxa_exception.hpp directly references `std::unexpected` and friends.
11 // This breaks this test when compiled in C++17. For now fix this by manually
12 // re-enabling the STL functions.
13 #define _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS
14 
15 #include <cstdlib>
16 #include <algorithm>
17 #include <iostream>
18 #include <__threading_support>
19 #include <unistd.h>
20 
21 #include "../src/cxa_exception.hpp"
22 
23 typedef __cxxabiv1::__cxa_eh_globals globals_t ;
24 
25 void *thread_code (void *parm) {
26     size_t *result = (size_t *) parm;
27     globals_t *glob1, *glob2;
28 
29     glob1 = __cxxabiv1::__cxa_get_globals ();
30     if ( NULL == glob1 )
31         std::cerr << "Got null result from __cxa_get_globals" << std::endl;
32 
33     glob2 = __cxxabiv1::__cxa_get_globals_fast ();
34     if ( glob1 != glob2 )
35         std::cerr << "Got different globals!" << std::endl;
36 
37     *result = (size_t) glob1;
38     sleep ( 1 );
39     return parm;
40     }
41 
42 #ifndef _LIBCXXABI_HAS_NO_THREADS
43 #define NUMTHREADS  10
44 size_t                 thread_globals [ NUMTHREADS ] = { 0 };
45 std::__libcpp_thread_t   threads        [ NUMTHREADS ];
46 #endif
47 
48 int main () {
49     int retVal = 0;
50 
51 #ifndef _LIBCXXABI_HAS_NO_THREADS
52 //  Make the threads, let them run, and wait for them to finish
53     for ( int i = 0; i < NUMTHREADS; ++i )
54         std::__libcpp_thread_create ( threads + i, thread_code, (void *) (thread_globals + i));
55     for ( int i = 0; i < NUMTHREADS; ++i )
56         std::__libcpp_thread_join ( &threads [ i ] );
57 
58     for ( int i = 0; i < NUMTHREADS; ++i )
59         if ( 0 == thread_globals [ i ] ) {
60             std::cerr << "Thread #" << i << " had a zero global" << std::endl;
61             retVal = 1;
62             }
63 
64     std::sort ( thread_globals, thread_globals + NUMTHREADS );
65     for ( int i = 1; i < NUMTHREADS; ++i )
66         if ( thread_globals [ i - 1 ] == thread_globals [ i ] ) {
67             std::cerr << "Duplicate thread globals (" << i-1 << " and " << i << ")" << std::endl;
68             retVal = 2;
69             }
70 #else // _LIBCXXABI_HAS_NO_THREADS
71     size_t thread_globals;
72     // Check that __cxa_get_globals() is not NULL.
73     if (thread_code(&thread_globals) == 0) {
74         retVal = 1;
75     }
76 #endif // !_LIBCXXABI_HAS_NO_THREADS
77     return retVal;
78 }
79