1 //===-- PerfReader.cpp - perfscript reader  ---------------------*- C++ -*-===//
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 "PerfReader.h"
9 #include "ProfileGenerator.h"
10 #include "llvm/Support/FileSystem.h"
11 #include "llvm/Support/Process.h"
12 
13 #define DEBUG_TYPE "perf-reader"
14 
15 cl::opt<bool> SkipSymbolization("skip-symbolization", cl::init(false),
16                                 cl::ZeroOrMore,
17                                 cl::desc("Dump the unsymbolized profile to the "
18                                          "output file. It will show unwinder "
19                                          "output for CS profile generation."));
20 
21 static cl::opt<bool> ShowMmapEvents("show-mmap-events", cl::init(false),
22                                     cl::ZeroOrMore,
23                                     cl::desc("Print binary load events."));
24 
25 static cl::opt<bool>
26     UseOffset("use-offset", cl::init(true), cl::ZeroOrMore,
27               cl::desc("Work with `--skip-symbolization` or "
28                        "`--unsymbolized-profile` to write/read the "
29                        "offset instead of virtual address."));
30 
31 static cl::opt<bool> UseLoadableSegmentAsBase(
32     "use-first-loadable-segment-as-base", cl::init(false), cl::ZeroOrMore,
33     cl::desc("Use first loadable segment address as base address "
34              "for offsets in unsymbolized profile. By default "
35              "first executable segment address is used"));
36 
37 static cl::opt<bool>
38     IgnoreStackSamples("ignore-stack-samples", cl::init(false), cl::ZeroOrMore,
39                        cl::desc("Ignore call stack samples for hybrid samples "
40                                 "and produce context-insensitive profile."));
41 cl::opt<bool> ShowDetailedWarning("show-detailed-warning", cl::init(false),
42                                   cl::ZeroOrMore,
43                                   cl::desc("Show detailed warning message."));
44 
45 extern cl::opt<std::string> PerfTraceFilename;
46 extern cl::opt<bool> ShowDisassemblyOnly;
47 extern cl::opt<bool> ShowSourceLocations;
48 extern cl::opt<std::string> OutputFilename;
49 
50 namespace llvm {
51 namespace sampleprof {
52 
53 void VirtualUnwinder::unwindCall(UnwindState &State) {
54   // The 2nd frame after leaf could be missing if stack sample is
55   // taken when IP is within prolog/epilog, as frame chain isn't
56   // setup yet. Fill in the missing frame in that case.
57   // TODO: Currently we just assume all the addr that can't match the
58   // 2nd frame is in prolog/epilog. In the future, we will switch to
59   // pro/epi tracker(Dwarf CFI) for the precise check.
60   uint64_t Source = State.getCurrentLBRSource();
61   auto *ParentFrame = State.getParentFrame();
62   if (ParentFrame == State.getDummyRootPtr() ||
63       ParentFrame->Address != Source) {
64     State.switchToFrame(Source);
65   } else {
66     State.popFrame();
67   }
68   State.InstPtr.update(Source);
69 }
70 
71 void VirtualUnwinder::unwindLinear(UnwindState &State, uint64_t Repeat) {
72   InstructionPointer &IP = State.InstPtr;
73   uint64_t Target = State.getCurrentLBRTarget();
74   uint64_t End = IP.Address;
75   if (Binary->usePseudoProbes()) {
76     // We don't need to top frame probe since it should be extracted
77     // from the range.
78     // The outcome of the virtual unwinding with pseudo probes is a
79     // map from a context key to the address range being unwound.
80     // This means basically linear unwinding is not needed for pseudo
81     // probes. The range will be simply recorded here and will be
82     // converted to a list of pseudo probes to report in ProfileGenerator.
83     State.getParentFrame()->recordRangeCount(Target, End, Repeat);
84   } else {
85     // Unwind linear execution part.
86     // Split and record the range by different inline context. For example:
87     // [0x01] ... main:1          # Target
88     // [0x02] ... main:2
89     // [0x03] ... main:3 @ foo:1
90     // [0x04] ... main:3 @ foo:2
91     // [0x05] ... main:3 @ foo:3
92     // [0x06] ... main:4
93     // [0x07] ... main:5          # End
94     // It will be recorded:
95     // [main:*]         : [0x06, 0x07], [0x01, 0x02]
96     // [main:3 @ foo:*] : [0x03, 0x05]
97     while (IP.Address > Target) {
98       uint64_t PrevIP = IP.Address;
99       IP.backward();
100       // Break into segments for implicit call/return due to inlining
101       bool SameInlinee = Binary->inlineContextEqual(PrevIP, IP.Address);
102       if (!SameInlinee) {
103         State.switchToFrame(PrevIP);
104         State.CurrentLeafFrame->recordRangeCount(PrevIP, End, Repeat);
105         End = IP.Address;
106       }
107     }
108     assert(IP.Address == Target && "The last one must be the target address.");
109     // Record the remaining range, [0x01, 0x02] in the example
110     State.switchToFrame(IP.Address);
111     State.CurrentLeafFrame->recordRangeCount(IP.Address, End, Repeat);
112   }
113 }
114 
115 void VirtualUnwinder::unwindReturn(UnwindState &State) {
116   // Add extra frame as we unwind through the return
117   const LBREntry &LBR = State.getCurrentLBR();
118   uint64_t CallAddr = Binary->getCallAddrFromFrameAddr(LBR.Target);
119   State.switchToFrame(CallAddr);
120   State.pushFrame(LBR.Source);
121   State.InstPtr.update(LBR.Source);
122 }
123 
124 void VirtualUnwinder::unwindBranchWithinFrame(UnwindState &State) {
125   // TODO: Tolerate tail call for now, as we may see tail call from libraries.
126   // This is only for intra function branches, excluding tail calls.
127   uint64_t Source = State.getCurrentLBRSource();
128   State.switchToFrame(Source);
129   State.InstPtr.update(Source);
130 }
131 
132 std::shared_ptr<StringBasedCtxKey> FrameStack::getContextKey() {
133   std::shared_ptr<StringBasedCtxKey> KeyStr =
134       std::make_shared<StringBasedCtxKey>();
135   KeyStr->Context = Binary->getExpandedContext(Stack, KeyStr->WasLeafInlined);
136   if (KeyStr->Context.empty())
137     return nullptr;
138   return KeyStr;
139 }
140 
141 std::shared_ptr<ProbeBasedCtxKey> ProbeStack::getContextKey() {
142   std::shared_ptr<ProbeBasedCtxKey> ProbeBasedKey =
143       std::make_shared<ProbeBasedCtxKey>();
144   for (auto CallProbe : Stack) {
145     ProbeBasedKey->Probes.emplace_back(CallProbe);
146   }
147   CSProfileGenerator::compressRecursionContext<const MCDecodedPseudoProbe *>(
148       ProbeBasedKey->Probes);
149   CSProfileGenerator::trimContext<const MCDecodedPseudoProbe *>(
150       ProbeBasedKey->Probes);
151   return ProbeBasedKey;
152 }
153 
154 template <typename T>
155 void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,
156                                               T &Stack) {
157   if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())
158     return;
159 
160   std::shared_ptr<ContextKey> Key = Stack.getContextKey();
161   if (Key == nullptr)
162     return;
163   auto Ret = CtxCounterMap->emplace(Hashable<ContextKey>(Key), SampleCounter());
164   SampleCounter &SCounter = Ret.first->second;
165   for (auto &Item : Cur->RangeSamples) {
166     uint64_t StartOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
167     uint64_t EndOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
168     SCounter.recordRangeCount(StartOffset, EndOffset, std::get<2>(Item));
169   }
170 
171   for (auto &Item : Cur->BranchSamples) {
172     uint64_t SourceOffset = Binary->virtualAddrToOffset(std::get<0>(Item));
173     uint64_t TargetOffset = Binary->virtualAddrToOffset(std::get<1>(Item));
174     SCounter.recordBranchCount(SourceOffset, TargetOffset, std::get<2>(Item));
175   }
176 }
177 
178 template <typename T>
179 void VirtualUnwinder::collectSamplesFromFrameTrie(
180     UnwindState::ProfiledFrame *Cur, T &Stack) {
181   if (!Cur->isDummyRoot()) {
182     if (!Stack.pushFrame(Cur)) {
183       // Process truncated context
184       // Start a new traversal ignoring its bottom context
185       T EmptyStack(Binary);
186       collectSamplesFromFrame(Cur, EmptyStack);
187       for (const auto &Item : Cur->Children) {
188         collectSamplesFromFrameTrie(Item.second.get(), EmptyStack);
189       }
190 
191       // Keep note of untracked call site and deduplicate them
192       // for warning later.
193       if (!Cur->isLeafFrame())
194         UntrackedCallsites.insert(Cur->Address);
195 
196       return;
197     }
198   }
199 
200   collectSamplesFromFrame(Cur, Stack);
201   // Process children frame
202   for (const auto &Item : Cur->Children) {
203     collectSamplesFromFrameTrie(Item.second.get(), Stack);
204   }
205   // Recover the call stack
206   Stack.popFrame();
207 }
208 
209 void VirtualUnwinder::collectSamplesFromFrameTrie(
210     UnwindState::ProfiledFrame *Cur) {
211   if (Binary->usePseudoProbes()) {
212     ProbeStack Stack(Binary);
213     collectSamplesFromFrameTrie<ProbeStack>(Cur, Stack);
214   } else {
215     FrameStack Stack(Binary);
216     collectSamplesFromFrameTrie<FrameStack>(Cur, Stack);
217   }
218 }
219 
220 void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,
221                                         UnwindState &State, uint64_t Repeat) {
222   if (Branch.IsArtificial)
223     return;
224 
225   if (Binary->usePseudoProbes()) {
226     // Same as recordRangeCount, We don't need to top frame probe since we will
227     // extract it from branch's source address
228     State.getParentFrame()->recordBranchCount(Branch.Source, Branch.Target,
229                                               Repeat);
230   } else {
231     State.CurrentLeafFrame->recordBranchCount(Branch.Source, Branch.Target,
232                                               Repeat);
233   }
234 }
235 
236 bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {
237   // Capture initial state as starting point for unwinding.
238   UnwindState State(Sample, Binary);
239 
240   // Sanity check - making sure leaf of LBR aligns with leaf of stack sample
241   // Stack sample sometimes can be unreliable, so filter out bogus ones.
242   if (!State.validateInitialState())
243     return false;
244 
245   // Also do not attempt linear unwind for the leaf range as it's incomplete.
246   bool IsLeaf = true;
247 
248   // Now process the LBR samples in parrallel with stack sample
249   // Note that we do not reverse the LBR entry order so we can
250   // unwind the sample stack as we walk through LBR entries.
251   while (State.hasNextLBR()) {
252     State.checkStateConsistency();
253 
254     // Unwind implicit calls/returns from inlining, along the linear path,
255     // break into smaller sub section each with its own calling context.
256     if (!IsLeaf) {
257       unwindLinear(State, Repeat);
258     }
259     IsLeaf = false;
260 
261     // Save the LBR branch before it gets unwound.
262     const LBREntry &Branch = State.getCurrentLBR();
263 
264     if (isCallState(State)) {
265       // Unwind calls - we know we encountered call if LBR overlaps with
266       // transition between leaf the 2nd frame. Note that for calls that
267       // were not in the original stack sample, we should have added the
268       // extra frame when processing the return paired with this call.
269       unwindCall(State);
270     } else if (isReturnState(State)) {
271       // Unwind returns - check whether the IP is indeed at a return instruction
272       unwindReturn(State);
273     } else {
274       // Unwind branches - for regular intra function branches, we only
275       // need to record branch with context.
276       unwindBranchWithinFrame(State);
277     }
278     State.advanceLBR();
279     // Record `branch` with calling context after unwinding.
280     recordBranchCount(Branch, State, Repeat);
281   }
282   // As samples are aggregated on trie, record them into counter map
283   collectSamplesFromFrameTrie(State.getDummyRootPtr());
284 
285   return true;
286 }
287 
288 std::unique_ptr<PerfReaderBase>
289 PerfReaderBase::create(ProfiledBinary *Binary, PerfInputFile &PerfInput) {
290   std::unique_ptr<PerfReaderBase> PerfReader;
291 
292   if (PerfInput.Format == PerfFormat::UnsymbolizedProfile) {
293     PerfReader.reset(
294         new UnsymbolizedProfileReader(Binary, PerfInput.InputFile));
295     return PerfReader;
296   }
297 
298   // For perf data input, we need to convert them into perf script first.
299   if (PerfInput.Format == PerfFormat::PerfData)
300     PerfInput = PerfScriptReader::convertPerfDataToTrace(Binary, PerfInput);
301 
302   assert((PerfInput.Format == PerfFormat::PerfScript) &&
303          "Should be a perfscript!");
304 
305   PerfInput.Content =
306       PerfScriptReader::checkPerfScriptType(PerfInput.InputFile);
307   if (PerfInput.Content == PerfContent::LBRStack) {
308     PerfReader.reset(new HybridPerfReader(Binary, PerfInput.InputFile));
309   } else if (PerfInput.Content == PerfContent::LBR) {
310     PerfReader.reset(new LBRPerfReader(Binary, PerfInput.InputFile));
311   } else {
312     exitWithError("Unsupported perfscript!");
313   }
314 
315   return PerfReader;
316 }
317 
318 PerfInputFile PerfScriptReader::convertPerfDataToTrace(ProfiledBinary *Binary,
319                                                        PerfInputFile &File) {
320   StringRef PerfData = File.InputFile;
321   // Run perf script to retrieve PIDs matching binary we're interested in.
322   auto PerfExecutable = sys::Process::FindInEnvPath("PATH", "perf");
323   if (!PerfExecutable) {
324     exitWithError("Perf not found.");
325   }
326   std::string PerfPath = *PerfExecutable;
327   std::string PerfTraceFile = PerfData.str() + ".script.tmp";
328   StringRef ScriptMMapArgs[] = {PerfPath, "script",   "--show-mmap-events",
329                                 "-F",     "comm,pid", "-i",
330                                 PerfData};
331   Optional<StringRef> Redirects[] = {llvm::None,                // Stdin
332                                      StringRef(PerfTraceFile),  // Stdout
333                                      StringRef(PerfTraceFile)}; // Stderr
334   sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, llvm::None, Redirects);
335 
336   // Collect the PIDs
337   TraceStream TraceIt(PerfTraceFile);
338   std::string PIDs;
339   std::unordered_set<uint32_t> PIDSet;
340   while (!TraceIt.isAtEoF()) {
341     MMapEvent MMap;
342     if (isMMap2Event(TraceIt.getCurrentLine()) &&
343         extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap)) {
344       auto It = PIDSet.emplace(MMap.PID);
345       if (It.second) {
346         if (!PIDs.empty()) {
347           PIDs.append(",");
348         }
349         PIDs.append(utostr(MMap.PID));
350       }
351     }
352     TraceIt.advance();
353   }
354 
355   if (PIDs.empty()) {
356     exitWithError("No relevant mmap event is found in perf data.");
357   }
358 
359   // Run perf script again to retrieve events for PIDs collected above
360   StringRef ScriptSampleArgs[] = {PerfPath, "script",     "--show-mmap-events",
361                                   "-F",     "ip,brstack", "--pid",
362                                   PIDs,     "-i",         PerfData};
363   sys::ExecuteAndWait(PerfPath, ScriptSampleArgs, llvm::None, Redirects);
364 
365   return {PerfTraceFile, PerfFormat::PerfScript, PerfContent::UnknownContent};
366 }
367 
368 void PerfScriptReader::updateBinaryAddress(const MMapEvent &Event) {
369   // Drop the event which doesn't belong to user-provided binary
370   StringRef BinaryName = llvm::sys::path::filename(Event.BinaryPath);
371   if (Binary->getName() != BinaryName)
372     return;
373 
374   // Drop the event if its image is loaded at the same address
375   if (Event.Address == Binary->getBaseAddress()) {
376     Binary->setIsLoadedByMMap(true);
377     return;
378   }
379 
380   if (Event.Offset == Binary->getTextSegmentOffset()) {
381     // A binary image could be unloaded and then reloaded at different
382     // place, so update binary load address.
383     // Only update for the first executable segment and assume all other
384     // segments are loaded at consecutive memory addresses, which is the case on
385     // X64.
386     Binary->setBaseAddress(Event.Address);
387     Binary->setIsLoadedByMMap(true);
388   } else {
389     // Verify segments are loaded consecutively.
390     const auto &Offsets = Binary->getTextSegmentOffsets();
391     auto It = std::lower_bound(Offsets.begin(), Offsets.end(), Event.Offset);
392     if (It != Offsets.end() && *It == Event.Offset) {
393       // The event is for loading a separate executable segment.
394       auto I = std::distance(Offsets.begin(), It);
395       const auto &PreferredAddrs = Binary->getPreferredTextSegmentAddresses();
396       if (PreferredAddrs[I] - Binary->getPreferredBaseAddress() !=
397           Event.Address - Binary->getBaseAddress())
398         exitWithError("Executable segments not loaded consecutively");
399     } else {
400       if (It == Offsets.begin())
401         exitWithError("File offset not found");
402       else {
403         // Find the segment the event falls in. A large segment could be loaded
404         // via multiple mmap calls with consecutive memory addresses.
405         --It;
406         assert(*It < Event.Offset);
407         if (Event.Offset - *It != Event.Address - Binary->getBaseAddress())
408           exitWithError("Segment not loaded by consecutive mmaps");
409       }
410     }
411   }
412 }
413 
414 static std::string getContextKeyStr(ContextKey *K,
415                                     const ProfiledBinary *Binary) {
416   if (const auto *CtxKey = dyn_cast<StringBasedCtxKey>(K)) {
417     return SampleContext::getContextString(CtxKey->Context);
418   } else if (const auto *CtxKey = dyn_cast<ProbeBasedCtxKey>(K)) {
419     SampleContextFrameVector ContextStack;
420     for (const auto *Probe : CtxKey->Probes) {
421       Binary->getInlineContextForProbe(Probe, ContextStack, true);
422     }
423     // Probe context key at this point does not have leaf probe, so do not
424     // include the leaf inline location.
425     return SampleContext::getContextString(ContextStack, true);
426   } else {
427     llvm_unreachable("unexpected key type");
428   }
429 }
430 
431 void HybridPerfReader::unwindSamples() {
432   std::set<uint64_t> AllUntrackedCallsites;
433   for (const auto &Item : AggregatedSamples) {
434     const PerfSample *Sample = Item.first.getPtr();
435     VirtualUnwinder Unwinder(&SampleCounters, Binary);
436     Unwinder.unwind(Sample, Item.second);
437     auto &CurrUntrackedCallsites = Unwinder.getUntrackedCallsites();
438     AllUntrackedCallsites.insert(CurrUntrackedCallsites.begin(),
439                                  CurrUntrackedCallsites.end());
440   }
441 
442   // Warn about untracked frames due to missing probes.
443   if (ShowDetailedWarning) {
444     for (auto Address : AllUntrackedCallsites)
445       WithColor::warning() << "Profile context truncated due to missing probe "
446                            << "for call instruction at "
447                            << format("0x%" PRIx64, Address) << "\n";
448   }
449 
450   emitWarningSummary(AllUntrackedCallsites.size(), SampleCounters.size(),
451                      "of profiled contexts are truncated due to missing probe "
452                      "for call instruction.");
453 }
454 
455 bool PerfScriptReader::extractLBRStack(TraceStream &TraceIt,
456                                        SmallVectorImpl<LBREntry> &LBRStack) {
457   // The raw format of LBR stack is like:
458   // 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
459   //                           ... 0x4005c8/0x4005dc/P/-/-/0
460   // It's in FIFO order and seperated by whitespace.
461   SmallVector<StringRef, 32> Records;
462   TraceIt.getCurrentLine().split(Records, " ", -1, false);
463   auto WarnInvalidLBR = [](TraceStream &TraceIt) {
464     WithColor::warning() << "Invalid address in LBR record at line "
465                          << TraceIt.getLineNumber() << ": "
466                          << TraceIt.getCurrentLine() << "\n";
467   };
468 
469   // Skip the leading instruction pointer.
470   size_t Index = 0;
471   uint64_t LeadingAddr;
472   if (!Records.empty() && !Records[0].contains('/')) {
473     if (Records[0].getAsInteger(16, LeadingAddr)) {
474       WarnInvalidLBR(TraceIt);
475       TraceIt.advance();
476       return false;
477     }
478     Index = 1;
479   }
480   // Now extract LBR samples - note that we do not reverse the
481   // LBR entry order so we can unwind the sample stack as we walk
482   // through LBR entries.
483   uint64_t PrevTrDst = 0;
484 
485   while (Index < Records.size()) {
486     auto &Token = Records[Index++];
487     if (Token.size() == 0)
488       continue;
489 
490     SmallVector<StringRef, 8> Addresses;
491     Token.split(Addresses, "/");
492     uint64_t Src;
493     uint64_t Dst;
494 
495     // Stop at broken LBR records.
496     if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||
497         Addresses[1].substr(2).getAsInteger(16, Dst)) {
498       WarnInvalidLBR(TraceIt);
499       break;
500     }
501 
502     bool SrcIsInternal = Binary->addressIsCode(Src);
503     bool DstIsInternal = Binary->addressIsCode(Dst);
504     bool IsExternal = !SrcIsInternal && !DstIsInternal;
505     bool IsIncoming = !SrcIsInternal && DstIsInternal;
506     bool IsOutgoing = SrcIsInternal && !DstIsInternal;
507     bool IsArtificial = false;
508 
509     // Ignore branches outside the current binary. Ignore all remaining branches
510     // if there's no incoming branch before the external branch in reverse
511     // order.
512     if (IsExternal) {
513       if (PrevTrDst)
514         continue;
515       if (!LBRStack.empty()) {
516         WithColor::warning()
517             << "Invalid transfer to external code in LBR record at line "
518             << TraceIt.getLineNumber() << ": " << TraceIt.getCurrentLine()
519             << "\n";
520       }
521       break;
522     }
523 
524     if (IsOutgoing) {
525       if (!PrevTrDst) {
526         // This is unpaired outgoing jump which is likely due to interrupt or
527         // incomplete LBR trace. Ignore current and subsequent entries since
528         // they are likely in different contexts.
529         break;
530       }
531 
532       if (Binary->addressIsReturn(Src)) {
533         // In a callback case, a return from internal code, say A, to external
534         // runtime can happen. The external runtime can then call back to
535         // another internal routine, say B. Making an artificial branch that
536         // looks like a return from A to B can confuse the unwinder to treat
537         // the instruction before B as the call instruction.
538         break;
539       }
540 
541       // For transition to external code, group the Source with the next
542       // availabe transition target.
543       Dst = PrevTrDst;
544       PrevTrDst = 0;
545       IsArtificial = true;
546     } else {
547       if (PrevTrDst) {
548         // If we have seen an incoming transition from external code to internal
549         // code, but not a following outgoing transition, the incoming
550         // transition is likely due to interrupt which is usually unpaired.
551         // Ignore current and subsequent entries since they are likely in
552         // different contexts.
553         break;
554       }
555 
556       if (IsIncoming) {
557         // For transition from external code (such as dynamic libraries) to
558         // the current binary, keep track of the branch target which will be
559         // grouped with the Source of the last transition from the current
560         // binary.
561         PrevTrDst = Dst;
562         continue;
563       }
564     }
565 
566     // TODO: filter out buggy duplicate branches on Skylake
567 
568     LBRStack.emplace_back(LBREntry(Src, Dst, IsArtificial));
569   }
570   TraceIt.advance();
571   return !LBRStack.empty();
572 }
573 
574 bool PerfScriptReader::extractCallstack(TraceStream &TraceIt,
575                                         SmallVectorImpl<uint64_t> &CallStack) {
576   // The raw format of call stack is like:
577   //            4005dc      # leaf frame
578   //	          400634
579   //	          400684      # root frame
580   // It's in bottom-up order with each frame in one line.
581 
582   // Extract stack frames from sample
583   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
584     StringRef FrameStr = TraceIt.getCurrentLine().ltrim();
585     uint64_t FrameAddr = 0;
586     if (FrameStr.getAsInteger(16, FrameAddr)) {
587       // We might parse a non-perf sample line like empty line and comments,
588       // skip it
589       TraceIt.advance();
590       return false;
591     }
592     TraceIt.advance();
593     // Currently intermixed frame from different binaries is not supported.
594     // Ignore caller frames not from binary of interest.
595     if (!Binary->addressIsCode(FrameAddr))
596       break;
597 
598     // We need to translate return address to call address for non-leaf frames.
599     if (!CallStack.empty()) {
600       auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);
601       if (!CallAddr) {
602         // Stop at an invalid return address caused by bad unwinding. This could
603         // happen to frame-pointer-based unwinding and the callee functions that
604         // do not have the frame pointer chain set up.
605         InvalidReturnAddresses.insert(FrameAddr);
606         break;
607       }
608       FrameAddr = CallAddr;
609     }
610 
611     CallStack.emplace_back(FrameAddr);
612   }
613 
614   // Skip other unrelated line, find the next valid LBR line
615   // Note that even for empty call stack, we should skip the address at the
616   // bottom, otherwise the following pass may generate a truncated callstack
617   while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().startswith(" 0x")) {
618     TraceIt.advance();
619   }
620   // Filter out broken stack sample. We may not have complete frame info
621   // if sample end up in prolog/epilog, the result is dangling context not
622   // connected to entry point. This should be relatively rare thus not much
623   // impact on overall profile quality. However we do want to filter them
624   // out to reduce the number of different calling contexts. One instance
625   // of such case - when sample landed in prolog/epilog, somehow stack
626   // walking will be broken in an unexpected way that higher frames will be
627   // missing.
628   return !CallStack.empty() &&
629          !Binary->addressInPrologEpilog(CallStack.front());
630 }
631 
632 void PerfScriptReader::warnIfMissingMMap() {
633   if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {
634     WithColor::warning() << "No relevant mmap event is matched for "
635                          << Binary->getName()
636                          << ", will use preferred address ("
637                          << format("0x%" PRIx64,
638                                    Binary->getPreferredBaseAddress())
639                          << ") as the base loading address!\n";
640     // Avoid redundant warning, only warn at the first unmatched sample.
641     Binary->setMissingMMapWarned(true);
642   }
643 }
644 
645 void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
646   // The raw hybird sample started with call stack in FILO order and followed
647   // intermediately by LBR sample
648   // e.g.
649   // 	          4005dc    # call stack leaf
650   //	          400634
651   //	          400684    # call stack root
652   // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
653   //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
654   //
655   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
656 
657   // Parsing call stack and populate into PerfSample.CallStack
658   if (!extractCallstack(TraceIt, Sample->CallStack)) {
659     // Skip the next LBR line matched current call stack
660     if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x"))
661       TraceIt.advance();
662     return;
663   }
664 
665   warnIfMissingMMap();
666 
667   if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().startswith(" 0x")) {
668     // Parsing LBR stack and populate into PerfSample.LBRStack
669     if (extractLBRStack(TraceIt, Sample->LBRStack)) {
670       if (IgnoreStackSamples) {
671         Sample->CallStack.clear();
672       } else {
673         // Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR
674         // ranges
675         Sample->CallStack.front() = Sample->LBRStack[0].Target;
676       }
677       // Record samples by aggregation
678       AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
679     }
680   } else {
681     // LBR sample is encoded in single line after stack sample
682     exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");
683   }
684 }
685 
686 void PerfScriptReader::writeUnsymbolizedProfile(StringRef Filename) {
687   std::error_code EC;
688   raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
689   if (EC)
690     exitWithError(EC, Filename);
691   writeUnsymbolizedProfile(OS);
692 }
693 
694 // Use ordered map to make the output deterministic
695 using OrderedCounterForPrint = std::map<std::string, SampleCounter *>;
696 
697 void PerfScriptReader::writeUnsymbolizedProfile(raw_fd_ostream &OS) {
698   OrderedCounterForPrint OrderedCounters;
699   for (auto &CI : SampleCounters) {
700     OrderedCounters[getContextKeyStr(CI.first.getPtr(), Binary)] = &CI.second;
701   }
702 
703   auto SCounterPrinter = [&](RangeSample &Counter, StringRef Separator,
704                              uint32_t Indent) {
705     OS.indent(Indent);
706     OS << Counter.size() << "\n";
707     for (auto &I : Counter) {
708       uint64_t Start = I.first.first;
709       uint64_t End = I.first.second;
710 
711       if (!UseOffset || (UseOffset && UseLoadableSegmentAsBase)) {
712         Start = Binary->offsetToVirtualAddr(Start);
713         End = Binary->offsetToVirtualAddr(End);
714       }
715 
716       if (UseOffset && UseLoadableSegmentAsBase) {
717         Start -= Binary->getFirstLoadableAddress();
718         End -= Binary->getFirstLoadableAddress();
719       }
720 
721       OS.indent(Indent);
722       OS << Twine::utohexstr(Start) << Separator << Twine::utohexstr(End) << ":"
723          << I.second << "\n";
724     }
725   };
726 
727   for (auto &CI : OrderedCounters) {
728     uint32_t Indent = 0;
729     if (ProfileIsCS) {
730       // Context string key
731       OS << "[" << CI.first << "]\n";
732       Indent = 2;
733     }
734 
735     SampleCounter &Counter = *CI.second;
736     SCounterPrinter(Counter.RangeCounter, "-", Indent);
737     SCounterPrinter(Counter.BranchCounter, "->", Indent);
738   }
739 }
740 
741 // Format of input:
742 // number of entries in RangeCounter
743 // from_1-to_1:count_1
744 // from_2-to_2:count_2
745 // ......
746 // from_n-to_n:count_n
747 // number of entries in BranchCounter
748 // src_1->dst_1:count_1
749 // src_2->dst_2:count_2
750 // ......
751 // src_n->dst_n:count_n
752 void UnsymbolizedProfileReader::readSampleCounters(TraceStream &TraceIt,
753                                                    SampleCounter &SCounters) {
754   auto exitWithErrorForTraceLine = [](TraceStream &TraceIt) {
755     std::string Msg = TraceIt.isAtEoF()
756                           ? "Invalid raw profile!"
757                           : "Invalid raw profile at line " +
758                                 Twine(TraceIt.getLineNumber()).str() + ": " +
759                                 TraceIt.getCurrentLine().str();
760     exitWithError(Msg);
761   };
762   auto ReadNumber = [&](uint64_t &Num) {
763     if (TraceIt.isAtEoF())
764       exitWithErrorForTraceLine(TraceIt);
765     if (TraceIt.getCurrentLine().ltrim().getAsInteger(10, Num))
766       exitWithErrorForTraceLine(TraceIt);
767     TraceIt.advance();
768   };
769 
770   auto ReadCounter = [&](RangeSample &Counter, StringRef Separator) {
771     uint64_t Num = 0;
772     ReadNumber(Num);
773     while (Num--) {
774       if (TraceIt.isAtEoF())
775         exitWithErrorForTraceLine(TraceIt);
776       StringRef Line = TraceIt.getCurrentLine().ltrim();
777 
778       uint64_t Count = 0;
779       auto LineSplit = Line.split(":");
780       if (LineSplit.second.empty() || LineSplit.second.getAsInteger(10, Count))
781         exitWithErrorForTraceLine(TraceIt);
782 
783       uint64_t Source = 0;
784       uint64_t Target = 0;
785       auto Range = LineSplit.first.split(Separator);
786       if (Range.second.empty() || Range.first.getAsInteger(16, Source) ||
787           Range.second.getAsInteger(16, Target))
788         exitWithErrorForTraceLine(TraceIt);
789 
790       if (!UseOffset || (UseOffset && UseLoadableSegmentAsBase)) {
791         uint64_t BaseAddr = 0;
792         if (UseOffset && UseLoadableSegmentAsBase)
793           BaseAddr = Binary->getFirstLoadableAddress();
794 
795         Source = Binary->virtualAddrToOffset(Source + BaseAddr);
796         Target = Binary->virtualAddrToOffset(Target + BaseAddr);
797       }
798 
799       Counter[{Source, Target}] += Count;
800       TraceIt.advance();
801     }
802   };
803 
804   ReadCounter(SCounters.RangeCounter, "-");
805   ReadCounter(SCounters.BranchCounter, "->");
806 }
807 
808 void UnsymbolizedProfileReader::readUnsymbolizedProfile(StringRef FileName) {
809   TraceStream TraceIt(FileName);
810   while (!TraceIt.isAtEoF()) {
811     std::shared_ptr<StringBasedCtxKey> Key =
812         std::make_shared<StringBasedCtxKey>();
813     StringRef Line = TraceIt.getCurrentLine();
814     // Read context stack for CS profile.
815     if (Line.startswith("[")) {
816       ProfileIsCS = true;
817       auto I = ContextStrSet.insert(Line.str());
818       SampleContext::createCtxVectorFromStr(*I.first, Key->Context);
819       TraceIt.advance();
820     }
821     auto Ret =
822         SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
823     readSampleCounters(TraceIt, Ret.first->second);
824   }
825 }
826 
827 void UnsymbolizedProfileReader::parsePerfTraces() {
828   readUnsymbolizedProfile(PerfTraceFile);
829 }
830 
831 void PerfScriptReader::computeCounterFromLBR(const PerfSample *Sample,
832                                              uint64_t Repeat) {
833   SampleCounter &Counter = SampleCounters.begin()->second;
834   uint64_t EndOffeset = 0;
835   for (const LBREntry &LBR : Sample->LBRStack) {
836     uint64_t SourceOffset = Binary->virtualAddrToOffset(LBR.Source);
837     uint64_t TargetOffset = Binary->virtualAddrToOffset(LBR.Target);
838 
839     if (!LBR.IsArtificial) {
840       Counter.recordBranchCount(SourceOffset, TargetOffset, Repeat);
841     }
842 
843     // If this not the first LBR, update the range count between TO of current
844     // LBR and FROM of next LBR.
845     uint64_t StartOffset = TargetOffset;
846     if (EndOffeset != 0)
847       Counter.recordRangeCount(StartOffset, EndOffeset, Repeat);
848     EndOffeset = SourceOffset;
849   }
850 }
851 
852 void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {
853   std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();
854   // Parsing LBR stack and populate into PerfSample.LBRStack
855   if (extractLBRStack(TraceIt, Sample->LBRStack)) {
856     warnIfMissingMMap();
857     // Record LBR only samples by aggregation
858     AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;
859   }
860 }
861 
862 void PerfScriptReader::generateUnsymbolizedProfile() {
863   // There is no context for LBR only sample, so initialize one entry with
864   // fake "empty" context key.
865   assert(SampleCounters.empty() &&
866          "Sample counter map should be empty before raw profile generation");
867   std::shared_ptr<StringBasedCtxKey> Key =
868       std::make_shared<StringBasedCtxKey>();
869   SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());
870   for (const auto &Item : AggregatedSamples) {
871     const PerfSample *Sample = Item.first.getPtr();
872     computeCounterFromLBR(Sample, Item.second);
873   }
874 }
875 
876 uint64_t PerfScriptReader::parseAggregatedCount(TraceStream &TraceIt) {
877   // The aggregated count is optional, so do not skip the line and return 1 if
878   // it's unmatched
879   uint64_t Count = 1;
880   if (!TraceIt.getCurrentLine().getAsInteger(10, Count))
881     TraceIt.advance();
882   return Count;
883 }
884 
885 void PerfScriptReader::parseSample(TraceStream &TraceIt) {
886   uint64_t Count = parseAggregatedCount(TraceIt);
887   assert(Count >= 1 && "Aggregated count should be >= 1!");
888   parseSample(TraceIt, Count);
889 }
890 
891 bool PerfScriptReader::extractMMap2EventForBinary(ProfiledBinary *Binary,
892                                                   StringRef Line,
893                                                   MMapEvent &MMap) {
894   // Parse a line like:
895   //  PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0
896   //  08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so
897   constexpr static const char *const Pattern =
898       "PERF_RECORD_MMAP2 ([0-9]+)/[0-9]+: "
899       "\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "
900       "(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";
901   // Field 0 - whole line
902   // Field 1 - PID
903   // Field 2 - base address
904   // Field 3 - mmapped size
905   // Field 4 - page offset
906   // Field 5 - binary path
907   enum EventIndex {
908     WHOLE_LINE = 0,
909     PID = 1,
910     MMAPPED_ADDRESS = 2,
911     MMAPPED_SIZE = 3,
912     PAGE_OFFSET = 4,
913     BINARY_PATH = 5
914   };
915 
916   Regex RegMmap2(Pattern);
917   SmallVector<StringRef, 6> Fields;
918   bool R = RegMmap2.match(Line, &Fields);
919   if (!R) {
920     std::string ErrorMsg = "Cannot parse mmap event: " + Line.str() + " \n";
921     exitWithError(ErrorMsg);
922   }
923   Fields[PID].getAsInteger(10, MMap.PID);
924   Fields[MMAPPED_ADDRESS].getAsInteger(0, MMap.Address);
925   Fields[MMAPPED_SIZE].getAsInteger(0, MMap.Size);
926   Fields[PAGE_OFFSET].getAsInteger(0, MMap.Offset);
927   MMap.BinaryPath = Fields[BINARY_PATH];
928   if (ShowMmapEvents) {
929     outs() << "Mmap: Binary " << MMap.BinaryPath << " loaded at "
930            << format("0x%" PRIx64 ":", MMap.Address) << " \n";
931   }
932 
933   StringRef BinaryName = llvm::sys::path::filename(MMap.BinaryPath);
934   return Binary->getName() == BinaryName;
935 }
936 
937 void PerfScriptReader::parseMMap2Event(TraceStream &TraceIt) {
938   MMapEvent MMap;
939   if (extractMMap2EventForBinary(Binary, TraceIt.getCurrentLine(), MMap))
940     updateBinaryAddress(MMap);
941   TraceIt.advance();
942 }
943 
944 void PerfScriptReader::parseEventOrSample(TraceStream &TraceIt) {
945   if (isMMap2Event(TraceIt.getCurrentLine()))
946     parseMMap2Event(TraceIt);
947   else
948     parseSample(TraceIt);
949 }
950 
951 void PerfScriptReader::parseAndAggregateTrace() {
952   // Trace line iterator
953   TraceStream TraceIt(PerfTraceFile);
954   while (!TraceIt.isAtEoF())
955     parseEventOrSample(TraceIt);
956 }
957 
958 // A LBR sample is like:
959 // 40062f 0x5c6313f/0x5c63170/P/-/-/0  0x5c630e7/0x5c63130/P/-/-/0 ...
960 // A heuristic for fast detection by checking whether a
961 // leading "  0x" and the '/' exist.
962 bool PerfScriptReader::isLBRSample(StringRef Line) {
963   // Skip the leading instruction pointer
964   SmallVector<StringRef, 32> Records;
965   Line.trim().split(Records, " ", 2, false);
966   if (Records.size() < 2)
967     return false;
968   if (Records[1].startswith("0x") && Records[1].contains('/'))
969     return true;
970   return false;
971 }
972 
973 bool PerfScriptReader::isMMap2Event(StringRef Line) {
974   // Short cut to avoid string find is possible.
975   if (Line.empty() || Line.size() < 50)
976     return false;
977 
978   if (std::isdigit(Line[0]))
979     return false;
980 
981   // PERF_RECORD_MMAP2 does not appear at the beginning of the line
982   // for ` perf script  --show-mmap-events  -i ...`
983   return Line.contains("PERF_RECORD_MMAP2");
984 }
985 
986 // The raw hybird sample is like
987 // e.g.
988 // 	          4005dc    # call stack leaf
989 //	          400634
990 //	          400684    # call stack root
991 // 0x4005c8/0x4005dc/P/-/-/0   0x40062f/0x4005b0/P/-/-/0 ...
992 //          ... 0x4005c8/0x4005dc/P/-/-/0    # LBR Entries
993 // Determine the perfscript contains hybrid samples(call stack + LBRs) by
994 // checking whether there is a non-empty call stack immediately followed by
995 // a LBR sample
996 PerfContent PerfScriptReader::checkPerfScriptType(StringRef FileName) {
997   TraceStream TraceIt(FileName);
998   uint64_t FrameAddr = 0;
999   while (!TraceIt.isAtEoF()) {
1000     // Skip the aggregated count
1001     if (!TraceIt.getCurrentLine().getAsInteger(10, FrameAddr))
1002       TraceIt.advance();
1003 
1004     // Detect sample with call stack
1005     int32_t Count = 0;
1006     while (!TraceIt.isAtEoF() &&
1007            !TraceIt.getCurrentLine().ltrim().getAsInteger(16, FrameAddr)) {
1008       Count++;
1009       TraceIt.advance();
1010     }
1011     if (!TraceIt.isAtEoF()) {
1012       if (isLBRSample(TraceIt.getCurrentLine())) {
1013         if (Count > 0)
1014           return PerfContent::LBRStack;
1015         else
1016           return PerfContent::LBR;
1017       }
1018       TraceIt.advance();
1019     }
1020   }
1021 
1022   exitWithError("Invalid perf script input!");
1023   return PerfContent::UnknownContent;
1024 }
1025 
1026 void HybridPerfReader::generateUnsymbolizedProfile() {
1027   ProfileIsCS = !IgnoreStackSamples;
1028   if (ProfileIsCS)
1029     unwindSamples();
1030   else
1031     PerfScriptReader::generateUnsymbolizedProfile();
1032 }
1033 
1034 void PerfScriptReader::warnTruncatedStack() {
1035   if (ShowDetailedWarning) {
1036     for (auto Address : InvalidReturnAddresses) {
1037       WithColor::warning()
1038           << "Truncated stack sample due to invalid return address at "
1039           << format("0x%" PRIx64, Address)
1040           << ", likely caused by frame pointer omission\n";
1041     }
1042   }
1043   emitWarningSummary(
1044       InvalidReturnAddresses.size(), AggregatedSamples.size(),
1045       "of truncated stack samples due to invalid return address, "
1046       "likely caused by frame pointer omission.");
1047 }
1048 
1049 void PerfScriptReader::warnInvalidRange() {
1050   std::unordered_map<std::pair<uint64_t, uint64_t>, uint64_t,
1051                      pair_hash<uint64_t, uint64_t>>
1052       Ranges;
1053 
1054   for (const auto &Item : AggregatedSamples) {
1055     const PerfSample *Sample = Item.first.getPtr();
1056     uint64_t Count = Item.second;
1057     uint64_t EndOffeset = 0;
1058     for (const LBREntry &LBR : Sample->LBRStack) {
1059       uint64_t SourceOffset = Binary->virtualAddrToOffset(LBR.Source);
1060       uint64_t StartOffset = Binary->virtualAddrToOffset(LBR.Target);
1061       if (EndOffeset != 0)
1062         Ranges[{StartOffset, EndOffeset}] += Count;
1063       EndOffeset = SourceOffset;
1064     }
1065   }
1066 
1067   if (Ranges.empty()) {
1068     WithColor::warning() << "No samples in perf script!\n";
1069     return;
1070   }
1071 
1072   auto WarnInvalidRange =
1073       [&](uint64_t StartOffset, uint64_t EndOffset, StringRef Msg) {
1074         if (!ShowDetailedWarning)
1075           return;
1076         WithColor::warning()
1077             << "["
1078             << format("%8" PRIx64, Binary->offsetToVirtualAddr(StartOffset))
1079             << ","
1080             << format("%8" PRIx64, Binary->offsetToVirtualAddr(EndOffset))
1081             << "]: " << Msg << "\n";
1082       };
1083 
1084   const char *EndNotBoundaryMsg = "Range is not on instruction boundary, "
1085                                   "likely due to profile and binary mismatch.";
1086   const char *DanglingRangeMsg = "Range does not belong to any functions, "
1087                                  "likely from PLT, .init or .fini section.";
1088   const char *RangeCrossFuncMsg =
1089       "Fall through range should not cross function boundaries, likely due to "
1090       "profile and binary mismatch.";
1091 
1092   uint64_t InstNotBoundary = 0;
1093   uint64_t UnmatchedRange = 0;
1094   uint64_t RangeCrossFunc = 0;
1095 
1096   for (auto &I : Ranges) {
1097     uint64_t StartOffset = I.first.first;
1098     uint64_t EndOffset = I.first.second;
1099 
1100     if (!Binary->offsetIsCode(StartOffset) ||
1101         !Binary->offsetIsTransfer(EndOffset)) {
1102       InstNotBoundary++;
1103       WarnInvalidRange(StartOffset, EndOffset, EndNotBoundaryMsg);
1104     }
1105 
1106     auto *FRange = Binary->findFuncRangeForOffset(StartOffset);
1107     if (!FRange) {
1108       UnmatchedRange++;
1109       WarnInvalidRange(StartOffset, EndOffset, DanglingRangeMsg);
1110       continue;
1111     }
1112 
1113     if (EndOffset >= FRange->EndOffset) {
1114       RangeCrossFunc++;
1115       WarnInvalidRange(StartOffset, EndOffset, RangeCrossFuncMsg);
1116     }
1117   }
1118 
1119   uint64_t TotalRangeNum = Ranges.size();
1120   emitWarningSummary(InstNotBoundary, TotalRangeNum,
1121                      "of profiled ranges are not on instruction boundary.");
1122   emitWarningSummary(UnmatchedRange, TotalRangeNum,
1123                      "of profiled ranges do not belong to any functions.");
1124   emitWarningSummary(RangeCrossFunc, TotalRangeNum,
1125                      "of profiled ranges do cross function boundaries.");
1126 }
1127 
1128 void PerfScriptReader::parsePerfTraces() {
1129   // Parse perf traces and do aggregation.
1130   parseAndAggregateTrace();
1131 
1132   // Generate unsymbolized profile.
1133   warnTruncatedStack();
1134   warnInvalidRange();
1135   generateUnsymbolizedProfile();
1136 
1137   if (SkipSymbolization)
1138     writeUnsymbolizedProfile(OutputFilename);
1139 }
1140 
1141 } // end namespace sampleprof
1142 } // end namespace llvm
1143