xref: /llvm-project/libcxxabi/test/test_exception_storage.pass.cpp (revision 5aaefa510ef055e8f044ca89e352d4313f3aba49)
1 //===----------------------------------------------------------------------===//
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.h"
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 #ifndef _LIBCXXABI_HAS_NO_THREADS
33     sleep ( 1 );
34 #endif
35     return parm;
36 }
37 
38 #ifndef _LIBCXXABI_HAS_NO_THREADS
39 #define NUMTHREADS  10
40 size_t                 thread_globals [ NUMTHREADS ] = { 0 };
41 std::__libcpp_thread_t   threads        [ NUMTHREADS ];
42 #endif
43 
44 int main() {
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     int retVal = 0;
53     for ( int i = 0; i < NUMTHREADS; ++i ) {
54         if ( 0 == thread_globals [ i ] ) {
55             std::printf("Thread #%d had a zero global\n", i);
56             retVal = 1;
57         }
58     }
59 
60     std::sort ( thread_globals, thread_globals + NUMTHREADS );
61     for ( int i = 1; i < NUMTHREADS; ++i ) {
62         if ( thread_globals [ i - 1 ] == thread_globals [ i ] ) {
63             std::printf("Duplicate thread globals (%d and %d)\n", i-1, i);
64             retVal = 2;
65         }
66     }
67     return retVal;
68 #else // _LIBCXXABI_HAS_NO_THREADS
69     size_t thread_globals;
70     thread_code(&thread_globals);
71     // Check that __cxa_get_globals() is not NULL.
72     return (thread_globals == 0) ? 1 : 0;
73 #endif // !_LIBCXXABI_HAS_NO_THREADS
74 }
75