LLVM  10.0.0
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/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Object/Binary.h"
22 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/Support/Error.h"
28 #include <algorithm>
29 #include <cstddef>
30 #include <cstdint>
31 #include <system_error>
32 #include <vector>
33 
34 using namespace llvm;
35 using namespace xray;
36 
38  auto I = FunctionIds.find(Addr);
39  if (I != FunctionIds.end())
40  return I->second;
41  return None;
42 }
43 
45  auto I = FunctionAddresses.find(FuncId);
46  if (I != FunctionAddresses.end())
47  return I->second;
48  return None;
49 }
50 
52 
53 static Error
56  InstrumentationMap::FunctionAddressMap &FunctionAddresses,
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::ppc64le ||
64  ObjFile.getBinary()->getArch() == Triple::aarch64))
65  return make_error<StringError>(
66  "File format not supported (only does ELF and Mach-O little endian 64-bit).",
67  std::make_error_code(std::errc::not_supported));
68 
69  StringRef Contents = "";
70  const auto &Sections = ObjFile.getBinary()->sections();
71  auto I = llvm::find_if(Sections, [&](object::SectionRef Section) {
72  Expected<StringRef> NameOrErr = Section.getName();
73  if (NameOrErr)
74  return *NameOrErr == "xray_instr_map";
75  consumeError(NameOrErr.takeError());
76  return false;
77  });
78 
79  if (I == Sections.end())
80  return make_error<StringError>(
81  "Failed to find XRay instrumentation map.",
82  std::make_error_code(std::errc::executable_format_error));
83 
84  if (Expected<StringRef> E = I->getContents())
85  Contents = *E;
86  else
87  return E.takeError();
88 
89  RelocMap Relocs;
90  if (ObjFile.getBinary()->isELF()) {
91  uint32_t RelativeRelocation = [](object::ObjectFile *ObjFile) {
92  if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(ObjFile))
93  return ELFObj->getELFFile()->getRelativeRelocationType();
94  else if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(ObjFile))
95  return ELFObj->getELFFile()->getRelativeRelocationType();
96  else if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(ObjFile))
97  return ELFObj->getELFFile()->getRelativeRelocationType();
98  else if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(ObjFile))
99  return ELFObj->getELFFile()->getRelativeRelocationType();
100  else
101  return static_cast<uint32_t>(0);
102  }(ObjFile.getBinary());
103 
104  bool (*SupportsRelocation)(uint64_t);
106  std::tie(SupportsRelocation, Resolver) =
108 
109  for (const object::SectionRef &Section : Sections) {
110  for (const object::RelocationRef &Reloc : Section.relocations()) {
111  if (SupportsRelocation && SupportsRelocation(Reloc.getType())) {
112  auto AddendOrErr = object::ELFRelocationRef(Reloc).getAddend();
113  auto A = AddendOrErr ? *AddendOrErr : 0;
114  uint64_t resolved = Resolver(Reloc, Reloc.getSymbol()->getValue(), A);
115  Relocs.insert({Reloc.getOffset(), resolved});
116  } else if (Reloc.getType() == RelativeRelocation) {
117  if (auto AddendOrErr = object::ELFRelocationRef(Reloc).getAddend())
118  Relocs.insert({Reloc.getOffset(), *AddendOrErr});
119  }
120  }
121  }
122  }
123 
124  // Copy the instrumentation map data into the Sleds data structure.
125  auto C = Contents.bytes_begin();
126  static constexpr size_t ELF64SledEntrySize = 32;
127 
128  if ((C - Contents.bytes_end()) % ELF64SledEntrySize != 0)
129  return make_error<StringError>(
130  Twine("Instrumentation map entries not evenly divisible by size of "
131  "an XRay sled entry in ELF64."),
132  std::make_error_code(std::errc::executable_format_error));
133 
134  auto RelocateOrElse = [&](uint64_t Offset, uint64_t Address) {
135  if (!Address) {
136  uint64_t A = I->getAddress() + C - Contents.bytes_begin() + Offset;
137  RelocMap::const_iterator R = Relocs.find(A);
138  if (R != Relocs.end())
139  return R->second;
140  }
141  return Address;
142  };
143 
144  int32_t FuncId = 1;
145  uint64_t CurFn = 0;
146  for (; C != Contents.bytes_end(); C += ELF64SledEntrySize) {
147  DataExtractor Extractor(
148  StringRef(reinterpret_cast<const char *>(C), ELF64SledEntrySize), true,
149  8);
150  Sleds.push_back({});
151  auto &Entry = Sleds.back();
152  uint64_t OffsetPtr = 0;
153  uint64_t AddrOff = OffsetPtr;
154  Entry.Address = RelocateOrElse(AddrOff, Extractor.getU64(&OffsetPtr));
155  uint64_t FuncOff = OffsetPtr;
156  Entry.Function = RelocateOrElse(FuncOff, Extractor.getU64(&OffsetPtr));
157  auto Kind = Extractor.getU8(&OffsetPtr);
158  static constexpr SledEntry::FunctionKinds Kinds[] = {
163  if (Kind >= sizeof(Kinds))
164  return errorCodeToError(
165  std::make_error_code(std::errc::executable_format_error));
166  Entry.Kind = Kinds[Kind];
167  Entry.AlwaysInstrument = Extractor.getU8(&OffsetPtr) != 0;
168 
169  // We do replicate the function id generation scheme implemented in the
170  // XRay runtime.
171  // FIXME: Figure out how to keep this consistent with the XRay runtime.
172  if (CurFn == 0) {
173  CurFn = Entry.Function;
174  FunctionAddresses[FuncId] = Entry.Function;
175  FunctionIds[Entry.Function] = FuncId;
176  }
177  if (Entry.Function != CurFn) {
178  ++FuncId;
179  CurFn = Entry.Function;
180  FunctionAddresses[FuncId] = Entry.Function;
181  FunctionIds[Entry.Function] = FuncId;
182  }
183  }
184  return Error::success();
185 }
186 
187 static Error
188 loadYAML(sys::fs::file_t Fd, size_t FileSize, StringRef Filename,
190  InstrumentationMap::FunctionAddressMap &FunctionAddresses,
192  std::error_code EC;
193  sys::fs::mapped_file_region MappedFile(
194  Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
195  sys::fs::closeFile(Fd);
196  if (EC)
197  return make_error<StringError>(
198  Twine("Failed memory-mapping file '") + Filename + "'.", EC);
199 
200  std::vector<YAMLXRaySledEntry> YAMLSleds;
201  yaml::Input In(StringRef(MappedFile.data(), MappedFile.size()));
202  In >> YAMLSleds;
203  if (In.error())
204  return make_error<StringError>(
205  Twine("Failed loading YAML document from '") + Filename + "'.",
206  In.error());
207 
208  Sleds.reserve(YAMLSleds.size());
209  for (const auto &Y : YAMLSleds) {
210  FunctionAddresses[Y.FuncId] = Y.Function;
211  FunctionIds[Y.Function] = Y.FuncId;
212  Sleds.push_back(
213  SledEntry{Y.Address, Y.Function, Y.Kind, Y.AlwaysInstrument});
214  }
215  return Error::success();
216 }
217 
218 // FIXME: Create error types that encapsulate a bit more information than what
219 // StringError instances contain.
222  // At this point we assume the file is an object file -- and if that doesn't
223  // work, we treat it as YAML.
224  // FIXME: Extend to support non-ELF and non-x86_64 binaries.
225 
226  InstrumentationMap Map;
227  auto ObjectFileOrError = object::ObjectFile::createObjectFile(Filename);
228  if (!ObjectFileOrError) {
229  auto E = ObjectFileOrError.takeError();
230  // We try to load it as YAML if the ELF load didn't work.
232  if (!FdOrErr) {
233  // Report the ELF load error if YAML failed.
234  consumeError(FdOrErr.takeError());
235  return std::move(E);
236  }
237 
238  uint64_t FileSize;
239  if (sys::fs::file_size(Filename, FileSize))
240  return std::move(E);
241 
242  // If the file is empty, we return the original error.
243  if (FileSize == 0)
244  return std::move(E);
245 
246  // From this point on the errors will be only for the YAML parts, so we
247  // consume the errors at this point.
248  consumeError(std::move(E));
249  if (auto E = loadYAML(*FdOrErr, FileSize, Filename, Map.Sleds,
250  Map.FunctionAddresses, Map.FunctionIds))
251  return std::move(E);
252  } else if (auto E = loadObj(Filename, *ObjectFileOrError, Map.Sleds,
253  Map.FunctionAddresses, Map.FunctionIds)) {
254  return std::move(E);
255  }
256  return Map;
257 }
const NoneType None
Definition: None.h:23
uint64_t CallInst * C
uint8_t getU8(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint8_t value from *offset_ptr.
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:175
Profile::FuncID FuncId
Definition: Profile.cpp:321
Optional< uint64_t > getFunctionAddr(int32_t FuncId) const
Returns the function address for a function id.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
FunctionKinds
Each entry here represents the kinds of supported instrumentation map entries.
std::pair< bool(*)(uint64_t), RelocationResolver > getRelocationResolver(const ObjectFile &Obj)
This class is the base class for all object file types.
Definition: ObjectFile.h:223
This class represents a memory mapped file.
Definition: FileSystem.h:1160
std::unordered_map< uint64_t, int32_t > FunctionAddressReverseMap
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:195
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
std::vector< SledEntry > SledContainer
This is a value type class that represents a single relocation in the list of relocations in the obje...
Definition: ObjectFile.h:52
std::error_code make_error_code(BitcodeError E)
std::error_code file_size(const Twine &Path, uint64_t &Result)
Get file size.
Definition: FileSystem.h:696
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
Expected< InstrumentationMap > loadInstrumentationMap(StringRef Filename)
Loads the instrumentation map from |Filename|.
static Error loadYAML(sys::fs::file_t Fd, size_t FileSize, StringRef Filename, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds)
static Error loadObj(StringRef Filename, object::OwningBinary< object::ObjectFile > &ObjFile, InstrumentationMap::SledContainer &Sleds, InstrumentationMap::FunctionAddressMap &FunctionAddresses, InstrumentationMap::FunctionAddressReverseMap &FunctionIds)
Represents an XRay instrumentation sled entry from an object file.
section_iterator_range sections() const
Definition: ObjectFile.h:312
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:1870
Expected< int64_t > getAddend() const
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1210
bool isELF() const
Definition: Binary.h:118
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1001
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
virtual Triple::ArchType getArch() const =0
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 closeFile(file_t &F)
Close the file object.
Expected< StringRef > getName() const
Definition: ObjectFile.h:434
Optional< int32_t > getFunctionId(uint64_t Addr) const
Returns an XRay computed function id, provided a function address.
iterator_range< relocation_iterator > relocations() const
Definition: ObjectFile.h:130
#define I(x, y, z)
Definition: MD5.cpp:58
iterator end()
Definition: DenseMap.h:82
std::unordered_map< int32_t, uint64_t > FunctionAddressMap
uint64_t(*)(RelocationRef R, uint64_t S, uint64_t A) RelocationResolver
The InstrumentationMap represents the computed function id&#39;s and indicated function addresses from an...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
uint64_t getU64(uint64_t *offset_ptr, Error *Err=nullptr) const
Extract a uint64_t value from *offset_ptr.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
bool isMachO() const
Definition: Binary.h:122
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81