LLVM  13.0.0git
GsymCreator.cpp
Go to the documentation of this file.
1 //===- GsymCreator.cpp ----------------------------------------------------===//
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 
14 
15 #include <algorithm>
16 #include <cassert>
17 #include <functional>
18 #include <vector>
19 
20 using namespace llvm;
21 using namespace gsym;
22 
23 
26 }
27 
32  // We must insert the strings first, then call the FileEntry constructor.
33  // If we inline the insertString() function call into the constructor, the
34  // call order is undefined due to parameter lists not having any ordering
35  // requirements.
36  const uint32_t Dir = insertString(directory);
37  const uint32_t Base = insertString(filename);
38  FileEntry FE(Dir, Base);
39 
40  std::lock_guard<std::recursive_mutex> Guard(Mutex);
41  const auto NextIndex = Files.size();
42  // Find FE in hash map and insert if not present.
43  auto R = FileEntryToIndex.insert(std::make_pair(FE, NextIndex));
44  if (R.second)
45  Files.emplace_back(FE);
46  return R.first->second;
47 }
48 
50  llvm::support::endianness ByteOrder) const {
51  std::error_code EC;
52  raw_fd_ostream OutStrm(Path, EC);
53  if (EC)
54  return llvm::errorCodeToError(EC);
55  FileWriter O(OutStrm, ByteOrder);
56  return encode(O);
57 }
58 
60  std::lock_guard<std::recursive_mutex> Guard(Mutex);
61  if (Funcs.empty())
62  return createStringError(std::errc::invalid_argument,
63  "no functions to encode");
64  if (!Finalized)
65  return createStringError(std::errc::invalid_argument,
66  "GsymCreator wasn't finalized prior to encoding");
67 
68  if (Funcs.size() > UINT32_MAX)
69  return createStringError(std::errc::invalid_argument,
70  "too many FunctionInfos");
71 
72  const uint64_t MinAddr = BaseAddress ? *BaseAddress : Funcs.front().startAddress();
73  const uint64_t MaxAddr = Funcs.back().startAddress();
74  const uint64_t AddrDelta = MaxAddr - MinAddr;
75  Header Hdr;
76  Hdr.Magic = GSYM_MAGIC;
77  Hdr.Version = GSYM_VERSION;
78  Hdr.AddrOffSize = 0;
79  Hdr.UUIDSize = static_cast<uint8_t>(UUID.size());
80  Hdr.BaseAddress = MinAddr;
81  Hdr.NumAddresses = static_cast<uint32_t>(Funcs.size());
82  Hdr.StrtabOffset = 0; // We will fix this up later.
83  Hdr.StrtabSize = 0; // We will fix this up later.
84  memset(Hdr.UUID, 0, sizeof(Hdr.UUID));
85  if (UUID.size() > sizeof(Hdr.UUID))
86  return createStringError(std::errc::invalid_argument,
87  "invalid UUID size %u", (uint32_t)UUID.size());
88  // Set the address offset size correctly in the GSYM header.
89  if (AddrDelta <= UINT8_MAX)
90  Hdr.AddrOffSize = 1;
91  else if (AddrDelta <= UINT16_MAX)
92  Hdr.AddrOffSize = 2;
93  else if (AddrDelta <= UINT32_MAX)
94  Hdr.AddrOffSize = 4;
95  else
96  Hdr.AddrOffSize = 8;
97  // Copy the UUID value if we have one.
98  if (UUID.size() > 0)
99  memcpy(Hdr.UUID, UUID.data(), UUID.size());
100  // Write out the header.
101  llvm::Error Err = Hdr.encode(O);
102  if (Err)
103  return Err;
104 
105  // Write out the address offsets.
106  O.alignTo(Hdr.AddrOffSize);
107  for (const auto &FuncInfo : Funcs) {
108  uint64_t AddrOffset = FuncInfo.startAddress() - Hdr.BaseAddress;
109  switch(Hdr.AddrOffSize) {
110  case 1: O.writeU8(static_cast<uint8_t>(AddrOffset)); break;
111  case 2: O.writeU16(static_cast<uint16_t>(AddrOffset)); break;
112  case 4: O.writeU32(static_cast<uint32_t>(AddrOffset)); break;
113  case 8: O.writeU64(AddrOffset); break;
114  }
115  }
116 
117  // Write out all zeros for the AddrInfoOffsets.
118  O.alignTo(4);
119  const off_t AddrInfoOffsetsOffset = O.tell();
120  for (size_t i = 0, n = Funcs.size(); i < n; ++i)
121  O.writeU32(0);
122 
123  // Write out the file table
124  O.alignTo(4);
125  assert(!Files.empty());
126  assert(Files[0].Dir == 0);
127  assert(Files[0].Base == 0);
128  size_t NumFiles = Files.size();
129  if (NumFiles > UINT32_MAX)
130  return createStringError(std::errc::invalid_argument,
131  "too many files");
132  O.writeU32(static_cast<uint32_t>(NumFiles));
133  for (auto File: Files) {
134  O.writeU32(File.Dir);
135  O.writeU32(File.Base);
136  }
137 
138  // Write out the sting table.
139  const off_t StrtabOffset = O.tell();
140  StrTab.write(O.get_stream());
141  const off_t StrtabSize = O.tell() - StrtabOffset;
142  std::vector<uint32_t> AddrInfoOffsets;
143 
144  // Write out the address infos for each function info.
145  for (const auto &FuncInfo : Funcs) {
146  if (Expected<uint64_t> OffsetOrErr = FuncInfo.encode(O))
147  AddrInfoOffsets.push_back(OffsetOrErr.get());
148  else
149  return OffsetOrErr.takeError();
150  }
151  // Fixup the string table offset and size in the header
152  O.fixup32((uint32_t)StrtabOffset, offsetof(Header, StrtabOffset));
153  O.fixup32((uint32_t)StrtabSize, offsetof(Header, StrtabSize));
154 
155  // Fixup all address info offsets
156  uint64_t Offset = 0;
157  for (auto AddrInfoOffset: AddrInfoOffsets) {
158  O.fixup32(AddrInfoOffset, AddrInfoOffsetsOffset + Offset);
159  Offset += 4;
160  }
161  return ErrorSuccess();
162 }
163 
164 // Similar to std::remove_if, but the predicate is binary and it is passed both
165 // the previous and the current element.
166 template <class ForwardIt, class BinaryPredicate>
167 static ForwardIt removeIfBinary(ForwardIt FirstIt, ForwardIt LastIt,
168  BinaryPredicate Pred) {
169  if (FirstIt != LastIt) {
170  auto PrevIt = FirstIt++;
171  FirstIt = std::find_if(FirstIt, LastIt, [&](const auto &Curr) {
172  return Pred(*PrevIt++, Curr);
173  });
174  if (FirstIt != LastIt)
175  for (ForwardIt CurrIt = FirstIt; ++CurrIt != LastIt;)
176  if (!Pred(*PrevIt, *CurrIt)) {
177  PrevIt = FirstIt;
178  *FirstIt++ = std::move(*CurrIt);
179  }
180  }
181  return FirstIt;
182 }
183 
185  std::lock_guard<std::recursive_mutex> Guard(Mutex);
186  if (Finalized)
187  return createStringError(std::errc::invalid_argument,
188  "already finalized");
189  Finalized = true;
190 
191  // Sort function infos so we can emit sorted functions.
192  llvm::sort(Funcs);
193 
194  // Don't let the string table indexes change by finalizing in order.
195  StrTab.finalizeInOrder();
196 
197  // Remove duplicates function infos that have both entries from debug info
198  // (DWARF or Breakpad) and entries from the SymbolTable.
199  //
200  // Also handle overlapping function. Usually there shouldn't be any, but they
201  // can and do happen in some rare cases.
202  //
203  // (a) (b) (c)
204  // ^ ^ ^ ^
205  // |X |Y |X ^ |X
206  // | | | |Y | ^
207  // | | | v v |Y
208  // v v v v
209  //
210  // In (a) and (b), Y is ignored and X will be reported for the full range.
211  // In (c), both functions will be included in the result and lookups for an
212  // address in the intersection will return Y because of binary search.
213  //
214  // Note that in case of (b), we cannot include Y in the result because then
215  // we wouldn't find any function for range (end of Y, end of X)
216  // with binary search
217  auto NumBefore = Funcs.size();
218  Funcs.erase(
219  removeIfBinary(Funcs.begin(), Funcs.end(),
220  [&](const auto &Prev, const auto &Curr) {
221  if (Prev.Range.intersects(Curr.Range)) {
222  // Overlapping address ranges.
223  if (Prev.Range == Curr.Range) {
224  // Same address range. Check if one is from debug
225  // info and the other is from a symbol table. If
226  // so, then keep the one with debug info. Our
227  // sorting guarantees that entries with matching
228  // address ranges that have debug info are last in
229  // the sort.
230  if (Prev == Curr) {
231  // FunctionInfo entries match exactly (range,
232  // lines, inlines)
233 
234  // We used to output a warning here, but this was
235  // so frequent on some binaries, in particular
236  // when those were built with GCC, that it slowed
237  // down processing extremely.
238  return true;
239  } else {
240  if (!Prev.hasRichInfo() && Curr.hasRichInfo()) {
241  // Same address range, one with no debug info
242  // (symbol) and the next with debug info. Keep
243  // the latter.
244  return true;
245  } else {
246  OS << "warning: same address range contains "
247  "different debug "
248  << "info. Removing:\n"
249  << Prev << "\nIn favor of this one:\n"
250  << Curr << "\n";
251  return true;
252  }
253  }
254  } else {
255  // print warnings about overlaps
256  OS << "warning: function ranges overlap:\n"
257  << Prev << "\n"
258  << Curr << "\n";
259  }
260  } else if (Prev.Range.size() == 0 &&
261  Curr.Range.contains(Prev.Range.Start)) {
262  OS << "warning: removing symbol:\n"
263  << Prev << "\nKeeping:\n"
264  << Curr << "\n";
265  return true;
266  }
267 
268  return false;
269  }),
270  Funcs.end());
271 
272  // If our last function info entry doesn't have a size and if we have valid
273  // text ranges, we should set the size of the last entry since any search for
274  // a high address might match our last entry. By fixing up this size, we can
275  // help ensure we don't cause lookups to always return the last symbol that
276  // has no size when doing lookups.
277  if (!Funcs.empty() && Funcs.back().Range.size() == 0 && ValidTextRanges) {
278  if (auto Range = ValidTextRanges->getRangeThatContains(
279  Funcs.back().Range.Start)) {
280  Funcs.back().Range.End = Range->End;
281  }
282  }
283  OS << "Pruned " << NumBefore - Funcs.size() << " functions, ended with "
284  << Funcs.size() << " total\n";
285  return Error::success();
286 }
287 
288 uint32_t GsymCreator::insertString(StringRef S, bool Copy) {
289  if (S.empty())
290  return 0;
291  std::lock_guard<std::recursive_mutex> Guard(Mutex);
292  if (Copy) {
293  // We need to provide backing storage for the string if requested
294  // since StringTableBuilder stores references to strings. Any string
295  // that comes from a section in an object file doesn't need to be
296  // copied, but any string created by code will need to be copied.
297  // This allows GsymCreator to be really fast when parsing DWARF and
298  // other object files as most strings don't need to be copied.
299  CachedHashStringRef CHStr(S);
300  if (!StrTab.contains(CHStr))
301  S = StringStorage.insert(S).first->getKey();
302  }
303  return StrTab.add(S);
304 }
305 
306 void GsymCreator::addFunctionInfo(FunctionInfo &&FI) {
307  std::lock_guard<std::recursive_mutex> Guard(Mutex);
308  Ranges.insert(FI.Range);
309  Funcs.emplace_back(FI);
310 }
311 
312 void GsymCreator::forEachFunctionInfo(
313  std::function<bool(FunctionInfo &)> const &Callback) {
314  std::lock_guard<std::recursive_mutex> Guard(Mutex);
315  for (auto &FI : Funcs) {
316  if (!Callback(FI))
317  break;
318  }
319 }
320 
321 void GsymCreator::forEachFunctionInfo(
322  std::function<bool(const FunctionInfo &)> const &Callback) const {
323  std::lock_guard<std::recursive_mutex> Guard(Mutex);
324  for (const auto &FI : Funcs) {
325  if (!Callback(FI))
326  break;
327  }
328 }
329 
330 size_t GsymCreator::getNumFunctionInfos() const{
331  std::lock_guard<std::recursive_mutex> Guard(Mutex);
332  return Funcs.size();
333 }
334 
335 bool GsymCreator::IsValidTextAddress(uint64_t Addr) const {
336  if (ValidTextRanges)
337  return ValidTextRanges->contains(Addr);
338  return true; // No valid text ranges has been set, so accept all ranges.
339 }
340 
341 bool GsymCreator::hasFunctionInfoForAddress(uint64_t Addr) const {
342  std::lock_guard<std::recursive_mutex> Guard(Mutex);
343  return Ranges.contains(Addr);
344 }
i
i
Definition: README.txt:29
llvm::gsym::Header::UUIDSize
uint8_t UUIDSize
The size in bytes of the UUID encoded in the "UUID" member.
Definition: Header.h:58
llvm
Definition: AllocatorList.h:23
llvm::gsym::Header::BaseAddress
uint64_t BaseAddress
The 64 bit base address that all address offsets in the address offsets table are relative to.
Definition: Header.h:62
offsetof
#define offsetof(TYPE, MEMBER)
Definition: AMDHSAKernelDescriptor.h:23
llvm::gsym::Header
The GSYM header.
Definition: Header.h:45
llvm::Error::success
static ErrorSuccess success()
Create a success value.
Definition: Error.h:332
llvm::StringTableBuilder::finalizeInOrder
void finalizeInOrder()
Finalize the string table without reording it.
Definition: StringTableBuilder.cpp:132
llvm::gsym::GsymCreator::encode
llvm::Error encode(FileWriter &O) const
Encode a GSYM into the file writer stream at the current position.
Definition: GsymCreator.cpp:59
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
llvm::gsym::GSYM_MAGIC
constexpr uint32_t GSYM_MAGIC
Definition: Header.h:24
StringTableBuilder.h
llvm::gsym::Header::encode
llvm::Error encode(FileWriter &O) const
Encode this object into FileWriter stream.
Definition: Header.cpp:85
llvm::gsym::GSYM_VERSION
constexpr uint32_t GSYM_VERSION
Definition: Header.h:26
llvm::errorCodeToError
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
llvm::gsym::Header::Magic
uint32_t Magic
The magic bytes should be set to GSYM_MAGIC.
Definition: Header.h:49
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:50
llvm::gsym::Header::StrtabSize
uint32_t StrtabSize
The size in bytes of the string table.
Definition: Header.h:80
llvm::sys::path::Style
Style
Definition: Path.h:28
llvm::sys::SmartMutex< false >
llvm::gsym::FunctionInfo
Function information in GSYM files encodes information for one contiguous address range.
Definition: FunctionInfo.h:89
llvm::CachedHashStringRef
A container which contains a StringRef plus a precomputed hash.
Definition: CachedHashString.h:28
llvm::RISCVFenceField::O
@ O
Definition: RISCVBaseInfo.h:179
Addr
uint64_t Addr
Definition: ELFObjHandler.cpp:80
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::ErrorSuccess
Subclass of Error for the sole purpose of identifying the success path in the type system.
Definition: Error.h:330
llvm::gsym::Header::UUID
uint8_t UUID[GSYM_MAX_UUID_SIZE]
The UUID of the original executable file.
Definition: Header.h:86
llvm::gsym::GsymCreator::GsymCreator
GsymCreator()
Definition: GsymCreator.cpp:24
llvm::HexStyle::Style
Style
Definition: MCInstPrinter.h:32
FileWriter.h
llvm::gsym::FileWriter
A simplified binary data writer class that doesn't require targets, target definitions,...
Definition: FileWriter.h:29
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::sys::path::parent_path
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:465
memcpy
<%struct.s * > cast struct s *S to sbyte *< sbyte * > sbyte uint cast struct s *agg result to sbyte *< sbyte * > sbyte uint cast struct s *memtmp to sbyte *< sbyte * > sbyte uint ret void llc ends up issuing two memcpy or custom lower memcpy(of small size) to be ldmia/stmia. I think option 2 is better but the current register allocator cannot allocate a chunk of registers at a time. A feasible temporary solution is to use specific physical registers at the lowering time for small(<
function
print Print MemDeps of function
Definition: MemDepPrinter.cpp:83
UUID
std::pair< llvm::MachO::Target, std::string > UUID
Definition: TextStubCommon.h:23
llvm::StringTableBuilder::write
void write(raw_ostream &OS) const
Definition: StringTableBuilder.cpp:59
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
if
if(llvm_vc STREQUAL "") set(fake_version_inc "$
Definition: CMakeLists.txt:14
uint32_t
S
add sub stmia L5 ldr r0 bl L_printf $stub Instead of a and a wouldn t it be better to do three moves *Return an aggregate type is even return S
Definition: README.txt:210
llvm::gsym::GsymCreator::insertString
uint32_t insertString(StringRef S, bool Copy=true)
Insert a string into the GSYM string table.
Definition: GsymCreator.cpp:288
llvm::DenseMapBase::insert
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:207
llvm::raw_fd_ostream
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:432
llvm::gsym::FileEntry
Files in GSYM are contained in FileEntry structs where we split the directory and basename into two d...
Definition: FileEntry.h:24
llvm::gsym::Header::NumAddresses
uint32_t NumAddresses
The number of addresses stored in the address offsets table.
Definition: Header.h:64
llvm::find_if
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:1509
LineTable.h
llvm::createStringError
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1202
uint16_t
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::sort
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1423
llvm::StringTableBuilder
Utility for building string tables with deduplicated suffixes.
Definition: StringTableBuilder.h:23
llvm::gsym::Header::StrtabOffset
uint32_t StrtabOffset
The file relative offset of the start of the string table for strings contained in the GSYM file.
Definition: Header.h:72
llvm::gsym::GsymCreator::insertFile
uint32_t insertFile(StringRef Path, sys::path::Style Style=sys::path::Style::native)
Insert a file into this GSYM creator.
Definition: GsymCreator.cpp:28
llvm::sys::path::filename
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:575
llvm::gsym::Header::Version
uint16_t Version
The version can number determines how the header is decoded and how each InfoType in FunctionInfo is ...
Definition: Header.h:54
llvm::gsym::GsymCreator::save
llvm::Error save(StringRef Path, llvm::support::endianness ByteOrder) const
Save a GSYM file to a stand alone file.
Definition: GsymCreator.cpp:49
llvm::support::endianness
endianness
Definition: Endian.h:27
Header.h
raw_ostream.h
n
The same transformation can work with an even modulo with the addition of a and shrink the compare RHS by the same amount Unless the target supports that transformation probably isn t worthwhile The transformation can also easily be made to work with non zero equality for n
Definition: README.txt:685
llvm::gsym::GsymCreator::finalize
llvm::Error finalize(llvm::raw_ostream &OS)
Finalize the data in the GSYM creator prior to saving the data out.
Definition: GsymCreator.cpp:184
GsymCreator.h
File
Instrumentation for Order File
Definition: InstrOrderFile.cpp:206
llvm::gsym::Header::AddrOffSize
uint8_t AddrOffSize
The size in bytes of each address offset in the address offsets table.
Definition: Header.h:56
removeIfBinary
static ForwardIt removeIfBinary(ForwardIt FirstIt, ForwardIt LastIt, BinaryPredicate Pred)
Definition: GsymCreator.cpp:167