]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/xray/xray_interface.cc
Merge compiler-rt trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / xray / xray_interface.cc
1 //===-- xray_interface.cpp --------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of XRay, a dynamic runtime instrumentation system.
11 //
12 // Implementation of the API functions.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "xray_interface_internal.h"
17
18 #include <cstdint>
19 #include <cstdio>
20 #include <errno.h>
21 #include <limits>
22 #include <sys/mman.h>
23
24 #include "sanitizer_common/sanitizer_common.h"
25 #include "xray_defs.h"
26
27 namespace __xray {
28
29 #if defined(__x86_64__)
30 // FIXME: The actual length is 11 bytes. Why was length 12 passed to mprotect()
31 // ?
32 static const int16_t cSledLength = 12;
33 #elif defined(__aarch64__)
34 static const int16_t cSledLength = 32;
35 #elif defined(__arm__)
36 static const int16_t cSledLength = 28;
37 #elif SANITIZER_MIPS32
38 static const int16_t cSledLength = 48;
39 #elif SANITIZER_MIPS64
40 static const int16_t cSledLength = 64;
41 #elif defined(__powerpc64__)
42 static const int16_t cSledLength = 8;
43 #else
44 #error "Unsupported CPU Architecture"
45 #endif /* CPU architecture */
46
47 // This is the function to call when we encounter the entry or exit sleds.
48 __sanitizer::atomic_uintptr_t XRayPatchedFunction{0};
49
50 // This is the function to call from the arg1-enabled sleds/trampolines.
51 __sanitizer::atomic_uintptr_t XRayArgLogger{0};
52
53 // MProtectHelper is an RAII wrapper for calls to mprotect(...) that will undo
54 // any successful mprotect(...) changes. This is used to make a page writeable
55 // and executable, and upon destruction if it was successful in doing so returns
56 // the page into a read-only and executable page.
57 //
58 // This is only used specifically for runtime-patching of the XRay
59 // instrumentation points. This assumes that the executable pages are originally
60 // read-and-execute only.
61 class MProtectHelper {
62   void *PageAlignedAddr;
63   std::size_t MProtectLen;
64   bool MustCleanup;
65
66 public:
67   explicit MProtectHelper(void *PageAlignedAddr,
68                           std::size_t MProtectLen) XRAY_NEVER_INSTRUMENT
69       : PageAlignedAddr(PageAlignedAddr),
70         MProtectLen(MProtectLen),
71         MustCleanup(false) {}
72
73   int MakeWriteable() XRAY_NEVER_INSTRUMENT {
74     auto R = mprotect(PageAlignedAddr, MProtectLen,
75                       PROT_READ | PROT_WRITE | PROT_EXEC);
76     if (R != -1)
77       MustCleanup = true;
78     return R;
79   }
80
81   ~MProtectHelper() XRAY_NEVER_INSTRUMENT {
82     if (MustCleanup) {
83       mprotect(PageAlignedAddr, MProtectLen, PROT_READ | PROT_EXEC);
84     }
85   }
86 };
87
88 } // namespace __xray
89
90 extern __sanitizer::SpinMutex XRayInstrMapMutex;
91 extern __sanitizer::atomic_uint8_t XRayInitialized;
92 extern __xray::XRaySledMap XRayInstrMap;
93
94 int __xray_set_handler(void (*entry)(int32_t,
95                                      XRayEntryType)) XRAY_NEVER_INSTRUMENT {
96   if (__sanitizer::atomic_load(&XRayInitialized,
97                                __sanitizer::memory_order_acquire)) {
98
99     __sanitizer::atomic_store(&__xray::XRayPatchedFunction,
100                               reinterpret_cast<uint64_t>(entry),
101                               __sanitizer::memory_order_release);
102     return 1;
103   }
104   return 0;
105 }
106
107 int __xray_remove_handler() XRAY_NEVER_INSTRUMENT {
108   return __xray_set_handler(nullptr);
109 }
110
111 __sanitizer::atomic_uint8_t XRayPatching{0};
112
113 using namespace __xray;
114
115 // FIXME: Figure out whether we can move this class to sanitizer_common instead
116 // as a generic "scope guard".
117 template <class Function> class CleanupInvoker {
118   Function Fn;
119
120 public:
121   explicit CleanupInvoker(Function Fn) XRAY_NEVER_INSTRUMENT : Fn(Fn) {}
122   CleanupInvoker(const CleanupInvoker &) XRAY_NEVER_INSTRUMENT = default;
123   CleanupInvoker(CleanupInvoker &&) XRAY_NEVER_INSTRUMENT = default;
124   CleanupInvoker &
125   operator=(const CleanupInvoker &) XRAY_NEVER_INSTRUMENT = delete;
126   CleanupInvoker &operator=(CleanupInvoker &&) XRAY_NEVER_INSTRUMENT = delete;
127   ~CleanupInvoker() XRAY_NEVER_INSTRUMENT { Fn(); }
128 };
129
130 template <class Function>
131 CleanupInvoker<Function> scopeCleanup(Function Fn) XRAY_NEVER_INSTRUMENT {
132   return CleanupInvoker<Function>{Fn};
133 }
134
135 // controlPatching implements the common internals of the patching/unpatching
136 // implementation. |Enable| defines whether we're enabling or disabling the
137 // runtime XRay instrumentation.
138 XRayPatchingStatus controlPatching(bool Enable) XRAY_NEVER_INSTRUMENT {
139   if (!__sanitizer::atomic_load(&XRayInitialized,
140                                __sanitizer::memory_order_acquire))
141     return XRayPatchingStatus::NOT_INITIALIZED; // Not initialized.
142
143   uint8_t NotPatching = false;
144   if (!__sanitizer::atomic_compare_exchange_strong(
145           &XRayPatching, &NotPatching, true, __sanitizer::memory_order_acq_rel))
146     return XRayPatchingStatus::ONGOING; // Already patching.
147
148   uint8_t PatchingSuccess = false;
149   auto XRayPatchingStatusResetter = scopeCleanup([&PatchingSuccess] {
150     if (!PatchingSuccess)
151       __sanitizer::atomic_store(&XRayPatching, false,
152                                 __sanitizer::memory_order_release);
153   });
154
155   // Step 1: Compute the function id, as a unique identifier per function in the
156   // instrumentation map.
157   XRaySledMap InstrMap;
158   {
159     __sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
160     InstrMap = XRayInstrMap;
161   }
162   if (InstrMap.Entries == 0)
163     return XRayPatchingStatus::NOT_INITIALIZED;
164
165   const uint64_t PageSize = GetPageSizeCached();
166   if ((PageSize == 0) || ((PageSize & (PageSize - 1)) != 0)) {
167     Report("System page size is not a power of two: %lld\n", PageSize);
168     return XRayPatchingStatus::FAILED;
169   }
170
171   uint32_t FuncId = 1;
172   uint64_t CurFun = 0;
173   for (std::size_t I = 0; I < InstrMap.Entries; I++) {
174     auto Sled = InstrMap.Sleds[I];
175     auto F = Sled.Function;
176     if (CurFun == 0)
177       CurFun = F;
178     if (F != CurFun) {
179       ++FuncId;
180       CurFun = F;
181     }
182
183     // While we're here, we should patch the nop sled. To do that we mprotect
184     // the page containing the function to be writeable.
185     void *PageAlignedAddr =
186         reinterpret_cast<void *>(Sled.Address & ~(PageSize - 1));
187     std::size_t MProtectLen = (Sled.Address + cSledLength) -
188                               reinterpret_cast<uint64_t>(PageAlignedAddr);
189     MProtectHelper Protector(PageAlignedAddr, MProtectLen);
190     if (Protector.MakeWriteable() == -1) {
191       printf("Failed mprotect: %d\n", errno);
192       return XRayPatchingStatus::FAILED;
193     }
194
195     bool Success = false;
196     switch (Sled.Kind) {
197     case XRayEntryType::ENTRY:
198       Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_FunctionEntry);
199       break;
200     case XRayEntryType::EXIT:
201       Success = patchFunctionExit(Enable, FuncId, Sled);
202       break;
203     case XRayEntryType::TAIL:
204       Success = patchFunctionTailExit(Enable, FuncId, Sled);
205       break;
206     case XRayEntryType::LOG_ARGS_ENTRY:
207       Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_ArgLoggerEntry);
208       break;
209     default:
210       Report("Unsupported sled kind: %d\n", int(Sled.Kind));
211       continue;
212     }
213     (void)Success;
214   }
215   __sanitizer::atomic_store(&XRayPatching, false,
216                             __sanitizer::memory_order_release);
217   PatchingSuccess = true;
218   return XRayPatchingStatus::SUCCESS;
219 }
220
221 XRayPatchingStatus __xray_patch() XRAY_NEVER_INSTRUMENT {
222   return controlPatching(true);
223 }
224
225 XRayPatchingStatus __xray_unpatch() XRAY_NEVER_INSTRUMENT {
226   return controlPatching(false);
227 }
228
229 int __xray_set_handler_arg1(void (*Handler)(int32_t, XRayEntryType, uint64_t)) {
230   if (!__sanitizer::atomic_load(&XRayInitialized,
231                                 __sanitizer::memory_order_acquire))
232     return 0;
233
234   // A relaxed write might not be visible even if the current thread gets
235   // scheduled on a different CPU/NUMA node.  We need to wait for everyone to
236   // have this handler installed for consistency of collected data across CPUs.
237   __sanitizer::atomic_store(&XRayArgLogger, reinterpret_cast<uint64_t>(Handler),
238                             __sanitizer::memory_order_release);
239   return 1;
240 }
241 int __xray_remove_handler_arg1() { return __xray_set_handler_arg1(nullptr); }