[compiler-rt] [llvm] Introduce XRay object mapping file to enable symbolization for DSOs (PR #133269)

via llvm-commits llvm-commits at lists.llvm.org
Thu Mar 27 09:01:11 PDT 2025


github-actions[bot] wrote:

<!--LLVM CODE FORMAT COMMENT: {clang-format}-->


:warning: C/C++ code formatter, clang-format found issues in your code. :warning:

<details>
<summary>
You can test this locally with the following command:
</summary>

``````````bash
git-clang-format --diff 34fa037c4fd7f38faada5beedc63ad234e904247 bc0ae8d83cc0a297b26b4dcb64814347a6b15d8b --extensions h,cpp -- compiler-rt/include/xray/xray_interface.h compiler-rt/lib/xray/xray_basic_logging.cpp compiler-rt/lib/xray/xray_init.cpp compiler-rt/lib/xray/xray_interface.cpp compiler-rt/lib/xray/xray_interface_internal.h compiler-rt/lib/xray/xray_utils.cpp compiler-rt/lib/xray/xray_utils.h llvm/tools/llvm-xray/xray-extract.cpp
``````````

</details>

<details>
<summary>
View the diff from clang-format here.
</summary>

``````````diff
diff --git a/compiler-rt/include/xray/xray_interface.h b/compiler-rt/include/xray/xray_interface.h
index f8b07df688..df200c15a7 100644
--- a/compiler-rt/include/xray/xray_interface.h
+++ b/compiler-rt/include/xray/xray_interface.h
@@ -169,7 +169,7 @@ extern int32_t __xray_pack_id(int32_t FuncId, int32_t ObjId);
 /// from.
 /// The returned string is owned by the XRay runtime and remains valid until the
 /// end of execution.
-extern const char* __xray_object_path(int32_t ObjId);
+extern const char *__xray_object_path(int32_t ObjId);
 
 /// Initialize the required XRay data structures. This is useful in cases where
 /// users want to control precisely when the XRay instrumentation data
diff --git a/compiler-rt/lib/xray/xray_basic_logging.cpp b/compiler-rt/lib/xray/xray_basic_logging.cpp
index c11b9bd2d7..78a1e8b2cd 100644
--- a/compiler-rt/lib/xray/xray_basic_logging.cpp
+++ b/compiler-rt/lib/xray/xray_basic_logging.cpp
@@ -450,9 +450,8 @@ static void writeObjectMapping() {
     Report("Writing object mapping file.\n");
 
   char MapFilename[256] = {};
-  int NeededLength = internal_snprintf(
-      MapFilename, sizeof(MapFilename), "%s.map.yaml",
-      LW->GetFilename());
+  int NeededLength = internal_snprintf(MapFilename, sizeof(MapFilename),
+                                       "%s.map.yaml", LW->GetFilename());
   if (NeededLength > int(sizeof(MapFilename))) {
     Report("XRay map file name too long (%d): %s\n", NeededLength, MapFilename);
     return;
@@ -489,7 +488,6 @@ XRayLogFlushStatus basicLoggingFlush() XRAY_NEVER_INSTRUMENT {
 void basicLoggingHandleArg0Empty(int32_t, XRayEntryType) XRAY_NEVER_INSTRUMENT {
 }
 
-
 bool basicLogDynamicInitializer() XRAY_NEVER_INSTRUMENT {
   XRayLogImpl Impl{
       basicLoggingInit,
@@ -532,7 +530,10 @@ bool basicLogDynamicInitializer() XRAY_NEVER_INSTRUMENT {
     pthread_once(&DynamicOnce, +[] {
       static void *FakeTLD = nullptr;
       FakeTLD = &getThreadLocalData();
-      Atexit(+[] { TLDDestructor(FakeTLD); writeObjectMapping(); });
+      Atexit(+[] {
+        TLDDestructor(FakeTLD);
+        writeObjectMapping();
+      });
     });
   }
   return true;
diff --git a/compiler-rt/lib/xray/xray_init.cpp b/compiler-rt/lib/xray/xray_init.cpp
index abc24120e4..b1de0386ef 100644
--- a/compiler-rt/lib/xray/xray_init.cpp
+++ b/compiler-rt/lib/xray/xray_init.cpp
@@ -67,40 +67,41 @@ atomic_uint8_t XRayFlagsInitialized{0};
 // A mutex to allow only one thread to initialize the XRay data structures.
 SpinMutex XRayInitMutex;
 
-
 namespace {
 
 struct DlIteratePhdrData {
   intptr_t TargetSledAddr{0};
-  const char* Path{nullptr};
+  const char *Path{nullptr};
   bool Found{false};
 };
 
-const char* DetectObjPath(bool IsDSO, uint64_t Addr) XRAY_NEVER_INSTRUMENT {
+const char *DetectObjPath(bool IsDSO, uint64_t Addr) XRAY_NEVER_INSTRUMENT {
   if (IsDSO) {
     // Detection of DSO paths only supported for ELF
 #ifdef __ELF__
     // Look for the given address by iterating over the loaded DSOs
     DlIteratePhdrData Data;
     Data.TargetSledAddr = Addr;
-    dl_iterate_phdr([](dl_phdr_info *info, size_t size, void *arg) -> int {
-      auto *data = (DlIteratePhdrData *)arg;
-      data->Found = false;
-      for (int i = 0; i < info->dlpi_phnum; i++) {
-        const auto *phdr = &info->dlpi_phdr[i];
-        if (phdr->p_type != PT_LOAD)
-          continue;
-        intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
-        intptr_t end = beg + phdr->p_memsz;
-
-        if (beg <= data->TargetSledAddr && data->TargetSledAddr < end) {
-          data->Path = info->dlpi_name;
-          data->Found = true;
-          return 1;
-        }
-      }
-      return 0;
-    }, &Data);
+    dl_iterate_phdr(
+        [](dl_phdr_info *info, size_t size, void *arg) -> int {
+          auto *data = (DlIteratePhdrData *)arg;
+          data->Found = false;
+          for (int i = 0; i < info->dlpi_phnum; i++) {
+            const auto *phdr = &info->dlpi_phdr[i];
+            if (phdr->p_type != PT_LOAD)
+              continue;
+            intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
+            intptr_t end = beg + phdr->p_memsz;
+
+            if (beg <= data->TargetSledAddr && data->TargetSledAddr < end) {
+              data->Path = info->dlpi_name;
+              data->Found = true;
+              return 1;
+            }
+          }
+          return 0;
+        },
+        &Data);
     if (Data.Found) {
       return Data.Path;
     }
@@ -111,11 +112,11 @@ const char* DetectObjPath(bool IsDSO, uint64_t Addr) XRAY_NEVER_INSTRUMENT {
   // If the address is in the main executable, use the built-in sanitizer
   // functionality.
   __sanitizer::UpdateProcessName();
-  const char* ExecName = __sanitizer::GetProcessName();
+  const char *ExecName = __sanitizer::GetProcessName();
   // TODO: Is this the full path?
   return ExecName;
 }
-}
+} // namespace
 
 // Registers XRay sleds and trampolines coming from the main executable or one
 // of the linked DSOs.
@@ -162,12 +163,13 @@ __xray_register_sleds(const XRaySledEntry *SledsBegin,
   if (Verbosity())
     Report("Registering %d new functions!\n", SledMap.Functions);
 
-  const char* Path = DetectObjPath(FromDSO, SledsBegin->address());
+  const char *Path = DetectObjPath(FromDSO, SledsBegin->address());
   if (Path) {
     // Copy needed because DSO path is freed when unloaded.
     SledMap.Path = internal_strdup(Path);
   } else {
-    Report("Unable to determine load path for address %x\n", SledsBegin->address());
+    Report("Unable to determine load path for address %x\n",
+           SledsBegin->address());
   }
 
   {
diff --git a/compiler-rt/lib/xray/xray_interface.cpp b/compiler-rt/lib/xray/xray_interface.cpp
index 7605ce743f..91a4df7361 100644
--- a/compiler-rt/lib/xray/xray_interface.cpp
+++ b/compiler-rt/lib/xray/xray_interface.cpp
@@ -689,7 +689,7 @@ int32_t __xray_pack_id(int32_t FuncId, int32_t ObjId) {
   return __xray::MakePackedId(FuncId, ObjId);
 }
 
-const char* __xray_object_path(int32_t ObjId) {
+const char *__xray_object_path(int32_t ObjId) {
   SpinMutexLock Guard(&XRayInstrMapMutex);
   if (ObjId < 0 || static_cast<uint32_t>(ObjId) >=
                        atomic_load(&XRayNumObjects, memory_order_acquire))
@@ -699,7 +699,7 @@ const char* __xray_object_path(int32_t ObjId) {
 
 #include <stdio.h>
 
-bool __xray_write_object_mapping(const char* outfile) XRAY_NEVER_INSTRUMENT {
+bool __xray_write_object_mapping(const char *outfile) XRAY_NEVER_INSTRUMENT {
   // TODO: Use low-level IO API?
   FILE *of = fopen(outfile, "w");
   if (!of) {
@@ -712,10 +712,11 @@ bool __xray_write_object_mapping(const char* outfile) XRAY_NEVER_INSTRUMENT {
   fprintf(of, "objects:\n");
   int NumObjects = __xray_num_objects();
   for (int ObjId = 0; ObjId < NumObjects; ObjId++) {
-    auto* Path = __xray_object_path(ObjId);
+    auto *Path = __xray_object_path(ObjId);
     if (!Path)
       Report("Unknown path for object %d. The XRay mapping file may be "
-             "incomplete.\n", ObjId);
+             "incomplete.\n",
+             ObjId);
     fprintf(of, "  - id: %d\n", ObjId);
     fprintf(of, "    path: \"%s\"\n", Path ? Path : "");
   }
diff --git a/compiler-rt/lib/xray/xray_interface_internal.h b/compiler-rt/lib/xray/xray_interface_internal.h
index 5d3e4b435b..3bb860c815 100644
--- a/compiler-rt/lib/xray/xray_interface_internal.h
+++ b/compiler-rt/lib/xray/xray_interface_internal.h
@@ -107,7 +107,7 @@ extern int32_t __xray_register_dso(const XRaySledEntry *SledsBegin,
 
 extern bool __xray_deregister_dso(int32_t ObjId);
 
-extern bool __xray_write_object_mapping(const char* outfile);
+extern bool __xray_write_object_mapping(const char *outfile);
 }
 
 namespace __xray {
@@ -139,7 +139,7 @@ struct XRaySledMap {
   XRayTrampolines Trampolines;
   bool FromDSO;
   bool Loaded;
-  const char* Path;
+  const char *Path;
 };
 
 bool patchFunctionEntry(bool Enable, uint32_t FuncId, const XRaySledEntry &Sled,
diff --git a/compiler-rt/lib/xray/xray_utils.cpp b/compiler-rt/lib/xray/xray_utils.cpp
index 7563bc18a2..a8c591965b 100644
--- a/compiler-rt/lib/xray/xray_utils.cpp
+++ b/compiler-rt/lib/xray/xray_utils.cpp
@@ -155,9 +155,7 @@ void LogWriter::WriteAll(const char *Begin, const char *End) XRAY_NEVER_INSTRUME
   }
 }
 
-const char* LogWriter::GetFilename() XRAY_NEVER_INSTRUMENT {
-  return Filename;
-}
+const char *LogWriter::GetFilename() XRAY_NEVER_INSTRUMENT { return Filename; }
 
 void LogWriter::Flush() XRAY_NEVER_INSTRUMENT {
   fsync(Fd);
diff --git a/compiler-rt/lib/xray/xray_utils.h b/compiler-rt/lib/xray/xray_utils.h
index 309e4d8be8..3d5d9d3a74 100644
--- a/compiler-rt/lib/xray/xray_utils.h
+++ b/compiler-rt/lib/xray/xray_utils.h
@@ -31,7 +31,7 @@ public:
 #if SANITIZER_FUCHSIA
  LogWriter(zx_handle_t Vmo) : Vmo(Vmo) {}
 #else
-  explicit LogWriter(int Fd, const char* Filename) : Fd(Fd) {
+  explicit LogWriter(int Fd, const char *Filename) : Fd(Fd) {
     internal_strlcpy(this->Filename, Filename, sizeof(this->Filename));
   }
 #endif
@@ -40,7 +40,7 @@ public:
  // Write a character range into a log.
  void WriteAll(const char *Begin, const char *End);
 
- const char* GetFilename();
+ const char *GetFilename();
 
  void Flush();
 
diff --git a/llvm/tools/llvm-xray/xray-extract.cpp b/llvm/tools/llvm-xray/xray-extract.cpp
index 394c4f7051..d0cb63e75e 100644
--- a/llvm/tools/llvm-xray/xray-extract.cpp
+++ b/llvm/tools/llvm-xray/xray-extract.cpp
@@ -12,7 +12,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-
 #include "func-id-helper.h"
 #include "xray-registry.h"
 #include "llvm/Object/ObjectFile.h"
@@ -20,8 +19,8 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Format.h"
-#include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/YAMLTraits.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/XRay/InstrumentationMap.h"
 
 #include <assert.h>
@@ -54,9 +53,10 @@ static cl::opt<bool> Demangle("demangle",
 static cl::opt<bool> NoDemangle("no-demangle",
                                 cl::desc("don't demangle symbols"),
                                 cl::sub(Extract));
-static cl::opt<bool> FromMapping("mapping", cl::init(false),
-                             cl::desc("Create instrumentation map from object map YAML"),
-                             cl::sub(Extract));
+static cl::opt<bool>
+    FromMapping("mapping", cl::init(false),
+                cl::desc("Create instrumentation map from object map YAML"),
+                cl::sub(Extract));
 
 namespace {
 
@@ -70,9 +70,9 @@ struct YAMLXRayObjectMapping {
   std::vector<YAMLXRayObjectMapEntry> Objects;
 };
 
-}
+} // namespace
 
-namespace llvm{
+namespace llvm {
 namespace yaml {
 template <> struct MappingTraits<YAMLXRayObjectMapEntry> {
   static void mapping(IO &IO, YAMLXRayObjectMapEntry &Entry) {
@@ -94,7 +94,8 @@ LLVM_YAML_IS_SEQUENCE_VECTOR(YAMLXRayObjectMapEntry)
 
 namespace {
 
-Error ReadObjectMappingYAML(StringRef Filename, YAMLXRayObjectMapping& Mapping) {
+Error ReadObjectMappingYAML(StringRef Filename,
+                            YAMLXRayObjectMapping &Mapping) {
   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufferOrErr =
       llvm::MemoryBuffer::getFile(ExtractInput);
   if (!FileBufferOrErr) {
@@ -125,6 +126,7 @@ struct IdMappingHelper {
   int32_t MapId(int32_t FnId, int32_t ObjId) const {
     return ((ObjId & ObjBitMask) << NumFnBits) | (FnId & FnBitMask);
   }
+
 private:
   int NumObjBits;
   int NumFnBits;
@@ -132,11 +134,10 @@ private:
   int32_t FnBitMask;
 };
 
-
 void TranslateAndAppendSleds(const InstrumentationMap &Map,
-                             FuncIdConversionHelper &FH,
-                             int ObjId, const IdMappingHelper& IdMapping,
-                             std::vector<YAMLXRaySledEntry>& YAMLSleds) {
+                             FuncIdConversionHelper &FH, int ObjId,
+                             const IdMappingHelper &IdMapping,
+                             std::vector<YAMLXRaySledEntry> &YAMLSleds) {
   auto Sleds = Map.sleds();
   auto SledCount = std::distance(Sleds.begin(), Sleds.end());
   YAMLSleds.reserve(YAMLSleds.size() + SledCount);
@@ -145,9 +146,10 @@ void TranslateAndAppendSleds(const InstrumentationMap &Map,
     if (!FuncId)
       return;
     auto MappedId = IdMapping.MapId(*FuncId, ObjId);
-    YAMLSleds.push_back(
-        {MappedId, Sled.Address, Sled.Function, Sled.Kind, Sled.AlwaysInstrument,
-         ExtractSymbolize ? FH.SymbolOrNumber(*FuncId) : "", Sled.Version});
+    YAMLSleds.push_back({MappedId, Sled.Address, Sled.Function, Sled.Kind,
+                         Sled.AlwaysInstrument,
+                         ExtractSymbolize ? FH.SymbolOrNumber(*FuncId) : "",
+                         Sled.Version});
   }
 }
 
@@ -164,7 +166,7 @@ static CommandRegistration Unused(&Extract, []() -> Error {
       return Err;
     }
     NumObjBits = ObjMapping.NumObjBits;
-    for (auto& Obj : ObjMapping.Objects) {
+    for (auto &Obj : ObjMapping.Objects) {
       Inputs[Obj.ObjId] = Obj.Path;
     }
   } else {
@@ -180,22 +182,22 @@ static CommandRegistration Unused(&Extract, []() -> Error {
 
   std::vector<YAMLXRaySledEntry> YAMLSleds;
 
-  for (auto& [ObjId, Path] : Inputs) {
+  for (auto &[ObjId, Path] : Inputs) {
     auto InstrumentationMapOrError = loadInstrumentationMap(Path);
     if (!InstrumentationMapOrError)
-      return joinErrors(make_error<StringError>(
-                            Twine("Cannot extract instrumentation map from '") +
-                                Path + "'.",
-                            std::make_error_code(std::errc::invalid_argument)),
-                        InstrumentationMapOrError.takeError());
+      return joinErrors(
+          make_error<StringError>(
+              Twine("Cannot extract instrumentation map from '") + Path + "'.",
+              std::make_error_code(std::errc::invalid_argument)),
+          InstrumentationMapOrError.takeError());
 
     const auto &FunctionAddresses =
         InstrumentationMapOrError->getFunctionAddresses();
 
     llvm::xray::FuncIdConversionHelper FuncIdHelper(Path, Symbolizer,
                                                     FunctionAddresses);
-    TranslateAndAppendSleds(*InstrumentationMapOrError, FuncIdHelper,
-                            ObjId, IdMapping, YAMLSleds);
+    TranslateAndAppendSleds(*InstrumentationMapOrError, FuncIdHelper, ObjId,
+                            IdMapping, YAMLSleds);
   }
 
   std::error_code EC;
@@ -207,5 +209,3 @@ static CommandRegistration Unused(&Extract, []() -> Error {
   Out << YAMLSleds;
   return Error::success();
 });
-
-

``````````

</details>


https://github.com/llvm/llvm-project/pull/133269


More information about the llvm-commits mailing list