1*7c3d14c8STreehugger Robot // RUN: %clangxx_tsan -O1 %s -DBUILD_SO -fPIC -shared -o %t-so.so
2*7c3d14c8STreehugger Robot // RUN: %clangxx_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
3*7c3d14c8STreehugger Robot
4*7c3d14c8STreehugger Robot // dl_iterate_phdr doesn't exist on OS X.
5*7c3d14c8STreehugger Robot // UNSUPPORTED: darwin
6*7c3d14c8STreehugger Robot
7*7c3d14c8STreehugger Robot #ifdef BUILD_SO
8*7c3d14c8STreehugger Robot
9*7c3d14c8STreehugger Robot #include "test.h"
10*7c3d14c8STreehugger Robot
11*7c3d14c8STreehugger Robot int exported_var = 0;
12*7c3d14c8STreehugger Robot
13*7c3d14c8STreehugger Robot #else // BUILD_SO
14*7c3d14c8STreehugger Robot
15*7c3d14c8STreehugger Robot #include "test.h"
16*7c3d14c8STreehugger Robot #include <dlfcn.h>
17*7c3d14c8STreehugger Robot #include <link.h>
18*7c3d14c8STreehugger Robot #include <string.h>
19*7c3d14c8STreehugger Robot #include <string>
20*7c3d14c8STreehugger Robot
callback(struct dl_phdr_info * info,size_t size,void * data)21*7c3d14c8STreehugger Robot static int callback(struct dl_phdr_info *info, size_t size, void *data) {
22*7c3d14c8STreehugger Robot if (info->dlpi_name[0] == '\0')
23*7c3d14c8STreehugger Robot info->dlpi_name = "/proc/self/exe";
24*7c3d14c8STreehugger Robot return !strcmp(info->dlpi_name, "non existent module");
25*7c3d14c8STreehugger Robot }
26*7c3d14c8STreehugger Robot
thread(void * unused)27*7c3d14c8STreehugger Robot void *thread(void *unused) {
28*7c3d14c8STreehugger Robot for (int i = 0; i < 1000; i++) {
29*7c3d14c8STreehugger Robot barrier_wait(&barrier);
30*7c3d14c8STreehugger Robot dl_iterate_phdr(callback, 0);
31*7c3d14c8STreehugger Robot }
32*7c3d14c8STreehugger Robot return 0;
33*7c3d14c8STreehugger Robot }
34*7c3d14c8STreehugger Robot
main(int argc,char * argv[])35*7c3d14c8STreehugger Robot int main(int argc, char *argv[]) {
36*7c3d14c8STreehugger Robot barrier_init(&barrier, 2);
37*7c3d14c8STreehugger Robot std::string path = std::string(argv[0]) + std::string("-so.so");
38*7c3d14c8STreehugger Robot pthread_t th;
39*7c3d14c8STreehugger Robot pthread_create(&th, 0, thread, 0);
40*7c3d14c8STreehugger Robot for (int i = 0; i < 1000; i++) {
41*7c3d14c8STreehugger Robot barrier_wait(&barrier);
42*7c3d14c8STreehugger Robot void *lib = dlopen(path.c_str(), RTLD_NOW);
43*7c3d14c8STreehugger Robot if (!lib) {
44*7c3d14c8STreehugger Robot printf("error in dlopen: %s\n", dlerror());
45*7c3d14c8STreehugger Robot return 1;
46*7c3d14c8STreehugger Robot }
47*7c3d14c8STreehugger Robot dlclose(lib);
48*7c3d14c8STreehugger Robot }
49*7c3d14c8STreehugger Robot pthread_join(th, 0);
50*7c3d14c8STreehugger Robot fprintf(stderr, "DONE\n");
51*7c3d14c8STreehugger Robot return 0;
52*7c3d14c8STreehugger Robot }
53*7c3d14c8STreehugger Robot
54*7c3d14c8STreehugger Robot #endif // BUILD_SO
55*7c3d14c8STreehugger Robot
56*7c3d14c8STreehugger Robot // CHECK-NOT: WARNING: ThreadSanitizer: data race
57*7c3d14c8STreehugger Robot // CHECK: DONE
58