| 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 | |
| 8 | #include "llvm/DebugInfo/GSYM/GsymCreator.h" |
| 9 | #include "llvm/ADT/SmallString.h" |
| 10 | #include "llvm/DebugInfo/GSYM/FileWriter.h" |
| 11 | #include "llvm/DebugInfo/GSYM/Header.h" |
| 12 | #include "llvm/DebugInfo/GSYM/LineTable.h" |
| 13 | #include "llvm/DebugInfo/GSYM/OutputAggregator.h" |
| 14 | #include "llvm/MC/StringTableBuilder.h" |
| 15 | #include "llvm/Support/raw_ostream.h" |
| 16 | |
| 17 | #include <algorithm> |
| 18 | #include <cassert> |
| 19 | #include <functional> |
| 20 | #include <vector> |
| 21 | |
| 22 | using namespace llvm; |
| 23 | using namespace gsym; |
| 24 | |
| 25 | // Keep this matching cheap: Itanium and Swift both encode identifiers as |
| 26 | // <length><identifier> in the raw mangled name. Look for that token instead of |
| 27 | // demangling during finalize(). |
| 28 | static bool isSupportedMangledPrefix(StringRef Name) { |
| 29 | return Name.starts_with(Prefix: "_Z" ) || Name.starts_with(Prefix: "$s" ) || |
| 30 | Name.starts_with(Prefix: "$S" ); |
| 31 | } |
| 32 | |
| 33 | static bool shouldReplaceWithMangledName(StringRef AlternateName, |
| 34 | StringRef CurrentName) { |
| 35 | // Any name is better than no name. |
| 36 | if (CurrentName.empty() && !AlternateName.empty()) |
| 37 | return true; |
| 38 | |
| 39 | // Keep the current name if it's already mangled, or if the alternate name |
| 40 | // is not a supported mangled name. |
| 41 | if (isSupportedMangledPrefix(Name: CurrentName) || |
| 42 | !isSupportedMangledPrefix(Name: AlternateName)) |
| 43 | return false; |
| 44 | |
| 45 | // Confirm the alternate mangled name actually contains the current name as |
| 46 | // an Itanium/Swift identifier token (<length><identifier>). |
| 47 | SmallString<64> LengthAndName; |
| 48 | raw_svector_ostream OS(LengthAndName); |
| 49 | OS << CurrentName.size() << CurrentName; |
| 50 | return AlternateName.contains(Other: StringRef(LengthAndName)); |
| 51 | } |
| 52 | |
| 53 | GsymCreator::GsymCreator() : StrTab(StringTableBuilder::ELF) { |
| 54 | insertFile(Path: StringRef()); |
| 55 | } |
| 56 | |
| 57 | uint32_t GsymCreator::insertFile(StringRef Path, llvm::sys::path::Style Style) { |
| 58 | llvm::StringRef directory = llvm::sys::path::parent_path(path: Path, style: Style); |
| 59 | llvm::StringRef filename = llvm::sys::path::filename(path: Path, style: Style); |
| 60 | // We must insert the strings first, then call the FileEntry constructor. |
| 61 | // If we inline the insertString() function call into the constructor, the |
| 62 | // call order is undefined due to parameter lists not having any ordering |
| 63 | // requirements. |
| 64 | const gsym_strp_t Dir = insertString(S: directory); |
| 65 | const gsym_strp_t Base = insertString(S: filename); |
| 66 | return insertFileEntry(FE: FileEntry(Dir, Base)); |
| 67 | } |
| 68 | |
| 69 | uint32_t GsymCreator::insertFileEntry(FileEntry FE) { |
| 70 | std::lock_guard<std::mutex> Guard(Mutex); |
| 71 | const auto NextIndex = Files.size(); |
| 72 | // Find FE in hash map and insert if not present. |
| 73 | auto R = FileEntryToIndex.insert(KV: std::make_pair(x&: FE, y: NextIndex)); |
| 74 | if (R.second) |
| 75 | Files.emplace_back(args&: FE); |
| 76 | return R.first->second; |
| 77 | } |
| 78 | |
| 79 | uint32_t GsymCreator::copyFile(const GsymCreator &SrcGC, uint32_t FileIdx) { |
| 80 | // File index zero is reserved for a FileEntry with no directory and no |
| 81 | // filename. Any other file and we need to copy the strings for the directory |
| 82 | // and filename. |
| 83 | if (FileIdx == 0) |
| 84 | return 0; |
| 85 | const FileEntry SrcFE = SrcGC.Files[FileIdx]; |
| 86 | // Copy the strings for the file and then add the newly converted file entry. |
| 87 | gsym_strp_t Dir = |
| 88 | SrcFE.Dir == 0 |
| 89 | ? 0 |
| 90 | : StrTab.add(S: SrcGC.StringOffsetMap.find(Val: SrcFE.Dir)->second); |
| 91 | gsym_strp_t Base = StrTab.add(S: SrcGC.StringOffsetMap.find(Val: SrcFE.Base)->second); |
| 92 | FileEntry DstFE(Dir, Base); |
| 93 | return insertFileEntry(FE: DstFE); |
| 94 | } |
| 95 | |
| 96 | llvm::Error GsymCreator::save(StringRef Path, llvm::endianness ByteOrder, |
| 97 | std::optional<uint64_t> SegmentSize) const { |
| 98 | if (SegmentSize) |
| 99 | return saveSegments(Path, ByteOrder, SegmentSize: *SegmentSize); |
| 100 | std::error_code EC; |
| 101 | raw_fd_ostream OutStrm(Path, EC); |
| 102 | if (EC) |
| 103 | return llvm::errorCodeToError(EC); |
| 104 | FileWriter O(OutStrm, ByteOrder); |
| 105 | O.setStringOffsetSize(getStringOffsetSize()); |
| 106 | return encode(O); |
| 107 | } |
| 108 | |
| 109 | llvm::Error GsymCreator::loadCallSitesFromYAML(StringRef YAMLFile) { |
| 110 | // Use the loader to load call site information from the YAML file. |
| 111 | CallSiteInfoLoader Loader(*this, Funcs); |
| 112 | return Loader.loadYAML(YAMLFile); |
| 113 | } |
| 114 | |
| 115 | void GsymCreator::prepareMergedFunctions(OutputAggregator &Out) { |
| 116 | // Nothing to do if we have less than 2 functions. |
| 117 | if (Funcs.size() < 2) |
| 118 | return; |
| 119 | |
| 120 | // Sort the function infos by address range first, preserving input order |
| 121 | llvm::stable_sort(Range&: Funcs); |
| 122 | std::vector<FunctionInfo> TopLevelFuncs; |
| 123 | |
| 124 | // Add the first function info to the top level functions |
| 125 | TopLevelFuncs.emplace_back(args: std::move(Funcs.front())); |
| 126 | |
| 127 | // Now if the next function info has the same address range as the top level, |
| 128 | // then merge it into the top level function, otherwise add it to the top |
| 129 | // level. |
| 130 | for (size_t Idx = 1; Idx < Funcs.size(); ++Idx) { |
| 131 | FunctionInfo &TopFunc = TopLevelFuncs.back(); |
| 132 | FunctionInfo &MatchFunc = Funcs[Idx]; |
| 133 | if (TopFunc.Range == MatchFunc.Range) { |
| 134 | // Both have the same range - add the 2nd func as a child of the 1st func |
| 135 | if (!TopFunc.MergedFunctions) |
| 136 | TopFunc.MergedFunctions = MergedFunctionsInfo(); |
| 137 | // Avoid adding duplicate functions to MergedFunctions. Since functions |
| 138 | // are already ordered within the Funcs array, we can just check equality |
| 139 | // against the last function in the merged array. |
| 140 | else if (TopFunc.MergedFunctions->MergedFunctions.back() == MatchFunc) |
| 141 | continue; |
| 142 | TopFunc.MergedFunctions->MergedFunctions.emplace_back( |
| 143 | args: std::move(MatchFunc)); |
| 144 | } else |
| 145 | // No match, add the function as a top-level function |
| 146 | TopLevelFuncs.emplace_back(args: std::move(MatchFunc)); |
| 147 | } |
| 148 | |
| 149 | uint32_t mergedCount = Funcs.size() - TopLevelFuncs.size(); |
| 150 | // If any functions were merged, print a message about it. |
| 151 | if (mergedCount != 0) |
| 152 | Out << "Have " << mergedCount |
| 153 | << " merged functions as children of other functions\n" ; |
| 154 | |
| 155 | std::swap(x&: Funcs, y&: TopLevelFuncs); |
| 156 | } |
| 157 | |
| 158 | llvm::Error GsymCreator::finalize(OutputAggregator &Out) { |
| 159 | std::lock_guard<std::mutex> Guard(Mutex); |
| 160 | if (Finalized) |
| 161 | return createStringError(EC: std::errc::invalid_argument, Fmt: "already finalized" ); |
| 162 | Finalized = true; |
| 163 | |
| 164 | // Don't let the string table indexes change by finalizing in order. |
| 165 | StrTab.finalizeInOrder(); |
| 166 | |
| 167 | // Remove duplicates function infos that have both entries from debug info |
| 168 | // (DWARF or Breakpad) and entries from the SymbolTable. |
| 169 | // |
| 170 | // Also handle overlapping function. Usually there shouldn't be any, but they |
| 171 | // can and do happen in some rare cases. |
| 172 | // |
| 173 | // (a) (b) (c) |
| 174 | // ^ ^ ^ ^ |
| 175 | // |X |Y |X ^ |X |
| 176 | // | | | |Y | ^ |
| 177 | // | | | v v |Y |
| 178 | // v v v v |
| 179 | // |
| 180 | // In (a) and (b), Y is ignored and X will be reported for the full range. |
| 181 | // In (c), both functions will be included in the result and lookups for an |
| 182 | // address in the intersection will return Y because of binary search. |
| 183 | // |
| 184 | // Note that in case of (b), we cannot include Y in the result because then |
| 185 | // we wouldn't find any function for range (end of Y, end of X) |
| 186 | // with binary search |
| 187 | |
| 188 | const auto NumBefore = Funcs.size(); |
| 189 | // Only sort and unique if this isn't a segment. If this is a segment we |
| 190 | // already finalized the main GsymCreator with all of the function infos |
| 191 | // and then the already sorted and uniqued function infos were added to this |
| 192 | // object. |
| 193 | if (!IsSegment) { |
| 194 | if (NumBefore > 1) { |
| 195 | // Sort function infos so we can emit sorted functions. Use stable sort to |
| 196 | // ensure determinism. |
| 197 | llvm::stable_sort(Range&: Funcs); |
| 198 | std::vector<FunctionInfo> FinalizedFuncs; |
| 199 | FinalizedFuncs.reserve(n: Funcs.size()); |
| 200 | FinalizedFuncs.emplace_back(args: std::move(Funcs.front())); |
| 201 | for (size_t Idx=1; Idx < NumBefore; ++Idx) { |
| 202 | FunctionInfo &Prev = FinalizedFuncs.back(); |
| 203 | FunctionInfo &Curr = Funcs[Idx]; |
| 204 | // Empty ranges won't intersect, but we still need to |
| 205 | // catch the case where we have multiple symbols at the |
| 206 | // same address and coalesce them. |
| 207 | const bool ranges_equal = Prev.Range == Curr.Range; |
| 208 | if (ranges_equal || Prev.Range.intersects(R: Curr.Range)) { |
| 209 | // Overlapping ranges or empty identical ranges. |
| 210 | if (ranges_equal) { |
| 211 | // Same address range. The sort orders entries with more debug info |
| 212 | // last, so when exactly one entry has rich info, Prev is the |
| 213 | // non-rich (typically symbol-table) entry and Curr is the rich |
| 214 | // (typically DWARF) one. DWARF often truncates a function's |
| 215 | // linkage name to its short form, so before dropping the non-rich |
| 216 | // entry check whether its name is a more complete mangled |
| 217 | // (Itanium or Swift) form of the rich entry's name and, if so, |
| 218 | // copy it onto the rich entry. This lets downstream tools |
| 219 | // demangle the full signature. |
| 220 | const bool PrevRich = Prev.hasRichInfo(); |
| 221 | const bool CurrRich = Curr.hasRichInfo(); |
| 222 | if (PrevRich != CurrRich) { |
| 223 | if (shouldReplaceWithMangledName(AlternateName: getString(Offset: Prev.Name), |
| 224 | CurrentName: getString(Offset: Curr.Name))) |
| 225 | Curr.Name = Prev.Name; |
| 226 | std::swap(a&: Prev, b&: Curr); |
| 227 | } else if (Prev != Curr) { |
| 228 | if (PrevRich) |
| 229 | Out.Report( |
| 230 | s: "Duplicate address ranges with different debug info." , |
| 231 | detailCallback: [&](raw_ostream &OS) { |
| 232 | OS << "warning: same address range contains " |
| 233 | "different debug " |
| 234 | << "info. Removing:\n" |
| 235 | << Prev << "\nIn favor of this one:\n" |
| 236 | << Curr << "\n" ; |
| 237 | }); |
| 238 | std::swap(a&: Prev, b&: Curr); |
| 239 | } |
| 240 | } else { |
| 241 | Out.Report(s: "Overlapping function ranges" , detailCallback: [&](raw_ostream &OS) { |
| 242 | // print warnings about overlaps |
| 243 | OS << "warning: function ranges overlap:\n" |
| 244 | << Prev << "\n" |
| 245 | << Curr << "\n" ; |
| 246 | }); |
| 247 | FinalizedFuncs.emplace_back(args: std::move(Curr)); |
| 248 | } |
| 249 | } else { |
| 250 | if (Prev.Range.size() == 0 && Curr.Range.contains(Addr: Prev.Range.start())) { |
| 251 | // Symbols on macOS don't have address ranges, so if the range |
| 252 | // doesn't match and the size is zero, then we replace the empty |
| 253 | // symbol function info with the current one. |
| 254 | std::swap(a&: Prev, b&: Curr); |
| 255 | } else { |
| 256 | FinalizedFuncs.emplace_back(args: std::move(Curr)); |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | std::swap(x&: Funcs, y&: FinalizedFuncs); |
| 261 | } |
| 262 | // If our last function info entry doesn't have a size and if we have valid |
| 263 | // text ranges, we should set the size of the last entry since any search for |
| 264 | // a high address might match our last entry. By fixing up this size, we can |
| 265 | // help ensure we don't cause lookups to always return the last symbol that |
| 266 | // has no size when doing lookups. |
| 267 | if (!Funcs.empty() && Funcs.back().Range.size() == 0 && ValidTextRanges) { |
| 268 | if (auto Range = |
| 269 | ValidTextRanges->getRangeThatContains(Addr: Funcs.back().Range.start())) { |
| 270 | Funcs.back().Range = {Funcs.back().Range.start(), Range->end()}; |
| 271 | } |
| 272 | } |
| 273 | Out << "Pruned " << NumBefore - Funcs.size() << " functions, ended with " |
| 274 | << Funcs.size() << " total\n" ; |
| 275 | } |
| 276 | return Error::success(); |
| 277 | } |
| 278 | |
| 279 | gsym_strp_t GsymCreator::copyString(const GsymCreator &SrcGC, |
| 280 | gsym_strp_t StrOff) { |
| 281 | // String offset at zero is always the empty string, no copying needed. |
| 282 | if (StrOff == 0) |
| 283 | return 0; |
| 284 | return StrTab.add(S: SrcGC.StringOffsetMap.find(Val: StrOff)->second); |
| 285 | } |
| 286 | |
| 287 | gsym_strp_t GsymCreator::insertString(StringRef S, bool Copy) { |
| 288 | if (S.empty()) |
| 289 | return 0; |
| 290 | |
| 291 | // The hash can be calculated outside the lock. |
| 292 | CachedHashStringRef CHStr(S); |
| 293 | std::lock_guard<std::mutex> Guard(Mutex); |
| 294 | if (Copy) { |
| 295 | // We need to provide backing storage for the string if requested |
| 296 | // since StringTableBuilder stores references to strings. Any string |
| 297 | // that comes from a section in an object file doesn't need to be |
| 298 | // copied, but any string created by code will need to be copied. |
| 299 | // This allows GsymCreator to be really fast when parsing DWARF and |
| 300 | // other object files as most strings don't need to be copied. |
| 301 | if (!StrTab.contains(S: CHStr)) |
| 302 | CHStr = CachedHashStringRef{StringStorage.insert(key: S).first->getKey(), |
| 303 | CHStr.hash()}; |
| 304 | } |
| 305 | const gsym_strp_t StrOff = StrTab.add(S: CHStr); |
| 306 | // Save a mapping of string offsets to the cached string reference in case |
| 307 | // we need to segment the GSYM file and copy string from one string table to |
| 308 | // another. |
| 309 | StringOffsetMap.try_emplace(Key: StrOff, Args&: CHStr); |
| 310 | return StrOff; |
| 311 | } |
| 312 | |
| 313 | StringRef GsymCreator::getString(gsym_strp_t Offset) { |
| 314 | auto I = StringOffsetMap.find(Val: Offset); |
| 315 | assert(I != StringOffsetMap.end() && |
| 316 | "GsymCreator::getString expects a valid offset as parameter." ); |
| 317 | return I->second.val(); |
| 318 | } |
| 319 | |
| 320 | void GsymCreator::addFunctionInfo(FunctionInfo &&FI) { |
| 321 | std::lock_guard<std::mutex> Guard(Mutex); |
| 322 | Funcs.emplace_back(args: std::move(FI)); |
| 323 | } |
| 324 | |
| 325 | void GsymCreator::forEachFunctionInfo( |
| 326 | std::function<bool(FunctionInfo &)> const &Callback) { |
| 327 | std::lock_guard<std::mutex> Guard(Mutex); |
| 328 | for (auto &FI : Funcs) { |
| 329 | if (!Callback(FI)) |
| 330 | break; |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | void GsymCreator::forEachFunctionInfo( |
| 335 | std::function<bool(const FunctionInfo &)> const &Callback) const { |
| 336 | std::lock_guard<std::mutex> Guard(Mutex); |
| 337 | for (const auto &FI : Funcs) { |
| 338 | if (!Callback(FI)) |
| 339 | break; |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | size_t GsymCreator::getNumFunctionInfos() const { |
| 344 | std::lock_guard<std::mutex> Guard(Mutex); |
| 345 | return Funcs.size(); |
| 346 | } |
| 347 | |
| 348 | bool GsymCreator::IsValidTextAddress(uint64_t Addr) const { |
| 349 | if (ValidTextRanges) |
| 350 | return ValidTextRanges->contains(Addr); |
| 351 | return true; // No valid text ranges has been set, so accept all ranges. |
| 352 | } |
| 353 | |
| 354 | std::optional<uint64_t> GsymCreator::getFirstFunctionAddress() const { |
| 355 | // If we have finalized then Funcs are sorted. If we are a segment then |
| 356 | // Funcs will be sorted as well since function infos get added from an |
| 357 | // already finalized GsymCreator object where its functions were sorted and |
| 358 | // uniqued. |
| 359 | if ((Finalized || IsSegment) && !Funcs.empty()) |
| 360 | return std::optional<uint64_t>(Funcs.front().startAddress()); |
| 361 | return std::nullopt; |
| 362 | } |
| 363 | |
| 364 | std::optional<uint64_t> GsymCreator::getLastFunctionAddress() const { |
| 365 | // If we have finalized then Funcs are sorted. If we are a segment then |
| 366 | // Funcs will be sorted as well since function infos get added from an |
| 367 | // already finalized GsymCreator object where its functions were sorted and |
| 368 | // uniqued. |
| 369 | if ((Finalized || IsSegment) && !Funcs.empty()) |
| 370 | return std::optional<uint64_t>(Funcs.back().startAddress()); |
| 371 | return std::nullopt; |
| 372 | } |
| 373 | |
| 374 | std::optional<uint64_t> GsymCreator::getBaseAddress() const { |
| 375 | if (BaseAddress) |
| 376 | return BaseAddress; |
| 377 | return getFirstFunctionAddress(); |
| 378 | } |
| 379 | |
| 380 | uint64_t GsymCreator::getMaxAddressOffset() const { |
| 381 | switch (getAddressOffsetSize()) { |
| 382 | case 1: return UINT8_MAX; |
| 383 | case 2: return UINT16_MAX; |
| 384 | case 4: return UINT32_MAX; |
| 385 | case 8: return UINT64_MAX; |
| 386 | } |
| 387 | llvm_unreachable("invalid address offset" ); |
| 388 | } |
| 389 | |
| 390 | uint8_t GsymCreator::getAddressOffsetSize() const { |
| 391 | const std::optional<uint64_t> BaseAddress = getBaseAddress(); |
| 392 | const std::optional<uint64_t> LastFuncAddr = getLastFunctionAddress(); |
| 393 | if (BaseAddress && LastFuncAddr) { |
| 394 | const uint64_t AddrDelta = *LastFuncAddr - *BaseAddress; |
| 395 | if (AddrDelta <= UINT8_MAX) |
| 396 | return 1; |
| 397 | else if (AddrDelta <= UINT16_MAX) |
| 398 | return 2; |
| 399 | else if (AddrDelta <= UINT32_MAX) |
| 400 | return 4; |
| 401 | return 8; |
| 402 | } |
| 403 | return 1; |
| 404 | } |
| 405 | |
| 406 | llvm::Error |
| 407 | GsymCreator::validateForEncoding(std::optional<uint64_t> &BaseAddr) const { |
| 408 | if (Funcs.empty()) |
| 409 | return createStringError(EC: std::errc::invalid_argument, |
| 410 | Fmt: "no functions to encode" ); |
| 411 | if (!Finalized) |
| 412 | return createStringError(EC: std::errc::invalid_argument, |
| 413 | Fmt: "GsymCreator wasn't finalized prior to encoding" ); |
| 414 | if (Funcs.size() > UINT32_MAX) |
| 415 | return createStringError(EC: std::errc::invalid_argument, |
| 416 | Fmt: "too many FunctionInfos" ); |
| 417 | BaseAddr = getBaseAddress(); |
| 418 | if (!BaseAddr) |
| 419 | return createStringError(EC: std::errc::invalid_argument, |
| 420 | Fmt: "invalid base address" ); |
| 421 | return Error::success(); |
| 422 | } |
| 423 | |
| 424 | void GsymCreator::encodeAddrOffsets(FileWriter &O, uint8_t AddrOffSize, |
| 425 | uint64_t BaseAddr) const { |
| 426 | const uint64_t MaxAddressOffset = getMaxAddressOffset(); |
| 427 | O.alignTo(Align: AddrOffSize); |
| 428 | for (const auto &FI : Funcs) { |
| 429 | uint64_t AddrOffset = FI.startAddress() - BaseAddr; |
| 430 | // Make sure we calculated the address offsets byte size correctly by |
| 431 | // verifying the current address offset is within ranges. We have seen bugs |
| 432 | // introduced when the code changes that can cause problems here so it is |
| 433 | // good to catch this during testing. |
| 434 | assert(AddrOffset <= MaxAddressOffset); |
| 435 | (void)MaxAddressOffset; |
| 436 | switch (AddrOffSize) { |
| 437 | case 1: |
| 438 | O.writeU8(Value: static_cast<uint8_t>(AddrOffset)); |
| 439 | break; |
| 440 | case 2: |
| 441 | O.writeU16(Value: static_cast<uint16_t>(AddrOffset)); |
| 442 | break; |
| 443 | case 4: |
| 444 | O.writeU32(Value: static_cast<uint32_t>(AddrOffset)); |
| 445 | break; |
| 446 | case 8: |
| 447 | O.writeU64(Value: AddrOffset); |
| 448 | break; |
| 449 | default: |
| 450 | llvm_unreachable("unsupported address offset size" ); |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | llvm::Error GsymCreator::encodeFileTable(FileWriter &O) const { |
| 456 | assert(!Files.empty()); |
| 457 | assert(Files[0].Dir == 0); |
| 458 | assert(Files[0].Base == 0); |
| 459 | if (Files.size() > UINT32_MAX) |
| 460 | return createStringError(EC: std::errc::invalid_argument, Fmt: "too many files" ); |
| 461 | O.writeU32(Value: static_cast<uint32_t>(Files.size())); |
| 462 | for (const auto &File : Files) { |
| 463 | O.writeStringOffset(Value: File.Dir); |
| 464 | O.writeStringOffset(Value: File.Base); |
| 465 | } |
| 466 | return Error::success(); |
| 467 | } |
| 468 | |
| 469 | // This function takes a InlineInfo class that was copy constructed from an |
| 470 | // InlineInfo from the \a SrcGC and updates all members that point to strings |
| 471 | // and files to point to strings and files from this GsymCreator. |
| 472 | void GsymCreator::fixupInlineInfo(const GsymCreator &SrcGC, InlineInfo &II) { |
| 473 | II.Name = copyString(SrcGC, StrOff: II.Name); |
| 474 | II.CallFile = copyFile(SrcGC, FileIdx: II.CallFile); |
| 475 | for (auto &ChildII: II.Children) |
| 476 | fixupInlineInfo(SrcGC, II&: ChildII); |
| 477 | } |
| 478 | |
| 479 | uint64_t GsymCreator::copyFunctionInfo(const GsymCreator &SrcGC, size_t FuncIdx) { |
| 480 | // To copy a function info we need to copy any files and strings over into |
| 481 | // this GsymCreator and then copy the function info and update the string |
| 482 | // table offsets to match the new offsets. |
| 483 | const FunctionInfo &SrcFI = SrcGC.Funcs[FuncIdx]; |
| 484 | |
| 485 | FunctionInfo DstFI; |
| 486 | DstFI.Range = SrcFI.Range; |
| 487 | DstFI.Name = copyString(SrcGC, StrOff: SrcFI.Name); |
| 488 | // Copy the line table if there is one. |
| 489 | if (SrcFI.OptLineTable) { |
| 490 | // Copy the entire line table. |
| 491 | DstFI.OptLineTable = LineTable(SrcFI.OptLineTable.value()); |
| 492 | // Fixup all LineEntry::File entries which are indexes in the the file table |
| 493 | // from SrcGC and must be converted to file indexes from this GsymCreator. |
| 494 | LineTable &DstLT = DstFI.OptLineTable.value(); |
| 495 | const size_t NumLines = DstLT.size(); |
| 496 | for (size_t I=0; I<NumLines; ++I) { |
| 497 | LineEntry &LE = DstLT.get(i: I); |
| 498 | LE.File = copyFile(SrcGC, FileIdx: LE.File); |
| 499 | } |
| 500 | } |
| 501 | // Copy the inline information if needed. |
| 502 | if (SrcFI.Inline) { |
| 503 | // Make a copy of the source inline information. |
| 504 | DstFI.Inline = SrcFI.Inline.value(); |
| 505 | // Fixup all strings and files in the copied inline information. |
| 506 | fixupInlineInfo(SrcGC, II&: *DstFI.Inline); |
| 507 | } |
| 508 | std::lock_guard<std::mutex> Guard(Mutex); |
| 509 | Funcs.emplace_back(args&: DstFI); |
| 510 | return Funcs.back().cacheEncoding(GC&: *this); |
| 511 | } |
| 512 | |
| 513 | llvm::Error GsymCreator::saveSegments(StringRef Path, |
| 514 | llvm::endianness ByteOrder, |
| 515 | uint64_t SegmentSize) const { |
| 516 | if (SegmentSize == 0) |
| 517 | return createStringError(EC: std::errc::invalid_argument, |
| 518 | Fmt: "invalid segment size zero" ); |
| 519 | |
| 520 | size_t FuncIdx = 0; |
| 521 | const size_t NumFuncs = Funcs.size(); |
| 522 | while (FuncIdx < NumFuncs) { |
| 523 | llvm::Expected<std::unique_ptr<GsymCreator>> ExpectedGC = |
| 524 | createSegment(SegmentSize, FuncIdx); |
| 525 | if (ExpectedGC) { |
| 526 | GsymCreator *GC = ExpectedGC->get(); |
| 527 | if (!GC) |
| 528 | break; // We had not more functions to encode. |
| 529 | // Don't collect any messages at all |
| 530 | OutputAggregator Out(nullptr); |
| 531 | llvm::Error Err = GC->finalize(Out); |
| 532 | if (Err) |
| 533 | return Err; |
| 534 | std::string SegmentedGsymPath; |
| 535 | raw_string_ostream SGP(SegmentedGsymPath); |
| 536 | std::optional<uint64_t> FirstFuncAddr = GC->getFirstFunctionAddress(); |
| 537 | if (FirstFuncAddr) { |
| 538 | SGP << Path << "-" << llvm::format_hex(N: *FirstFuncAddr, Width: 1); |
| 539 | Err = GC->save(Path: SegmentedGsymPath, ByteOrder, SegmentSize: std::nullopt); |
| 540 | if (Err) |
| 541 | return Err; |
| 542 | } |
| 543 | } else { |
| 544 | return ExpectedGC.takeError(); |
| 545 | } |
| 546 | } |
| 547 | return Error::success(); |
| 548 | } |
| 549 | |
| 550 | llvm::Expected<std::unique_ptr<GsymCreator>> |
| 551 | GsymCreator::createSegment(uint64_t SegmentSize, size_t &FuncIdx) const { |
| 552 | // No function entries, return empty unique pointer |
| 553 | if (FuncIdx >= Funcs.size()) |
| 554 | return std::unique_ptr<GsymCreator>(); |
| 555 | |
| 556 | std::unique_ptr<GsymCreator> GC = createNew(); |
| 557 | |
| 558 | // Tell the creator that this is a segment. |
| 559 | GC->setIsSegment(); |
| 560 | |
| 561 | // Set the base address if there is one. |
| 562 | if (BaseAddress) |
| 563 | GC->setBaseAddress(*BaseAddress); |
| 564 | // Copy the UUID value from this object into the new creator. |
| 565 | GC->setUUID(UUID); |
| 566 | const size_t NumFuncs = Funcs.size(); |
| 567 | // Track how big the function infos are for the current segment so we can |
| 568 | // emit segments that are close to the requested size. It is quick math to |
| 569 | // determine the current header and tables sizes, so we can do that each loop. |
| 570 | uint64_t SegmentFuncInfosSize = 0; |
| 571 | for (; FuncIdx < NumFuncs; ++FuncIdx) { |
| 572 | const uint64_t HeaderAndTableSize = GC->calculateHeaderAndTableSize(); |
| 573 | if (HeaderAndTableSize + SegmentFuncInfosSize >= SegmentSize) { |
| 574 | if (SegmentFuncInfosSize == 0) |
| 575 | return createStringError(EC: std::errc::invalid_argument, |
| 576 | Fmt: "a segment size of %" PRIu64 " is to small to " |
| 577 | "fit any function infos, specify a larger value" , |
| 578 | Vals: SegmentSize); |
| 579 | |
| 580 | break; |
| 581 | } |
| 582 | SegmentFuncInfosSize += alignTo(Value: GC->copyFunctionInfo(SrcGC: *this, FuncIdx), Align: 4); |
| 583 | } |
| 584 | return std::move(GC); |
| 585 | } |
| 586 | |