xref: /llvm-project/libcxxabi/test/test_exception_storage.pass.cpp (revision 086048df04f7fa44ba0bcb057260bffc746879fc)
1 //===-------------------- test_exception_storage.cpp ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <cstdlib>
10 #include <algorithm>
11 #include <iostream>
12 #include <__threading_support>
13 #include <unistd.h>
14 
15 #include "../src/cxa_exception.h"
16 
17 typedef __cxxabiv1::__cxa_eh_globals globals_t ;
18 
19 void *thread_code (void *parm) {
20     size_t *result = (size_t *) parm;
21     globals_t *glob1, *glob2;
22 
23     glob1 = __cxxabiv1::__cxa_get_globals ();
24     if ( NULL == glob1 )
25         std::cerr << "Got null result from __cxa_get_globals" << std::endl;
26 
27     glob2 = __cxxabiv1::__cxa_get_globals_fast ();
28     if ( glob1 != glob2 )
29         std::cerr << "Got different globals!" << std::endl;
30 
31     *result = (size_t) glob1;
32     sleep ( 1 );
33     return parm;
34     }
35 
36 #ifndef _LIBCXXABI_HAS_NO_THREADS
37 #define NUMTHREADS  10
38 size_t                 thread_globals [ NUMTHREADS ] = { 0 };
39 std::__libcpp_thread_t   threads        [ NUMTHREADS ];
40 #endif
41 
42 int main () {
43     int retVal = 0;
44 
45 #ifndef _LIBCXXABI_HAS_NO_THREADS
46 //  Make the threads, let them run, and wait for them to finish
47     for ( int i = 0; i < NUMTHREADS; ++i )
48         std::__libcpp_thread_create ( threads + i, thread_code, (void *) (thread_globals + i));
49     for ( int i = 0; i < NUMTHREADS; ++i )
50         std::__libcpp_thread_join ( &threads [ i ] );
51 
52     for ( int i = 0; i < NUMTHREADS; ++i )
53         if ( 0 == thread_globals [ i ] ) {
54             std::cerr << "Thread #" << i << " had a zero global" << std::endl;
55             retVal = 1;
56             }
57 
58     std::sort ( thread_globals, thread_globals + NUMTHREADS );
59     for ( int i = 1; i < NUMTHREADS; ++i )
60         if ( thread_globals [ i - 1 ] == thread_globals [ i ] ) {
61             std::cerr << "Duplicate thread globals (" << i-1 << " and " << i << ")" << std::endl;
62             retVal = 2;
63             }
64 #else // _LIBCXXABI_HAS_NO_THREADS
65     size_t thread_globals;
66     // Check that __cxa_get_globals() is not NULL.
67     if (thread_code(&thread_globals) == 0) {
68         retVal = 1;
69     }
70 #endif // !_LIBCXXABI_HAS_NO_THREADS
71     return retVal;
72 }
73