1 // RUN: %clangxx %s -g -DSHARED_LIB -shared -o %t_shared_lib.dylib
2 // RUN: %clangxx %s -g -USHARED_LIB -o %t_loader
3 // RUN: %env_tool_opts=verbosity=3 %run %t_loader %t_shared_lib.dylib > %t_loader_output.txt 2>&1
4 // RUN: FileCheck -input-file=%t_loader_output.txt %s
5 // RUN: FileCheck -check-prefix=CHECK-STACKTRACE -input-file=%t_loader_output.txt %s
6 
7 #include <stdio.h>
8 
9 #ifdef SHARED_LIB
10 #include <sanitizer/common_interface_defs.h>
11 
12 extern "C" void PrintStack() {
13   fprintf(stderr, "Calling __sanitizer_print_stack_trace\n");
14   // CHECK-STACKTRACE: #0{{( *0x.* *in *)?}}  __sanitizer_print_stack_trace
15   // CHECK-STACKTRACE: #1{{( *0x.* *in *)?}} PrintStack {{.*}}print-stack-trace-in-code-loaded-after-fork.cpp:[[@LINE+1]]
16   __sanitizer_print_stack_trace();
17 }
18 #else
19 #include <assert.h>
20 #include <dlfcn.h>
21 #include <stdlib.h>
22 #include <sys/wait.h>
23 #include <unistd.h>
24 
25 typedef void (*PrintStackFnPtrTy)(void);
26 
27 int main(int argc, char **argv) {
28   assert(argc == 2);
29   pid_t pid = fork();
30   if (pid != 0) {
31     // Parent
32     pid_t parent_pid = getpid();
33     fprintf(stderr, "parent: %d\n", parent_pid);
34     int status = 0;
35     pid_t child = waitpid(pid, &status, /*options=*/0);
36     assert(pid == child);
37     bool clean_exit = WIFEXITED(status) && WEXITSTATUS(status) == 0;
38     return !clean_exit;
39   }
40   // Child.
41   pid = getpid();
42   // CHECK: child: [[CHILD_PID:[0-9]+]]
43   fprintf(stderr, "child: %d\n", pid);
44   // We load new code into the child process that isn't loaded into the parent.
45   // When we symbolize in `PrintStack` if the symbolizer is told to symbolize
46   // the parent (an old bug) rather than the child then symbolization will
47   // fail.
48   const char *library_to_load = argv[1];
49   void *handle = dlopen(library_to_load, RTLD_NOW | RTLD_LOCAL);
50   assert(handle);
51   PrintStackFnPtrTy PrintStackFnPtr = (PrintStackFnPtrTy)dlsym(handle, "PrintStack");
52   assert(PrintStackFnPtr);
53   // Check that the symbolizer is told examine the child process.
54   // CHECK: Launching Symbolizer process: {{.+}}atos -p [[CHILD_PID]]
55   // CHECK-STACKTRACE: #2{{( *0x.* *in *)?}} main {{.*}}print-stack-trace-in-code-loaded-after-fork.cpp:[[@LINE+1]]
56   PrintStackFnPtr();
57   return 0;
58 }
59 
60 #endif
61