LLVM 20.0.0git
InstrumentationMap.cpp
Go to the documentation of this file.
1//===- InstrumentationMap.cpp - XRay Instrumentation Map ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of the InstrumentationMap type for XRay sleds.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/Object/Binary.h"
23#include "llvm/Support/Error.h"
27#include <algorithm>
28#include <cstddef>
29#include <cstdint>
30#include <system_error>
31#include <vector>
32
33using namespace llvm;
34using namespace xray;
35
36std::optional<int32_t> InstrumentationMap::getFunctionId(uint64_t Addr) const {
37 auto I = FunctionIds.find(Addr);
38 if (I != FunctionIds.end())
39 return I->second;
40 return std::nullopt;
41}
42
43std::optional<uint64_t>
45 auto I = FunctionAddresses.find(FuncId);
46 if (I != FunctionAddresses.end())
47 return I->second;
48 return std::nullopt;
49}
50
52
53static Error
59
60 // Find the section named "xray_instr_map".
61 if ((!ObjFile.getBinary()->isELF() && !ObjFile.getBinary()->isMachO()) ||
62 !(ObjFile.getBinary()->getArch() == Triple::x86_64 ||
63 ObjFile.getBinary()->getArch() == Triple::loongarch64 ||
64 ObjFile.getBinary()->getArch() == Triple::ppc64le ||
65 ObjFile.getBinary()->getArch() == Triple::arm ||
66 ObjFile.getBinary()->getArch() == Triple::aarch64 ||
67 ObjFile.getBinary()->getArch() == Triple::riscv64))
68 return make_error<StringError>(
69 "File format not supported (only does ELF and Mach-O little endian "
70 "64-bit).",
71 std::make_error_code(std::errc::not_supported));
72
73 StringRef Contents = "";
74 const auto &Sections = ObjFile.getBinary()->sections();
75 uint64_t Address = 0;
76 auto I = llvm::find_if(Sections, [&](object::SectionRef Section) {
77 Expected<StringRef> NameOrErr = Section.getName();
78 if (NameOrErr) {
79 Address = Section.getAddress();
80 return *NameOrErr == "xray_instr_map";
81 }
82 consumeError(NameOrErr.takeError());
83 return false;
84 });
85
86 if (I == Sections.end())
87 return make_error<StringError>(
88 "Failed to find XRay instrumentation map.",
89 std::make_error_code(std::errc::executable_format_error));
90
91 if (Error E = I->getContents().moveInto(Contents))
92 return E;
93
94 RelocMap Relocs;
95 if (ObjFile.getBinary()->isELF()) {
96 uint32_t RelativeRelocation = [](object::ObjectFile *ObjFile) {
97 if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(ObjFile))
98 return ELFObj->getELFFile().getRelativeRelocationType();
99 else if (const auto *ELFObj =
100 dyn_cast<object::ELF32BEObjectFile>(ObjFile))
101 return ELFObj->getELFFile().getRelativeRelocationType();
102 else if (const auto *ELFObj =
103 dyn_cast<object::ELF64LEObjectFile>(ObjFile))
104 return ELFObj->getELFFile().getRelativeRelocationType();
105 else if (const auto *ELFObj =
106 dyn_cast<object::ELF64BEObjectFile>(ObjFile))
107 return ELFObj->getELFFile().getRelativeRelocationType();
108 else
109 return static_cast<uint32_t>(0);
110 }(ObjFile.getBinary());
111
114 std::tie(Supports, Resolver) =
116
117 for (const object::SectionRef &Section : Sections) {
118 for (const object::RelocationRef &Reloc : Section.relocations()) {
119 if (ObjFile.getBinary()->getArch() == Triple::arm) {
120 if (Supports && Supports(Reloc.getType())) {
121 Expected<uint64_t> ValueOrErr = Reloc.getSymbol()->getValue();
122 if (!ValueOrErr)
123 return ValueOrErr.takeError();
124 Relocs.insert(
125 {Reloc.getOffset(),
126 object::resolveRelocation(Resolver, Reloc, *ValueOrErr, 0)});
127 }
128 } else if (Supports && Supports(Reloc.getType())) {
129 auto AddendOrErr = object::ELFRelocationRef(Reloc).getAddend();
130 auto A = AddendOrErr ? *AddendOrErr : 0;
131 Expected<uint64_t> ValueOrErr = Reloc.getSymbol()->getValue();
132 if (!ValueOrErr)
133 // TODO: Test this error.
134 return ValueOrErr.takeError();
135 Relocs.insert(
136 {Reloc.getOffset(),
137 object::resolveRelocation(Resolver, Reloc, *ValueOrErr, A)});
138 } else if (Reloc.getType() == RelativeRelocation) {
139 if (auto AddendOrErr = object::ELFRelocationRef(Reloc).getAddend())
140 Relocs.insert({Reloc.getOffset(), *AddendOrErr});
141 }
142 }
143 }
144 }
145
146 // Copy the instrumentation map data into the Sleds data structure.
147 auto C = Contents.bytes_begin();
148 bool Is32Bit = ObjFile.getBinary()->makeTriple().isArch32Bit();
149 size_t ELFSledEntrySize = Is32Bit ? 16 : 32;
150
151 if ((C - Contents.bytes_end()) % ELFSledEntrySize != 0)
152 return make_error<StringError>(
153 Twine("Instrumentation map entries not evenly divisible by size of "
154 "an XRay sled entry."),
155 std::make_error_code(std::errc::executable_format_error));
156
157 auto RelocateOrElse = [&](uint64_t Offset, uint64_t Address) {
158 if (!Address) {
159 uint64_t A = I->getAddress() + C - Contents.bytes_begin() + Offset;
160 RelocMap::const_iterator R = Relocs.find(A);
161 if (R != Relocs.end())
162 return R->second;
163 }
164 return Address;
165 };
166
167 const int WordSize = Is32Bit ? 4 : 8;
168 int32_t FuncId = 1;
169 uint64_t CurFn = 0;
170 for (; C != Contents.bytes_end(); C += ELFSledEntrySize) {
171 DataExtractor Extractor(
172 StringRef(reinterpret_cast<const char *>(C), ELFSledEntrySize), true,
173 8);
174 Sleds.push_back({});
175 auto &Entry = Sleds.back();
176 uint64_t OffsetPtr = 0;
177 uint64_t AddrOff = OffsetPtr;
178 if (Is32Bit)
179 Entry.Address = RelocateOrElse(AddrOff, Extractor.getU32(&OffsetPtr));
180 else
181 Entry.Address = RelocateOrElse(AddrOff, Extractor.getU64(&OffsetPtr));
182 uint64_t FuncOff = OffsetPtr;
183 if (Is32Bit)
184 Entry.Function = RelocateOrElse(FuncOff, Extractor.getU32(&OffsetPtr));
185 else
186 Entry.Function = RelocateOrElse(FuncOff, Extractor.getU64(&OffsetPtr));
187 auto Kind = Extractor.getU8(&OffsetPtr);
188 static constexpr SledEntry::FunctionKinds Kinds[] = {
193 if (Kind >= std::size(Kinds))
194 return errorCodeToError(
195 std::make_error_code(std::errc::executable_format_error));
196 Entry.Kind = Kinds[Kind];
197 Entry.AlwaysInstrument = Extractor.getU8(&OffsetPtr) != 0;
198 Entry.Version = Extractor.getU8(&OffsetPtr);
199 if (Entry.Version >= 2) {
200 Entry.Address += C - Contents.bytes_begin() + Address;
201 Entry.Function += C - Contents.bytes_begin() + WordSize + Address;
202 }
203
204 // We do replicate the function id generation scheme implemented in the
205 // XRay runtime.
206 // FIXME: Figure out how to keep this consistent with the XRay runtime.
207 if (CurFn == 0) {
208 CurFn = Entry.Function;
209 FunctionAddresses[FuncId] = Entry.Function;
210 FunctionIds[Entry.Function] = FuncId;
211 }
212 if (Entry.Function != CurFn) {
213 ++FuncId;
214 CurFn = Entry.Function;
215 FunctionAddresses[FuncId] = Entry.Function;
216 FunctionIds[Entry.Function] = FuncId;
217 }
218 }
219 return Error::success();
220}
221
222static Error
223loadYAML(sys::fs::file_t Fd, size_t FileSize, StringRef Filename,
227 std::error_code EC;
231 if (EC)
232 return make_error<StringError>(
233 Twine("Failed memory-mapping file '") + Filename + "'.", EC);
234
235 std::vector<YAMLXRaySledEntry> YAMLSleds;
236 yaml::Input In(StringRef(MappedFile.data(), MappedFile.size()));
237 In >> YAMLSleds;
238 if (In.error())
239 return make_error<StringError>(
240 Twine("Failed loading YAML document from '") + Filename + "'.",
241 In.error());
242
243 Sleds.reserve(YAMLSleds.size());
244 for (const auto &Y : YAMLSleds) {
245 FunctionAddresses[Y.FuncId] = Y.Function;
246 FunctionIds[Y.Function] = Y.FuncId;
247 Sleds.push_back(SledEntry{Y.Address, Y.Function, Y.Kind, Y.AlwaysInstrument,
248 Y.Version});
249 }
250 return Error::success();
251}
252
253// FIXME: Create error types that encapsulate a bit more information than what
254// StringError instances contain.
257 // At this point we assume the file is an object file -- and if that doesn't
258 // work, we treat it as YAML.
259 // FIXME: Extend to support non-ELF and non-x86_64 binaries.
260
262 auto ObjectFileOrError = object::ObjectFile::createObjectFile(Filename);
263 if (!ObjectFileOrError) {
264 auto E = ObjectFileOrError.takeError();
265 // We try to load it as YAML if the ELF load didn't work.
268 if (!FdOrErr) {
269 // Report the ELF load error if YAML failed.
270 consumeError(FdOrErr.takeError());
271 return std::move(E);
272 }
273
274 uint64_t FileSize;
275 if (sys::fs::file_size(Filename, FileSize))
276 return std::move(E);
277
278 // If the file is empty, we return the original error.
279 if (FileSize == 0)
280 return std::move(E);
281
282 // From this point on the errors will be only for the YAML parts, so we
283 // consume the errors at this point.
284 consumeError(std::move(E));
285 if (auto E = loadYAML(*FdOrErr, FileSize, Filename, Map.Sleds,
286 Map.FunctionAddresses, Map.FunctionIds))
287 return std::move(E);
288 } else if (auto E = loadObj(Filename, *ObjectFileOrError, Map.Sleds,
289 Map.FunctionAddresses, Map.FunctionIds)) {
290 return std::move(E);
291 }
292 return Map;
293}
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file defines the DenseMap class.
uint64_t Addr
static void getAddend(uint64_t &, const Elf_Rel_Impl< ELFT, false > &)
Definition: ELFObject.cpp:1647
static Error loadObj(StringRef Filename, object::OwningBinary< object::ObjectFile > &ObjFile, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds)
static Error loadYAML(sys::fs::file_t Fd, size_t FileSize, StringRef Filename, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds)
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
Profile::FuncID FuncId
Definition: Profile.cpp:321
This file contains some templates that are useful if you are working with the STL at all.
uint32_t getU32(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint32_t value from *offset_ptr.
uint8_t getU8(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint8_t value from *offset_ptr.
uint64_t getU64(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint64_t value from *offset_ptr.
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:156
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2203
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
const unsigned char * bytes_end() const
Definition: StringRef.h:131
const unsigned char * bytes_begin() const
Definition: StringRef.h:128
@ loongarch64
Definition: Triple.h:62
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Expected< int64_t > getAddend() const
This class is the base class for all object file types.
Definition: ObjectFile.h:229
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:209
This is a value type class that represents a single relocation in the list of relocations in the obje...
Definition: ObjectFile.h:52
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
This class represents a memory mapped file.
Definition: FileSystem.h:1266
@ readonly
May only access map via const_data as read only.
Definition: FileSystem.h:1269
The InstrumentationMap represents the computed function id's and indicated function addresses from an...
std::unordered_map< int32_t, uint64_t > FunctionAddressMap
std::unordered_map< uint64_t, int32_t > FunctionAddressReverseMap
std::vector< SledEntry > SledContainer
std::optional< int32_t > getFunctionId(uint64_t Addr) const
Returns an XRay computed function id, provided a function address.
std::optional< uint64_t > getFunctionAddr(int32_t FuncId) const
Returns the function address for a function id.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
uint64_t(*)(uint64_t Type, uint64_t Offset, uint64_t S, uint64_t LocData, int64_t Addend) RelocationResolver
bool(*)(uint64_t) SupportsRelocation
uint64_t resolveRelocation(RelocationResolver Resolver, const RelocationRef &R, uint64_t S, uint64_t LocData)
std::pair< SupportsRelocation, RelocationResolver > getRelocationResolver(const ObjectFile &Obj)
std::error_code closeFile(file_t &F)
Close the file object.
Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
Definition: FileSystem.h:688
Expected< InstrumentationMap > loadInstrumentationMap(StringRef Filename)
Loads the instrumentation map from |Filename|.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1766
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
Represents an XRay instrumentation sled entry from an object file.
FunctionKinds
Each entry here represents the kinds of supported instrumentation map entries.