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