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