1 //===-- xray_interface.cpp --------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a part of XRay, a dynamic runtime instrumentation system.
12 // Implementation of the API functions.
14 //===----------------------------------------------------------------------===//
16 #include "xray_interface_internal.h"
24 #include "sanitizer_common/sanitizer_common.h"
25 #include "xray_defs.h"
29 #if defined(__x86_64__)
30 // FIXME: The actual length is 11 bytes. Why was length 12 passed to mprotect()
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;
44 #error "Unsupported CPU Architecture"
45 #endif /* CPU architecture */
47 // This is the function to call when we encounter the entry or exit sleds.
48 __sanitizer::atomic_uintptr_t XRayPatchedFunction{0};
50 // This is the function to call from the arg1-enabled sleds/trampolines.
51 __sanitizer::atomic_uintptr_t XRayArgLogger{0};
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.
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;
67 explicit MProtectHelper(void *PageAlignedAddr,
68 std::size_t MProtectLen) XRAY_NEVER_INSTRUMENT
69 : PageAlignedAddr(PageAlignedAddr),
70 MProtectLen(MProtectLen),
73 int MakeWriteable() XRAY_NEVER_INSTRUMENT {
74 auto R = mprotect(PageAlignedAddr, MProtectLen,
75 PROT_READ | PROT_WRITE | PROT_EXEC);
81 ~MProtectHelper() XRAY_NEVER_INSTRUMENT {
83 mprotect(PageAlignedAddr, MProtectLen, PROT_READ | PROT_EXEC);
90 extern __sanitizer::SpinMutex XRayInstrMapMutex;
91 extern __sanitizer::atomic_uint8_t XRayInitialized;
92 extern __xray::XRaySledMap XRayInstrMap;
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)) {
99 __sanitizer::atomic_store(&__xray::XRayPatchedFunction,
100 reinterpret_cast<uint64_t>(entry),
101 __sanitizer::memory_order_release);
107 int __xray_remove_handler() XRAY_NEVER_INSTRUMENT {
108 return __xray_set_handler(nullptr);
111 __sanitizer::atomic_uint8_t XRayPatching{0};
113 using namespace __xray;
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 {
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;
125 operator=(const CleanupInvoker &) XRAY_NEVER_INSTRUMENT = delete;
126 CleanupInvoker &operator=(CleanupInvoker &&) XRAY_NEVER_INSTRUMENT = delete;
127 ~CleanupInvoker() XRAY_NEVER_INSTRUMENT { Fn(); }
130 template <class Function>
131 CleanupInvoker<Function> scopeCleanup(Function Fn) XRAY_NEVER_INSTRUMENT {
132 return CleanupInvoker<Function>{Fn};
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.
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.
148 uint8_t PatchingSuccess = false;
149 auto XRayPatchingStatusResetter = scopeCleanup([&PatchingSuccess] {
150 if (!PatchingSuccess)
151 __sanitizer::atomic_store(&XRayPatching, false,
152 __sanitizer::memory_order_release);
155 // Step 1: Compute the function id, as a unique identifier per function in the
156 // instrumentation map.
157 XRaySledMap InstrMap;
159 __sanitizer::SpinMutexLock Guard(&XRayInstrMapMutex);
160 InstrMap = XRayInstrMap;
162 if (InstrMap.Entries == 0)
163 return XRayPatchingStatus::NOT_INITIALIZED;
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;
173 for (std::size_t I = 0; I < InstrMap.Entries; I++) {
174 auto Sled = InstrMap.Sleds[I];
175 auto F = Sled.Function;
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;
195 bool Success = false;
197 case XRayEntryType::ENTRY:
198 Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_FunctionEntry);
200 case XRayEntryType::EXIT:
201 Success = patchFunctionExit(Enable, FuncId, Sled);
203 case XRayEntryType::TAIL:
204 Success = patchFunctionTailExit(Enable, FuncId, Sled);
206 case XRayEntryType::LOG_ARGS_ENTRY:
207 Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_ArgLoggerEntry);
210 Report("Unsupported sled kind: %d\n", int(Sled.Kind));
215 __sanitizer::atomic_store(&XRayPatching, false,
216 __sanitizer::memory_order_release);
217 PatchingSuccess = true;
218 return XRayPatchingStatus::SUCCESS;
221 XRayPatchingStatus __xray_patch() XRAY_NEVER_INSTRUMENT {
222 return controlPatching(true);
225 XRayPatchingStatus __xray_unpatch() XRAY_NEVER_INSTRUMENT {
226 return controlPatching(false);
229 int __xray_set_handler_arg1(void (*Handler)(int32_t, XRayEntryType, uint64_t)) {
230 if (!__sanitizer::atomic_load(&XRayInitialized,
231 __sanitizer::memory_order_acquire))
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);
241 int __xray_remove_handler_arg1() { return __xray_set_handler_arg1(nullptr); }