1b3018603SNico Weber //===-- xray_interface.cpp --------------------------------------*- C++ -*-===//
2b3018603SNico Weber //
3b3018603SNico Weber // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4b3018603SNico Weber // See https://llvm.org/LICENSE.txt for license information.
5b3018603SNico Weber // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b3018603SNico Weber //
7b3018603SNico Weber //===----------------------------------------------------------------------===//
8b3018603SNico Weber //
9b3018603SNico Weber // This file is a part of XRay, a dynamic runtime instrumentation system.
10b3018603SNico Weber //
11b3018603SNico Weber // Implementation of the API functions.
12b3018603SNico Weber //
13b3018603SNico Weber //===----------------------------------------------------------------------===//
14b3018603SNico Weber 
15b3018603SNico Weber #include "xray_interface_internal.h"
16b3018603SNico Weber 
17bbba9d8cSDimitry Andric #include <cinttypes>
18b3018603SNico Weber #include <cstdio>
19b3018603SNico Weber #include <errno.h>
20b3018603SNico Weber #include <limits>
21b3018603SNico Weber #include <string.h>
22b3018603SNico Weber #include <sys/mman.h>
23b3018603SNico Weber 
24b3018603SNico Weber #if SANITIZER_FUCHSIA
25b3018603SNico Weber #include <zircon/process.h>
26b3018603SNico Weber #include <zircon/sanitizer.h>
27b3018603SNico Weber #include <zircon/status.h>
28b3018603SNico Weber #include <zircon/syscalls.h>
29b3018603SNico Weber #endif
30b3018603SNico Weber 
31b3018603SNico Weber #include "sanitizer_common/sanitizer_addrhashmap.h"
32b3018603SNico Weber #include "sanitizer_common/sanitizer_common.h"
33b3018603SNico Weber 
34b3018603SNico Weber #include "xray_defs.h"
35b3018603SNico Weber #include "xray_flags.h"
36b3018603SNico Weber 
37b3018603SNico Weber extern __sanitizer::SpinMutex XRayInstrMapMutex;
38b3018603SNico Weber extern __sanitizer::atomic_uint8_t XRayInitialized;
39b3018603SNico Weber extern __xray::XRaySledMap XRayInstrMap;
40b3018603SNico Weber 
41b3018603SNico Weber namespace __xray {
42b3018603SNico Weber 
43b3018603SNico Weber #if defined(__x86_64__)
44b3018603SNico Weber static const int16_t cSledLength = 12;
45b3018603SNico Weber #elif defined(__aarch64__)
46b3018603SNico Weber static const int16_t cSledLength = 32;
47b3018603SNico Weber #elif defined(__arm__)
48b3018603SNico Weber static const int16_t cSledLength = 28;
49b3018603SNico Weber #elif SANITIZER_MIPS32
50b3018603SNico Weber static const int16_t cSledLength = 48;
51b3018603SNico Weber #elif SANITIZER_MIPS64
52b3018603SNico Weber static const int16_t cSledLength = 64;
53b3018603SNico Weber #elif defined(__powerpc64__)
54b3018603SNico Weber static const int16_t cSledLength = 8;
55*1e68c799SBrian Cain #elif defined(__hexagon__)
56*1e68c799SBrian Cain static const int16_t cSledLength = 20;
57b3018603SNico Weber #else
58b3018603SNico Weber #error "Unsupported CPU Architecture"
59b3018603SNico Weber #endif /* CPU architecture */
60b3018603SNico Weber 
61b3018603SNico Weber // This is the function to call when we encounter the entry or exit sleds.
62b3018603SNico Weber atomic_uintptr_t XRayPatchedFunction{0};
63b3018603SNico Weber 
64b3018603SNico Weber // This is the function to call from the arg1-enabled sleds/trampolines.
65b3018603SNico Weber atomic_uintptr_t XRayArgLogger{0};
66b3018603SNico Weber 
67b3018603SNico Weber // This is the function to call when we encounter a custom event log call.
68b3018603SNico Weber atomic_uintptr_t XRayPatchedCustomEvent{0};
69b3018603SNico Weber 
70b3018603SNico Weber // This is the function to call when we encounter a typed event log call.
71b3018603SNico Weber atomic_uintptr_t XRayPatchedTypedEvent{0};
72b3018603SNico Weber 
73b3018603SNico Weber // This is the global status to determine whether we are currently
74b3018603SNico Weber // patching/unpatching.
75b3018603SNico Weber atomic_uint8_t XRayPatching{0};
76b3018603SNico Weber 
77b3018603SNico Weber struct TypeDescription {
78b3018603SNico Weber   uint32_t type_id;
79b3018603SNico Weber   std::size_t description_string_length;
80b3018603SNico Weber };
81b3018603SNico Weber 
82b3018603SNico Weber using TypeDescriptorMapType = AddrHashMap<TypeDescription, 11>;
83b3018603SNico Weber // An address map from immutable descriptors to type ids.
84b3018603SNico Weber TypeDescriptorMapType TypeDescriptorAddressMap{};
85b3018603SNico Weber 
86b3018603SNico Weber atomic_uint32_t TypeEventDescriptorCounter{0};
87b3018603SNico Weber 
88b3018603SNico Weber // MProtectHelper is an RAII wrapper for calls to mprotect(...) that will
89b3018603SNico Weber // undo any successful mprotect(...) changes. This is used to make a page
90b3018603SNico Weber // writeable and executable, and upon destruction if it was successful in
91b3018603SNico Weber // doing so returns the page into a read-only and executable page.
92b3018603SNico Weber //
93b3018603SNico Weber // This is only used specifically for runtime-patching of the XRay
94b3018603SNico Weber // instrumentation points. This assumes that the executable pages are
95b3018603SNico Weber // originally read-and-execute only.
96b3018603SNico Weber class MProtectHelper {
97b3018603SNico Weber   void *PageAlignedAddr;
98b3018603SNico Weber   std::size_t MProtectLen;
99b3018603SNico Weber   bool MustCleanup;
100b3018603SNico Weber 
101b3018603SNico Weber public:
MProtectHelper(void * PageAlignedAddr,std::size_t MProtectLen,std::size_t PageSize)102b3018603SNico Weber   explicit MProtectHelper(void *PageAlignedAddr,
103b3018603SNico Weber                           std::size_t MProtectLen,
104b3018603SNico Weber                           std::size_t PageSize) XRAY_NEVER_INSTRUMENT
105b3018603SNico Weber       : PageAlignedAddr(PageAlignedAddr),
106b3018603SNico Weber         MProtectLen(MProtectLen),
107b3018603SNico Weber         MustCleanup(false) {
108b3018603SNico Weber #if SANITIZER_FUCHSIA
109b3018603SNico Weber     MProtectLen = RoundUpTo(MProtectLen, PageSize);
110b3018603SNico Weber #endif
111b3018603SNico Weber   }
112b3018603SNico Weber 
MakeWriteable()113b3018603SNico Weber   int MakeWriteable() XRAY_NEVER_INSTRUMENT {
114b3018603SNico Weber #if SANITIZER_FUCHSIA
115b3018603SNico Weber     auto R = __sanitizer_change_code_protection(
116b3018603SNico Weber         reinterpret_cast<uintptr_t>(PageAlignedAddr), MProtectLen, true);
117b3018603SNico Weber     if (R != ZX_OK) {
118b3018603SNico Weber       Report("XRay: cannot change code protection: %s\n",
119b3018603SNico Weber              _zx_status_get_string(R));
120b3018603SNico Weber       return -1;
121b3018603SNico Weber     }
122b3018603SNico Weber     MustCleanup = true;
123b3018603SNico Weber     return 0;
124b3018603SNico Weber #else
125b3018603SNico Weber     auto R = mprotect(PageAlignedAddr, MProtectLen,
126b3018603SNico Weber                       PROT_READ | PROT_WRITE | PROT_EXEC);
127b3018603SNico Weber     if (R != -1)
128b3018603SNico Weber       MustCleanup = true;
129b3018603SNico Weber     return R;
130b3018603SNico Weber #endif
131b3018603SNico Weber   }
132b3018603SNico Weber 
~MProtectHelper()133b3018603SNico Weber   ~MProtectHelper() XRAY_NEVER_INSTRUMENT {
134b3018603SNico Weber     if (MustCleanup) {
135b3018603SNico Weber #if SANITIZER_FUCHSIA
136b3018603SNico Weber       auto R = __sanitizer_change_code_protection(
137b3018603SNico Weber           reinterpret_cast<uintptr_t>(PageAlignedAddr), MProtectLen, false);
138b3018603SNico Weber       if (R != ZX_OK) {
139b3018603SNico Weber         Report("XRay: cannot change code protection: %s\n",
140b3018603SNico Weber                _zx_status_get_string(R));
141b3018603SNico Weber       }
142b3018603SNico Weber #else
143b3018603SNico Weber       mprotect(PageAlignedAddr, MProtectLen, PROT_READ | PROT_EXEC);
144b3018603SNico Weber #endif
145b3018603SNico Weber     }
146b3018603SNico Weber   }
147b3018603SNico Weber };
148b3018603SNico Weber 
149b3018603SNico Weber namespace {
150b3018603SNico Weber 
patchSled(const XRaySledEntry & Sled,bool Enable,int32_t FuncId)151b3018603SNico Weber bool patchSled(const XRaySledEntry &Sled, bool Enable,
152b3018603SNico Weber                int32_t FuncId) XRAY_NEVER_INSTRUMENT {
153b3018603SNico Weber   bool Success = false;
154b3018603SNico Weber   switch (Sled.Kind) {
155b3018603SNico Weber   case XRayEntryType::ENTRY:
156b3018603SNico Weber     Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_FunctionEntry);
157b3018603SNico Weber     break;
158b3018603SNico Weber   case XRayEntryType::EXIT:
159b3018603SNico Weber     Success = patchFunctionExit(Enable, FuncId, Sled);
160b3018603SNico Weber     break;
161b3018603SNico Weber   case XRayEntryType::TAIL:
162b3018603SNico Weber     Success = patchFunctionTailExit(Enable, FuncId, Sled);
163b3018603SNico Weber     break;
164b3018603SNico Weber   case XRayEntryType::LOG_ARGS_ENTRY:
165b3018603SNico Weber     Success = patchFunctionEntry(Enable, FuncId, Sled, __xray_ArgLoggerEntry);
166b3018603SNico Weber     break;
167b3018603SNico Weber   case XRayEntryType::CUSTOM_EVENT:
168b3018603SNico Weber     Success = patchCustomEvent(Enable, FuncId, Sled);
169b3018603SNico Weber     break;
170b3018603SNico Weber   case XRayEntryType::TYPED_EVENT:
171b3018603SNico Weber     Success = patchTypedEvent(Enable, FuncId, Sled);
172b3018603SNico Weber     break;
173b3018603SNico Weber   default:
174bbba9d8cSDimitry Andric     Report("Unsupported sled kind '%" PRIu64 "' @%04x\n", Sled.Address,
175bbba9d8cSDimitry Andric            int(Sled.Kind));
176b3018603SNico Weber     return false;
177b3018603SNico Weber   }
178b3018603SNico Weber   return Success;
179b3018603SNico Weber }
180b3018603SNico Weber 
1817c7c8e0dSIan Levesque const XRayFunctionSledIndex
findFunctionSleds(int32_t FuncId,const XRaySledMap & InstrMap)1827c7c8e0dSIan Levesque findFunctionSleds(int32_t FuncId,
1837c7c8e0dSIan Levesque                   const XRaySledMap &InstrMap) XRAY_NEVER_INSTRUMENT {
1847c7c8e0dSIan Levesque   int32_t CurFn = 0;
1857c7c8e0dSIan Levesque   uint64_t LastFnAddr = 0;
1867c7c8e0dSIan Levesque   XRayFunctionSledIndex Index = {nullptr, nullptr};
1877c7c8e0dSIan Levesque 
1887c7c8e0dSIan Levesque   for (std::size_t I = 0; I < InstrMap.Entries && CurFn <= FuncId; I++) {
1897c7c8e0dSIan Levesque     const auto &Sled = InstrMap.Sleds[I];
1907c7c8e0dSIan Levesque     const auto Function = Sled.function();
1917c7c8e0dSIan Levesque     if (Function != LastFnAddr) {
1927c7c8e0dSIan Levesque       CurFn++;
1937c7c8e0dSIan Levesque       LastFnAddr = Function;
1947c7c8e0dSIan Levesque     }
1957c7c8e0dSIan Levesque 
1967c7c8e0dSIan Levesque     if (CurFn == FuncId) {
1977c7c8e0dSIan Levesque       if (Index.Begin == nullptr)
1987c7c8e0dSIan Levesque         Index.Begin = &Sled;
1997c7c8e0dSIan Levesque       Index.End = &Sled;
2007c7c8e0dSIan Levesque     }
2017c7c8e0dSIan Levesque   }
2027c7c8e0dSIan Levesque 
2037c7c8e0dSIan Levesque   Index.End += 1;
2047c7c8e0dSIan Levesque 
2057c7c8e0dSIan Levesque   return Index;
2067c7c8e0dSIan Levesque }
2077c7c8e0dSIan Levesque 
patchFunction(int32_t FuncId,bool Enable)208b3018603SNico Weber XRayPatchingStatus patchFunction(int32_t FuncId,
209b3018603SNico Weber                                  bool Enable) XRAY_NEVER_INSTRUMENT {
210b3018603SNico Weber   if (!atomic_load(&XRayInitialized,
211b3018603SNico Weber                                 memory_order_acquire))
212b3018603SNico Weber     return XRayPatchingStatus::NOT_INITIALIZED; // Not initialized.
213b3018603SNico Weber 
214b3018603SNico Weber   uint8_t NotPatching = false;
215b3018603SNico Weber   if (!atomic_compare_exchange_strong(
216b3018603SNico Weber           &XRayPatching, &NotPatching, true, memory_order_acq_rel))
217b3018603SNico Weber     return XRayPatchingStatus::ONGOING; // Already patching.
218b3018603SNico Weber 
219b3018603SNico Weber   // Next, we look for the function index.
220b3018603SNico Weber   XRaySledMap InstrMap;
221b3018603SNico Weber   {
222b3018603SNico Weber     SpinMutexLock Guard(&XRayInstrMapMutex);
223b3018603SNico Weber     InstrMap = XRayInstrMap;
224b3018603SNico Weber   }
225b3018603SNico Weber 
226b3018603SNico Weber   // If we don't have an index, we can't patch individual functions.
227b3018603SNico Weber   if (InstrMap.Functions == 0)
228b3018603SNico Weber     return XRayPatchingStatus::NOT_INITIALIZED;
229b3018603SNico Weber 
230b3018603SNico Weber   // FuncId must be a positive number, less than the number of functions
231b3018603SNico Weber   // instrumented.
232b3018603SNico Weber   if (FuncId <= 0 || static_cast<size_t>(FuncId) > InstrMap.Functions) {
233b3018603SNico Weber     Report("Invalid function id provided: %d\n", FuncId);
234b3018603SNico Weber     return XRayPatchingStatus::FAILED;
235b3018603SNico Weber   }
236b3018603SNico Weber 
237b3018603SNico Weber   // Now we patch ths sleds for this specific function.
2387c7c8e0dSIan Levesque   auto SledRange = InstrMap.SledsIndex ? InstrMap.SledsIndex[FuncId - 1]
2397c7c8e0dSIan Levesque                                        : findFunctionSleds(FuncId, InstrMap);
240b3018603SNico Weber   auto *f = SledRange.Begin;
241b3018603SNico Weber   auto *e = SledRange.End;
242b3018603SNico Weber   bool SucceedOnce = false;
243b3018603SNico Weber   while (f != e)
244b3018603SNico Weber     SucceedOnce |= patchSled(*f++, Enable, FuncId);
245b3018603SNico Weber 
246b3018603SNico Weber   atomic_store(&XRayPatching, false,
247b3018603SNico Weber                             memory_order_release);
248b3018603SNico Weber 
249b3018603SNico Weber   if (!SucceedOnce) {
250b3018603SNico Weber     Report("Failed patching any sled for function '%d'.", FuncId);
251b3018603SNico Weber     return XRayPatchingStatus::FAILED;
252b3018603SNico Weber   }
253b3018603SNico Weber 
254b3018603SNico Weber   return XRayPatchingStatus::SUCCESS;
255b3018603SNico Weber }
256b3018603SNico Weber 
257b3018603SNico Weber // controlPatching implements the common internals of the patching/unpatching
258b3018603SNico Weber // implementation. |Enable| defines whether we're enabling or disabling the
259b3018603SNico Weber // runtime XRay instrumentation.
controlPatching(bool Enable)260b3018603SNico Weber XRayPatchingStatus controlPatching(bool Enable) XRAY_NEVER_INSTRUMENT {
261b3018603SNico Weber   if (!atomic_load(&XRayInitialized,
262b3018603SNico Weber                                 memory_order_acquire))
263b3018603SNico Weber     return XRayPatchingStatus::NOT_INITIALIZED; // Not initialized.
264b3018603SNico Weber 
265b3018603SNico Weber   uint8_t NotPatching = false;
266b3018603SNico Weber   if (!atomic_compare_exchange_strong(
267b3018603SNico Weber           &XRayPatching, &NotPatching, true, memory_order_acq_rel))
268b3018603SNico Weber     return XRayPatchingStatus::ONGOING; // Already patching.
269b3018603SNico Weber 
270b3018603SNico Weber   uint8_t PatchingSuccess = false;
271b3018603SNico Weber   auto XRayPatchingStatusResetter =
272b3018603SNico Weber       at_scope_exit([&PatchingSuccess] {
273b3018603SNico Weber         if (!PatchingSuccess)
274b3018603SNico Weber           atomic_store(&XRayPatching, false,
275b3018603SNico Weber                                     memory_order_release);
276b3018603SNico Weber       });
277b3018603SNico Weber 
278b3018603SNico Weber   XRaySledMap InstrMap;
279b3018603SNico Weber   {
280b3018603SNico Weber     SpinMutexLock Guard(&XRayInstrMapMutex);
281b3018603SNico Weber     InstrMap = XRayInstrMap;
282b3018603SNico Weber   }
283b3018603SNico Weber   if (InstrMap.Entries == 0)
284b3018603SNico Weber     return XRayPatchingStatus::NOT_INITIALIZED;
285b3018603SNico Weber 
286b3018603SNico Weber   uint32_t FuncId = 1;
287b3018603SNico Weber   uint64_t CurFun = 0;
288b3018603SNico Weber 
289b3018603SNico Weber   // First we want to find the bounds for which we have instrumentation points,
290b3018603SNico Weber   // and try to get as few calls to mprotect(...) as possible. We're assuming
291b3018603SNico Weber   // that all the sleds for the instrumentation map are contiguous as a single
292b3018603SNico Weber   // set of pages. When we do support dynamic shared object instrumentation,
293b3018603SNico Weber   // we'll need to do this for each set of page load offsets per DSO loaded. For
294b3018603SNico Weber   // now we're assuming we can mprotect the whole section of text between the
295b3018603SNico Weber   // minimum sled address and the maximum sled address (+ the largest sled
296b3018603SNico Weber   // size).
2975771c985SFangrui Song   auto *MinSled = &InstrMap.Sleds[0];
2985771c985SFangrui Song   auto *MaxSled = &InstrMap.Sleds[InstrMap.Entries - 1];
299b3018603SNico Weber   for (std::size_t I = 0; I < InstrMap.Entries; I++) {
300b3018603SNico Weber     const auto &Sled = InstrMap.Sleds[I];
3015771c985SFangrui Song     if (Sled.address() < MinSled->address())
3025771c985SFangrui Song       MinSled = &Sled;
3035771c985SFangrui Song     if (Sled.address() > MaxSled->address())
3045771c985SFangrui Song       MaxSled = &Sled;
305b3018603SNico Weber   }
306b3018603SNico Weber 
307b3018603SNico Weber   const size_t PageSize = flags()->xray_page_size_override > 0
308b3018603SNico Weber                               ? flags()->xray_page_size_override
309b3018603SNico Weber                               : GetPageSizeCached();
310b3018603SNico Weber   if ((PageSize == 0) || ((PageSize & (PageSize - 1)) != 0)) {
311bbba9d8cSDimitry Andric     Report("System page size is not a power of two: %zu\n", PageSize);
312b3018603SNico Weber     return XRayPatchingStatus::FAILED;
313b3018603SNico Weber   }
314b3018603SNico Weber 
315b3018603SNico Weber   void *PageAlignedAddr =
3165771c985SFangrui Song       reinterpret_cast<void *>(MinSled->address() & ~(PageSize - 1));
317b3018603SNico Weber   size_t MProtectLen =
3185771c985SFangrui Song       (MaxSled->address() - reinterpret_cast<uptr>(PageAlignedAddr)) +
3195771c985SFangrui Song       cSledLength;
320b3018603SNico Weber   MProtectHelper Protector(PageAlignedAddr, MProtectLen, PageSize);
321b3018603SNico Weber   if (Protector.MakeWriteable() == -1) {
322b3018603SNico Weber     Report("Failed mprotect: %d\n", errno);
323b3018603SNico Weber     return XRayPatchingStatus::FAILED;
324b3018603SNico Weber   }
325b3018603SNico Weber 
326b3018603SNico Weber   for (std::size_t I = 0; I < InstrMap.Entries; ++I) {
327b3018603SNico Weber     auto &Sled = InstrMap.Sleds[I];
32810bc1258SFangrui Song     auto F = Sled.function();
329b3018603SNico Weber     if (CurFun == 0)
330b3018603SNico Weber       CurFun = F;
331b3018603SNico Weber     if (F != CurFun) {
332b3018603SNico Weber       ++FuncId;
333b3018603SNico Weber       CurFun = F;
334b3018603SNico Weber     }
335b3018603SNico Weber     patchSled(Sled, Enable, FuncId);
336b3018603SNico Weber   }
337b3018603SNico Weber   atomic_store(&XRayPatching, false,
338b3018603SNico Weber                             memory_order_release);
339b3018603SNico Weber   PatchingSuccess = true;
340b3018603SNico Weber   return XRayPatchingStatus::SUCCESS;
341b3018603SNico Weber }
342b3018603SNico Weber 
mprotectAndPatchFunction(int32_t FuncId,bool Enable)343b3018603SNico Weber XRayPatchingStatus mprotectAndPatchFunction(int32_t FuncId,
344b3018603SNico Weber                                             bool Enable) XRAY_NEVER_INSTRUMENT {
345b3018603SNico Weber   XRaySledMap InstrMap;
346b3018603SNico Weber   {
347b3018603SNico Weber     SpinMutexLock Guard(&XRayInstrMapMutex);
348b3018603SNico Weber     InstrMap = XRayInstrMap;
349b3018603SNico Weber   }
350b3018603SNico Weber 
351b3018603SNico Weber   // FuncId must be a positive number, less than the number of functions
352b3018603SNico Weber   // instrumented.
353b3018603SNico Weber   if (FuncId <= 0 || static_cast<size_t>(FuncId) > InstrMap.Functions) {
354b3018603SNico Weber     Report("Invalid function id provided: %d\n", FuncId);
355b3018603SNico Weber     return XRayPatchingStatus::FAILED;
356b3018603SNico Weber   }
357b3018603SNico Weber 
358b3018603SNico Weber   const size_t PageSize = flags()->xray_page_size_override > 0
359b3018603SNico Weber                               ? flags()->xray_page_size_override
360b3018603SNico Weber                               : GetPageSizeCached();
361b3018603SNico Weber   if ((PageSize == 0) || ((PageSize & (PageSize - 1)) != 0)) {
362bbba9d8cSDimitry Andric     Report("Provided page size is not a power of two: %zu\n", PageSize);
363b3018603SNico Weber     return XRayPatchingStatus::FAILED;
364b3018603SNico Weber   }
365b3018603SNico Weber 
366a1e7e401SKazuaki Ishizaki   // Here we compute the minimum sled and maximum sled associated with a
367b3018603SNico Weber   // particular function ID.
3687c7c8e0dSIan Levesque   auto SledRange = InstrMap.SledsIndex ? InstrMap.SledsIndex[FuncId - 1]
3697c7c8e0dSIan Levesque                                        : findFunctionSleds(FuncId, InstrMap);
370b3018603SNico Weber   auto *f = SledRange.Begin;
371b3018603SNico Weber   auto *e = SledRange.End;
3725771c985SFangrui Song   auto *MinSled = f;
3735771c985SFangrui Song   auto *MaxSled = (SledRange.End - 1);
374b3018603SNico Weber   while (f != e) {
3755771c985SFangrui Song     if (f->address() < MinSled->address())
3765771c985SFangrui Song       MinSled = f;
3775771c985SFangrui Song     if (f->address() > MaxSled->address())
3785771c985SFangrui Song       MaxSled = f;
379b3018603SNico Weber     ++f;
380b3018603SNico Weber   }
381b3018603SNico Weber 
382b3018603SNico Weber   void *PageAlignedAddr =
3835771c985SFangrui Song       reinterpret_cast<void *>(MinSled->address() & ~(PageSize - 1));
384b3018603SNico Weber   size_t MProtectLen =
3855771c985SFangrui Song       (MaxSled->address() - reinterpret_cast<uptr>(PageAlignedAddr)) +
3865771c985SFangrui Song       cSledLength;
387b3018603SNico Weber   MProtectHelper Protector(PageAlignedAddr, MProtectLen, PageSize);
388b3018603SNico Weber   if (Protector.MakeWriteable() == -1) {
389b3018603SNico Weber     Report("Failed mprotect: %d\n", errno);
390b3018603SNico Weber     return XRayPatchingStatus::FAILED;
391b3018603SNico Weber   }
392b3018603SNico Weber   return patchFunction(FuncId, Enable);
393b3018603SNico Weber }
394b3018603SNico Weber 
395b3018603SNico Weber } // namespace
396b3018603SNico Weber 
397b3018603SNico Weber } // namespace __xray
398b3018603SNico Weber 
399b3018603SNico Weber using namespace __xray;
400b3018603SNico Weber 
401b3018603SNico Weber // The following functions are declared `extern "C" {...}` in the header, hence
402b3018603SNico Weber // they're defined in the global namespace.
403b3018603SNico Weber 
__xray_set_handler(void (* entry)(int32_t,XRayEntryType))404b3018603SNico Weber int __xray_set_handler(void (*entry)(int32_t,
405b3018603SNico Weber                                      XRayEntryType)) XRAY_NEVER_INSTRUMENT {
406b3018603SNico Weber   if (atomic_load(&XRayInitialized,
407b3018603SNico Weber                                memory_order_acquire)) {
408b3018603SNico Weber 
409b3018603SNico Weber     atomic_store(&__xray::XRayPatchedFunction,
410b3018603SNico Weber                               reinterpret_cast<uintptr_t>(entry),
411b3018603SNico Weber                               memory_order_release);
412b3018603SNico Weber     return 1;
413b3018603SNico Weber   }
414b3018603SNico Weber   return 0;
415b3018603SNico Weber }
416b3018603SNico Weber 
__xray_set_customevent_handler(void (* entry)(void *,size_t))417b3018603SNico Weber int __xray_set_customevent_handler(void (*entry)(void *, size_t))
418b3018603SNico Weber     XRAY_NEVER_INSTRUMENT {
419b3018603SNico Weber   if (atomic_load(&XRayInitialized,
420b3018603SNico Weber                                memory_order_acquire)) {
421b3018603SNico Weber     atomic_store(&__xray::XRayPatchedCustomEvent,
422b3018603SNico Weber                               reinterpret_cast<uintptr_t>(entry),
423b3018603SNico Weber                               memory_order_release);
424b3018603SNico Weber     return 1;
425b3018603SNico Weber   }
426b3018603SNico Weber   return 0;
427b3018603SNico Weber }
428b3018603SNico Weber 
__xray_set_typedevent_handler(void (* entry)(uint16_t,const void *,size_t))429b3018603SNico Weber int __xray_set_typedevent_handler(void (*entry)(
430b3018603SNico Weber     uint16_t, const void *, size_t)) XRAY_NEVER_INSTRUMENT {
431b3018603SNico Weber   if (atomic_load(&XRayInitialized,
432b3018603SNico Weber                                memory_order_acquire)) {
433b3018603SNico Weber     atomic_store(&__xray::XRayPatchedTypedEvent,
434b3018603SNico Weber                               reinterpret_cast<uintptr_t>(entry),
435b3018603SNico Weber                               memory_order_release);
436b3018603SNico Weber     return 1;
437b3018603SNico Weber   }
438b3018603SNico Weber   return 0;
439b3018603SNico Weber }
440b3018603SNico Weber 
__xray_remove_handler()441b3018603SNico Weber int __xray_remove_handler() XRAY_NEVER_INSTRUMENT {
442b3018603SNico Weber   return __xray_set_handler(nullptr);
443b3018603SNico Weber }
444b3018603SNico Weber 
__xray_remove_customevent_handler()445b3018603SNico Weber int __xray_remove_customevent_handler() XRAY_NEVER_INSTRUMENT {
446b3018603SNico Weber   return __xray_set_customevent_handler(nullptr);
447b3018603SNico Weber }
448b3018603SNico Weber 
__xray_remove_typedevent_handler()449b3018603SNico Weber int __xray_remove_typedevent_handler() XRAY_NEVER_INSTRUMENT {
450b3018603SNico Weber   return __xray_set_typedevent_handler(nullptr);
451b3018603SNico Weber }
452b3018603SNico Weber 
__xray_register_event_type(const char * const event_type)453b3018603SNico Weber uint16_t __xray_register_event_type(
454b3018603SNico Weber     const char *const event_type) XRAY_NEVER_INSTRUMENT {
455b3018603SNico Weber   TypeDescriptorMapType::Handle h(&TypeDescriptorAddressMap, (uptr)event_type);
456b3018603SNico Weber   if (h.created()) {
457b3018603SNico Weber     h->type_id = atomic_fetch_add(
458b3018603SNico Weber         &TypeEventDescriptorCounter, 1, memory_order_acq_rel);
459b3018603SNico Weber     h->description_string_length = strnlen(event_type, 1024);
460b3018603SNico Weber   }
461b3018603SNico Weber   return h->type_id;
462b3018603SNico Weber }
463b3018603SNico Weber 
__xray_patch()464b3018603SNico Weber XRayPatchingStatus __xray_patch() XRAY_NEVER_INSTRUMENT {
465b3018603SNico Weber   return controlPatching(true);
466b3018603SNico Weber }
467b3018603SNico Weber 
__xray_unpatch()468b3018603SNico Weber XRayPatchingStatus __xray_unpatch() XRAY_NEVER_INSTRUMENT {
469b3018603SNico Weber   return controlPatching(false);
470b3018603SNico Weber }
471b3018603SNico Weber 
__xray_patch_function(int32_t FuncId)472b3018603SNico Weber XRayPatchingStatus __xray_patch_function(int32_t FuncId) XRAY_NEVER_INSTRUMENT {
473b3018603SNico Weber   return mprotectAndPatchFunction(FuncId, true);
474b3018603SNico Weber }
475b3018603SNico Weber 
476b3018603SNico Weber XRayPatchingStatus
__xray_unpatch_function(int32_t FuncId)477b3018603SNico Weber __xray_unpatch_function(int32_t FuncId) XRAY_NEVER_INSTRUMENT {
478b3018603SNico Weber   return mprotectAndPatchFunction(FuncId, false);
479b3018603SNico Weber }
480b3018603SNico Weber 
__xray_set_handler_arg1(void (* entry)(int32_t,XRayEntryType,uint64_t))481b3018603SNico Weber int __xray_set_handler_arg1(void (*entry)(int32_t, XRayEntryType, uint64_t)) {
482b3018603SNico Weber   if (!atomic_load(&XRayInitialized,
483b3018603SNico Weber                                 memory_order_acquire))
484b3018603SNico Weber     return 0;
485b3018603SNico Weber 
486b3018603SNico Weber   // A relaxed write might not be visible even if the current thread gets
487b3018603SNico Weber   // scheduled on a different CPU/NUMA node.  We need to wait for everyone to
488b3018603SNico Weber   // have this handler installed for consistency of collected data across CPUs.
489b3018603SNico Weber   atomic_store(&XRayArgLogger, reinterpret_cast<uint64_t>(entry),
490b3018603SNico Weber                             memory_order_release);
491b3018603SNico Weber   return 1;
492b3018603SNico Weber }
493b3018603SNico Weber 
__xray_remove_handler_arg1()494b3018603SNico Weber int __xray_remove_handler_arg1() { return __xray_set_handler_arg1(nullptr); }
495b3018603SNico Weber 
__xray_function_address(int32_t FuncId)496b3018603SNico Weber uintptr_t __xray_function_address(int32_t FuncId) XRAY_NEVER_INSTRUMENT {
4977c7c8e0dSIan Levesque   XRaySledMap InstrMap;
4987c7c8e0dSIan Levesque   {
499b3018603SNico Weber     SpinMutexLock Guard(&XRayInstrMapMutex);
5007c7c8e0dSIan Levesque     InstrMap = XRayInstrMap;
5017c7c8e0dSIan Levesque   }
5027c7c8e0dSIan Levesque 
5037c7c8e0dSIan Levesque   if (FuncId <= 0 || static_cast<size_t>(FuncId) > InstrMap.Functions)
504b3018603SNico Weber     return 0;
5057c7c8e0dSIan Levesque   const XRaySledEntry *Sled = InstrMap.SledsIndex
5067c7c8e0dSIan Levesque                                   ? InstrMap.SledsIndex[FuncId - 1].Begin
5077c7c8e0dSIan Levesque                                   : findFunctionSleds(FuncId, InstrMap).Begin;
5087c7c8e0dSIan Levesque   return Sled->function()
509b3018603SNico Weber // On PPC, function entries are always aligned to 16 bytes. The beginning of a
510b3018603SNico Weber // sled might be a local entry, which is always +8 based on the global entry.
511b3018603SNico Weber // Always return the global entry.
512b3018603SNico Weber #ifdef __PPC__
513b3018603SNico Weber          & ~0xf
514b3018603SNico Weber #endif
515b3018603SNico Weber       ;
516b3018603SNico Weber }
517b3018603SNico Weber 
__xray_max_function_id()518b3018603SNico Weber size_t __xray_max_function_id() XRAY_NEVER_INSTRUMENT {
519b3018603SNico Weber   SpinMutexLock Guard(&XRayInstrMapMutex);
520b3018603SNico Weber   return XRayInstrMap.Functions;
521b3018603SNico Weber }
522