xref: /llvm-project/libcxxabi/test/test_exception_storage.pass.cpp (revision cc69d211d0d65d7bf0335fecbc323f784ac3afcc)
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 <algorithm>
10 #include <cstdio>
11 #include <cstdlib>
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::printf("Got null result from __cxa_get_globals\n");
26 
27     glob2 = __cxxabiv1::__cxa_get_globals_fast ();
28     if ( glob1 != glob2 )
29         std::printf("Got different globals!\n");
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::printf("Thread #%d had a zero global\n", i);
55             retVal = 1;
56         }
57     }
58 
59     std::sort ( thread_globals, thread_globals + NUMTHREADS );
60     for ( int i = 1; i < NUMTHREADS; ++i ) {
61         if ( thread_globals [ i - 1 ] == thread_globals [ i ] ) {
62             std::printf("Duplicate thread globals (%d and %d)\n", i-1, i);
63             retVal = 2;
64         }
65     }
66 #else // _LIBCXXABI_HAS_NO_THREADS
67     size_t thread_globals;
68     // Check that __cxa_get_globals() is not NULL.
69     if (thread_code(&thread_globals) == 0) {
70         retVal = 1;
71     }
72 #endif // !_LIBCXXABI_HAS_NO_THREADS
73     return retVal;
74 }
75