blob: 862949f578c9f849cd7f6958050e08c1f958a414 [file] [log] [blame]
Dean Michael Berris0e8abab2017-02-01 00:05:29 +00001//===- InstrumentationMap.cpp - XRay Instrumentation Map ------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dean Michael Berris0e8abab2017-02-01 00:05:29 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Implementation of the InstrumentationMap type for XRay sleds.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruth6bda14b2017-06-06 11:49:48 +000013#include "llvm/XRay/InstrumentationMap.h"
Petr Hosek493a0822018-12-14 01:37:56 +000014#include "llvm/ADT/DenseMap.h"
Eugene Zelenko44d95122017-02-09 01:09:54 +000015#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"
Petr Hosek493a0822018-12-14 01:37:56 +000021#include "llvm/Object/ELFObjectFile.h"
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000022#include "llvm/Object/ObjectFile.h"
23#include "llvm/Support/DataExtractor.h"
Eugene Zelenko44d95122017-02-09 01:09:54 +000024#include "llvm/Support/Error.h"
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000025#include "llvm/Support/FileSystem.h"
Eugene Zelenko44d95122017-02-09 01:09:54 +000026#include "llvm/Support/YAMLTraits.h"
Eugene Zelenko44d95122017-02-09 01:09:54 +000027#include <algorithm>
28#include <cstddef>
29#include <cstdint>
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000030#include <system_error>
Eugene Zelenko44d95122017-02-09 01:09:54 +000031#include <vector>
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000032
Eugene Zelenko44d95122017-02-09 01:09:54 +000033using namespace llvm;
34using namespace xray;
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000035
36Optional<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 None;
41}
42
43Optional<uint64_t> InstrumentationMap::getFunctionAddr(int32_t FuncId) const {
44 auto I = FunctionAddresses.find(FuncId);
45 if (I != FunctionAddresses.end())
46 return I->second;
47 return None;
48}
49
Petr Hosek493a0822018-12-14 01:37:56 +000050using RelocMap = DenseMap<uint64_t, uint64_t>;
51
Eugene Zelenko44d95122017-02-09 01:09:54 +000052static Error
David Carlier07cc5a82018-09-10 05:00:43 +000053loadObj(StringRef Filename, object::OwningBinary<object::ObjectFile> &ObjFile,
Eugene Zelenko44d95122017-02-09 01:09:54 +000054 InstrumentationMap::SledContainer &Sleds,
55 InstrumentationMap::FunctionAddressMap &FunctionAddresses,
56 InstrumentationMap::FunctionAddressReverseMap &FunctionIds) {
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000057 InstrumentationMap Map;
58
59 // Find the section named "xray_instr_map".
David Carlier07cc5a82018-09-10 05:00:43 +000060 if ((!ObjFile.getBinary()->isELF() && !ObjFile.getBinary()->isMachO()) ||
Tim Shen918ed872017-02-10 21:03:24 +000061 !(ObjFile.getBinary()->getArch() == Triple::x86_64 ||
62 ObjFile.getBinary()->getArch() == Triple::ppc64le))
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000063 return make_error<StringError>(
David Carlier07cc5a82018-09-10 05:00:43 +000064 "File format not supported (only does ELF and Mach-O little endian 64-bit).",
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000065 std::make_error_code(std::errc::not_supported));
66
67 StringRef Contents = "";
68 const auto &Sections = ObjFile.getBinary()->sections();
Eugene Zelenko44d95122017-02-09 01:09:54 +000069 auto I = llvm::find_if(Sections, [&](object::SectionRef Section) {
Dean Michael Berris0e8abab2017-02-01 00:05:29 +000070 StringRef Name = "";
71 if (Section.getName(Name))
72 return false;
73 return Name == "xray_instr_map";
74 });
75
76 if (I == Sections.end())
77 return make_error<StringError>(
78 "Failed to find XRay instrumentation map.",
79 std::make_error_code(std::errc::executable_format_error));
80
81 if (I->getContents(Contents))
82 return errorCodeToError(
83 std::make_error_code(std::errc::executable_format_error));
84
Petr Hosek493a0822018-12-14 01:37:56 +000085 RelocMap Relocs;
86 if (ObjFile.getBinary()->isELF()) {
Fangrui Songd2ed5be2018-12-14 07:46:58 +000087 uint32_t RelativeRelocation = [](object::ObjectFile *ObjFile) {
Petr Hosek493a0822018-12-14 01:37:56 +000088 if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(ObjFile))
Fangrui Songd2ed5be2018-12-14 07:46:58 +000089 return ELFObj->getELFFile()->getRelativeRelocationType();
Petr Hosek493a0822018-12-14 01:37:56 +000090 else if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(ObjFile))
Fangrui Songd2ed5be2018-12-14 07:46:58 +000091 return ELFObj->getELFFile()->getRelativeRelocationType();
Petr Hosek493a0822018-12-14 01:37:56 +000092 else if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(ObjFile))
Fangrui Songd2ed5be2018-12-14 07:46:58 +000093 return ELFObj->getELFFile()->getRelativeRelocationType();
Petr Hosek493a0822018-12-14 01:37:56 +000094 else if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(ObjFile))
Fangrui Songd2ed5be2018-12-14 07:46:58 +000095 return ELFObj->getELFFile()->getRelativeRelocationType();
Petr Hosek493a0822018-12-14 01:37:56 +000096 else
97 return static_cast<uint32_t>(0);
98 }(ObjFile.getBinary());
99
100 for (const object::SectionRef &Section : Sections) {
101 for (const object::RelocationRef &Reloc : Section.relocations()) {
Fangrui Songd2ed5be2018-12-14 07:46:58 +0000102 if (Reloc.getType() != RelativeRelocation)
Petr Hosek493a0822018-12-14 01:37:56 +0000103 continue;
104 if (auto AddendOrErr = object::ELFRelocationRef(Reloc).getAddend())
105 Relocs.insert({Reloc.getOffset(), *AddendOrErr});
106 }
107 }
108 }
109
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000110 // Copy the instrumentation map data into the Sleds data structure.
111 auto C = Contents.bytes_begin();
112 static constexpr size_t ELF64SledEntrySize = 32;
113
114 if ((C - Contents.bytes_end()) % ELF64SledEntrySize != 0)
115 return make_error<StringError>(
116 Twine("Instrumentation map entries not evenly divisible by size of "
117 "an XRay sled entry in ELF64."),
118 std::make_error_code(std::errc::executable_format_error));
119
Petr Hosek493a0822018-12-14 01:37:56 +0000120 auto RelocateOrElse = [&](uint32_t Offset, uint64_t Address) {
121 if (!Address) {
122 uint64_t A = I->getAddress() + C - Contents.bytes_begin() + Offset;
123 RelocMap::const_iterator R = Relocs.find(A);
124 if (R != Relocs.end())
125 return R->second;
126 }
127 return Address;
128 };
129
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000130 int32_t FuncId = 1;
131 uint64_t CurFn = 0;
132 for (; C != Contents.bytes_end(); C += ELF64SledEntrySize) {
133 DataExtractor Extractor(
134 StringRef(reinterpret_cast<const char *>(C), ELF64SledEntrySize), true,
135 8);
136 Sleds.push_back({});
137 auto &Entry = Sleds.back();
138 uint32_t OffsetPtr = 0;
Petr Hosek0c023062018-12-14 06:06:19 +0000139 uint32_t AddrOff = OffsetPtr;
Petr Hosek27e2f202018-12-14 05:56:20 +0000140 Entry.Address = RelocateOrElse(AddrOff, Extractor.getU64(&OffsetPtr));
Petr Hosek0c023062018-12-14 06:06:19 +0000141 uint32_t FuncOff = OffsetPtr;
Petr Hosek27e2f202018-12-14 05:56:20 +0000142 Entry.Function = RelocateOrElse(FuncOff, Extractor.getU64(&OffsetPtr));
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000143 auto Kind = Extractor.getU8(&OffsetPtr);
144 static constexpr SledEntry::FunctionKinds Kinds[] = {
145 SledEntry::FunctionKinds::ENTRY, SledEntry::FunctionKinds::EXIT,
146 SledEntry::FunctionKinds::TAIL,
Dean Michael Berrisc5caf3e2017-08-21 00:14:06 +0000147 SledEntry::FunctionKinds::LOG_ARGS_ENTER,
148 SledEntry::FunctionKinds::CUSTOM_EVENT};
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000149 if (Kind >= sizeof(Kinds))
150 return errorCodeToError(
151 std::make_error_code(std::errc::executable_format_error));
152 Entry.Kind = Kinds[Kind];
153 Entry.AlwaysInstrument = Extractor.getU8(&OffsetPtr) != 0;
154
155 // We do replicate the function id generation scheme implemented in the
156 // XRay runtime.
157 // FIXME: Figure out how to keep this consistent with the XRay runtime.
158 if (CurFn == 0) {
159 CurFn = Entry.Function;
160 FunctionAddresses[FuncId] = Entry.Function;
161 FunctionIds[Entry.Function] = FuncId;
162 }
163 if (Entry.Function != CurFn) {
164 ++FuncId;
165 CurFn = Entry.Function;
166 FunctionAddresses[FuncId] = Entry.Function;
167 FunctionIds[Entry.Function] = FuncId;
168 }
169 }
170 return Error::success();
171}
172
Eugene Zelenko44d95122017-02-09 01:09:54 +0000173static Error
174loadYAML(int Fd, size_t FileSize, StringRef Filename,
175 InstrumentationMap::SledContainer &Sleds,
176 InstrumentationMap::FunctionAddressMap &FunctionAddresses,
177 InstrumentationMap::FunctionAddressReverseMap &FunctionIds) {
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000178 std::error_code EC;
179 sys::fs::mapped_file_region MappedFile(
180 Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
181 if (EC)
182 return make_error<StringError>(
183 Twine("Failed memory-mapping file '") + Filename + "'.", EC);
184
185 std::vector<YAMLXRaySledEntry> YAMLSleds;
186 yaml::Input In(StringRef(MappedFile.data(), MappedFile.size()));
187 In >> YAMLSleds;
188 if (In.error())
189 return make_error<StringError>(
190 Twine("Failed loading YAML document from '") + Filename + "'.",
191 In.error());
192
193 Sleds.reserve(YAMLSleds.size());
194 for (const auto &Y : YAMLSleds) {
195 FunctionAddresses[Y.FuncId] = Y.Function;
196 FunctionIds[Y.Function] = Y.FuncId;
197 Sleds.push_back(
198 SledEntry{Y.Address, Y.Function, Y.Kind, Y.AlwaysInstrument});
199 }
200 return Error::success();
201}
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000202
203// FIXME: Create error types that encapsulate a bit more information than what
204// StringError instances contain.
Eugene Zelenko44d95122017-02-09 01:09:54 +0000205Expected<InstrumentationMap>
206llvm::xray::loadInstrumentationMap(StringRef Filename) {
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000207 // At this point we assume the file is an object file -- and if that doesn't
208 // work, we treat it as YAML.
209 // FIXME: Extend to support non-ELF and non-x86_64 binaries.
210
211 InstrumentationMap Map;
212 auto ObjectFileOrError = object::ObjectFile::createObjectFile(Filename);
213 if (!ObjectFileOrError) {
214 auto E = ObjectFileOrError.takeError();
215 // We try to load it as YAML if the ELF load didn't work.
216 int Fd;
217 if (sys::fs::openFileForRead(Filename, Fd))
218 return std::move(E);
219
220 uint64_t FileSize;
221 if (sys::fs::file_size(Filename, FileSize))
222 return std::move(E);
223
224 // If the file is empty, we return the original error.
225 if (FileSize == 0)
226 return std::move(E);
227
228 // From this point on the errors will be only for the YAML parts, so we
229 // consume the errors at this point.
230 consumeError(std::move(E));
231 if (auto E = loadYAML(Fd, FileSize, Filename, Map.Sleds,
232 Map.FunctionAddresses, Map.FunctionIds))
233 return std::move(E);
David Carlier07cc5a82018-09-10 05:00:43 +0000234 } else if (auto E = loadObj(Filename, *ObjectFileOrError, Map.Sleds,
Dean Michael Berris0e8abab2017-02-01 00:05:29 +0000235 Map.FunctionAddresses, Map.FunctionIds)) {
236 return std::move(E);
237 }
238 return Map;
239}