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