1 // Check that we can patch and unpatch specific function ids.
2 //
3 // RUN: %clangxx_xray -std=c++11 %s -o %t
4 // RUN: XRAY_OPTIONS="patch_premain=false" %run %t | FileCheck %s
5 
6 // UNSUPPORTED: target-is-mips64,target-is-mips64el
7 
8 #include "xray/xray_interface.h"
9 
10 #include <set>
11 #include <cstdio>
12 #include <cassert>
13 
14 std::set<int32_t> function_ids;
15 
16 [[clang::xray_never_instrument]] void coverage_handler(int32_t fid,
17                                                        XRayEntryType) {
18   thread_local bool patching = false;
19   if (patching) return;
20   patching = true;
21   function_ids.insert(fid);
22   __xray_unpatch_function(fid);
23   patching = false;
24 }
25 
26 [[clang::xray_always_instrument]] void baz() {
27   // do nothing!
28 }
29 
30 [[clang::xray_always_instrument]] void bar() {
31   baz();
32 }
33 
34 [[clang::xray_always_instrument]] void foo() {
35   bar();
36 }
37 
38 [[clang::xray_always_instrument]] int main(int argc, char *argv[]) {
39   __xray_set_handler(coverage_handler);
40   assert(__xray_patch() == XRayPatchingStatus::SUCCESS);
41   foo();
42   assert(__xray_unpatch() == XRayPatchingStatus::SUCCESS);
43 
44   // print out the function_ids.
45   printf("first pass.\n");
46   for (const auto id : function_ids)
47     printf("patched: %d\n", id);
48 
49   // CHECK-LABEL: first pass.
50   // CHECK-DAG: patched: [[F1:.*]]
51   // CHECK-DAG: patched: [[F2:.*]]
52   // CHECK-DAG: patched: [[F3:.*]]
53 
54   // make a copy of the function_ids, then patch them later.
55   auto called_fns = function_ids;
56 
57   // clear the function_ids.
58   function_ids.clear();
59 
60   // patch the functions we've called before.
61   for (const auto id : called_fns)
62     assert(__xray_patch_function(id) == XRayPatchingStatus::SUCCESS);
63 
64   // then call them again.
65   foo();
66   assert(__xray_unpatch() == XRayPatchingStatus::SUCCESS);
67 
68   // confirm that we've seen the same functions again.
69   printf("second pass.\n");
70   for (const auto id : function_ids)
71     printf("patched: %d\n", id);
72   // CHECK-LABEL: second pass.
73   // CHECK-DAG: patched: [[F1]]
74   // CHECK-DAG: patched: [[F2]]
75   // CHECK-DAG: patched: [[F3]]
76 
77   // Now we want to make sure that if we unpatch one, that we're only going to
78   // see two calls of the coverage_handler.
79   function_ids.clear();
80   assert(__xray_patch() == XRayPatchingStatus::SUCCESS);
81   assert(__xray_unpatch_function(1) == XRayPatchingStatus::SUCCESS);
82   foo();
83   assert(__xray_unpatch() == XRayPatchingStatus::SUCCESS);
84 
85   // confirm that we don't see function id one called anymore.
86   printf("missing 1.\n");
87   for (const auto id : function_ids)
88     printf("patched: %d\n", id);
89   // CHECK-LABEL: missing 1.
90   // CHECK-NOT: patched: 1
91 }
92