llvm-project
1269 строк · 45.8 Кб
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/ADT/SmallString.h"11#include "llvm/DebugInfo/Symbolize/SymbolizableModule.h"12#include "llvm/Support/FileSystem.h"13#include "llvm/Support/Process.h"14#include "llvm/Support/ToolOutputFile.h"15
16#define DEBUG_TYPE "perf-reader"17
18cl::opt<bool> SkipSymbolization("skip-symbolization",19cl::desc("Dump the unsymbolized profile to the "20"output file. It will show unwinder "21"output for CS profile generation."));22
23static cl::opt<bool> ShowMmapEvents("show-mmap-events",24cl::desc("Print binary load events."));25
26static cl::opt<bool>27UseOffset("use-offset", cl::init(true),28cl::desc("Work with `--skip-symbolization` or "29"`--unsymbolized-profile` to write/read the "30"offset instead of virtual address."));31
32static cl::opt<bool> UseLoadableSegmentAsBase(33"use-first-loadable-segment-as-base",34cl::desc("Use first loadable segment address as base address "35"for offsets in unsymbolized profile. By default "36"first executable segment address is used"));37
38static cl::opt<bool>39IgnoreStackSamples("ignore-stack-samples",40cl::desc("Ignore call stack samples for hybrid samples "41"and produce context-insensitive profile."));42cl::opt<bool> ShowDetailedWarning("show-detailed-warning",43cl::desc("Show detailed warning message."));44
45extern cl::opt<std::string> PerfTraceFilename;46extern cl::opt<bool> ShowDisassemblyOnly;47extern cl::opt<bool> ShowSourceLocations;48extern cl::opt<std::string> OutputFilename;49
50namespace llvm {51namespace sampleprof {52
53void VirtualUnwinder::unwindCall(UnwindState &State) {54uint64_t Source = State.getCurrentLBRSource();55auto *ParentFrame = State.getParentFrame();56// The 2nd frame after leaf could be missing if stack sample is57// taken when IP is within prolog/epilog, as frame chain isn't58// setup yet. Fill in the missing frame in that case.59// TODO: Currently we just assume all the addr that can't match the60// 2nd frame is in prolog/epilog. In the future, we will switch to61// pro/epi tracker(Dwarf CFI) for the precise check.62if (ParentFrame == State.getDummyRootPtr() ||63ParentFrame->Address != Source) {64State.switchToFrame(Source);65if (ParentFrame != State.getDummyRootPtr()) {66if (Source == ExternalAddr)67NumMismatchedExtCallBranch++;68else69NumMismatchedProEpiBranch++;70}71} else {72State.popFrame();73}74State.InstPtr.update(Source);75}
76
77void VirtualUnwinder::unwindLinear(UnwindState &State, uint64_t Repeat) {78InstructionPointer &IP = State.InstPtr;79uint64_t Target = State.getCurrentLBRTarget();80uint64_t End = IP.Address;81
82if (End == ExternalAddr && Target == ExternalAddr) {83// Filter out the case when leaf external frame matches the external LBR84// target, this is a valid state, it happens that the code run into external85// address then return back. The call frame under the external frame86// remains valid and can be unwound later, just skip recording this range.87NumPairedExtAddr++;88return;89}90
91if (End == ExternalAddr || Target == ExternalAddr) {92// Range is invalid if only one point is external address. This means LBR93// traces contains a standalone external address failing to pair another94// one, likely due to interrupt jmp or broken perf script. Set the95// state to invalid.96NumUnpairedExtAddr++;97State.setInvalid();98return;99}100
101if (!isValidFallThroughRange(Target, End, Binary)) {102// Skip unwinding the rest of LBR trace when a bogus range is seen.103State.setInvalid();104return;105}106
107if (Binary->usePseudoProbes()) {108// We don't need to top frame probe since it should be extracted109// from the range.110// The outcome of the virtual unwinding with pseudo probes is a111// map from a context key to the address range being unwound.112// This means basically linear unwinding is not needed for pseudo113// probes. The range will be simply recorded here and will be114// converted to a list of pseudo probes to report in ProfileGenerator.115State.getParentFrame()->recordRangeCount(Target, End, Repeat);116} else {117// Unwind linear execution part.118// Split and record the range by different inline context. For example:119// [0x01] ... main:1 # Target120// [0x02] ... main:2121// [0x03] ... main:3 @ foo:1122// [0x04] ... main:3 @ foo:2123// [0x05] ... main:3 @ foo:3124// [0x06] ... main:4125// [0x07] ... main:5 # End126// It will be recorded:127// [main:*] : [0x06, 0x07], [0x01, 0x02]128// [main:3 @ foo:*] : [0x03, 0x05]129while (IP.Address > Target) {130uint64_t PrevIP = IP.Address;131IP.backward();132// Break into segments for implicit call/return due to inlining133bool SameInlinee = Binary->inlineContextEqual(PrevIP, IP.Address);134if (!SameInlinee) {135State.switchToFrame(PrevIP);136State.CurrentLeafFrame->recordRangeCount(PrevIP, End, Repeat);137End = IP.Address;138}139}140assert(IP.Address == Target && "The last one must be the target address.");141// Record the remaining range, [0x01, 0x02] in the example142State.switchToFrame(IP.Address);143State.CurrentLeafFrame->recordRangeCount(IP.Address, End, Repeat);144}145}
146
147void VirtualUnwinder::unwindReturn(UnwindState &State) {148// Add extra frame as we unwind through the return149const LBREntry &LBR = State.getCurrentLBR();150uint64_t CallAddr = Binary->getCallAddrFromFrameAddr(LBR.Target);151State.switchToFrame(CallAddr);152State.pushFrame(LBR.Source);153State.InstPtr.update(LBR.Source);154}
155
156void VirtualUnwinder::unwindBranch(UnwindState &State) {157// TODO: Tolerate tail call for now, as we may see tail call from libraries.158// This is only for intra function branches, excluding tail calls.159uint64_t Source = State.getCurrentLBRSource();160State.switchToFrame(Source);161State.InstPtr.update(Source);162}
163
164std::shared_ptr<StringBasedCtxKey> FrameStack::getContextKey() {165std::shared_ptr<StringBasedCtxKey> KeyStr =166std::make_shared<StringBasedCtxKey>();167KeyStr->Context = Binary->getExpandedContext(Stack, KeyStr->WasLeafInlined);168return KeyStr;169}
170
171std::shared_ptr<AddrBasedCtxKey> AddressStack::getContextKey() {172std::shared_ptr<AddrBasedCtxKey> KeyStr = std::make_shared<AddrBasedCtxKey>();173KeyStr->Context = Stack;174CSProfileGenerator::compressRecursionContext<uint64_t>(KeyStr->Context);175CSProfileGenerator::trimContext<uint64_t>(KeyStr->Context);176return KeyStr;177}
178
179template <typename T>180void VirtualUnwinder::collectSamplesFromFrame(UnwindState::ProfiledFrame *Cur,181T &Stack) {182if (Cur->RangeSamples.empty() && Cur->BranchSamples.empty())183return;184
185std::shared_ptr<ContextKey> Key = Stack.getContextKey();186if (Key == nullptr)187return;188auto Ret = CtxCounterMap->emplace(Hashable<ContextKey>(Key), SampleCounter());189SampleCounter &SCounter = Ret.first->second;190for (auto &I : Cur->RangeSamples)191SCounter.recordRangeCount(std::get<0>(I), std::get<1>(I), std::get<2>(I));192
193for (auto &I : Cur->BranchSamples)194SCounter.recordBranchCount(std::get<0>(I), std::get<1>(I), std::get<2>(I));195}
196
197template <typename T>198void VirtualUnwinder::collectSamplesFromFrameTrie(199UnwindState::ProfiledFrame *Cur, T &Stack) {200if (!Cur->isDummyRoot()) {201// Truncate the context for external frame since this isn't a real call202// context the compiler will see.203if (Cur->isExternalFrame() || !Stack.pushFrame(Cur)) {204// Process truncated context205// Start a new traversal ignoring its bottom context206T EmptyStack(Binary);207collectSamplesFromFrame(Cur, EmptyStack);208for (const auto &Item : Cur->Children) {209collectSamplesFromFrameTrie(Item.second.get(), EmptyStack);210}211
212// Keep note of untracked call site and deduplicate them213// for warning later.214if (!Cur->isLeafFrame())215UntrackedCallsites.insert(Cur->Address);216
217return;218}219}220
221collectSamplesFromFrame(Cur, Stack);222// Process children frame223for (const auto &Item : Cur->Children) {224collectSamplesFromFrameTrie(Item.second.get(), Stack);225}226// Recover the call stack227Stack.popFrame();228}
229
230void VirtualUnwinder::collectSamplesFromFrameTrie(231UnwindState::ProfiledFrame *Cur) {232if (Binary->usePseudoProbes()) {233AddressStack Stack(Binary);234collectSamplesFromFrameTrie<AddressStack>(Cur, Stack);235} else {236FrameStack Stack(Binary);237collectSamplesFromFrameTrie<FrameStack>(Cur, Stack);238}239}
240
241void VirtualUnwinder::recordBranchCount(const LBREntry &Branch,242UnwindState &State, uint64_t Repeat) {243if (Branch.Target == ExternalAddr)244return;245
246// Record external-to-internal pattern on the trie root, it later can be247// used for generating head samples.248if (Branch.Source == ExternalAddr) {249State.getDummyRootPtr()->recordBranchCount(Branch.Source, Branch.Target,250Repeat);251return;252}253
254if (Binary->usePseudoProbes()) {255// Same as recordRangeCount, We don't need to top frame probe since we will256// extract it from branch's source address257State.getParentFrame()->recordBranchCount(Branch.Source, Branch.Target,258Repeat);259} else {260State.CurrentLeafFrame->recordBranchCount(Branch.Source, Branch.Target,261Repeat);262}263}
264
265bool VirtualUnwinder::unwind(const PerfSample *Sample, uint64_t Repeat) {266// Capture initial state as starting point for unwinding.267UnwindState State(Sample, Binary);268
269// Sanity check - making sure leaf of LBR aligns with leaf of stack sample270// Stack sample sometimes can be unreliable, so filter out bogus ones.271if (!State.validateInitialState())272return false;273
274NumTotalBranches += State.LBRStack.size();275// Now process the LBR samples in parrallel with stack sample276// Note that we do not reverse the LBR entry order so we can277// unwind the sample stack as we walk through LBR entries.278while (State.hasNextLBR()) {279State.checkStateConsistency();280
281// Do not attempt linear unwind for the leaf range as it's incomplete.282if (!State.IsLastLBR()) {283// Unwind implicit calls/returns from inlining, along the linear path,284// break into smaller sub section each with its own calling context.285unwindLinear(State, Repeat);286}287
288// Save the LBR branch before it gets unwound.289const LBREntry &Branch = State.getCurrentLBR();290if (isCallState(State)) {291// Unwind calls - we know we encountered call if LBR overlaps with292// transition between leaf the 2nd frame. Note that for calls that293// were not in the original stack sample, we should have added the294// extra frame when processing the return paired with this call.295unwindCall(State);296} else if (isReturnState(State)) {297// Unwind returns - check whether the IP is indeed at a return298// instruction299unwindReturn(State);300} else if (isValidState(State)) {301// Unwind branches302unwindBranch(State);303} else {304// Skip unwinding the rest of LBR trace. Reset the stack and update the305// state so that the rest of the trace can still be processed as if they306// do not have stack samples.307State.clearCallStack();308State.InstPtr.update(State.getCurrentLBRSource());309State.pushFrame(State.InstPtr.Address);310}311
312State.advanceLBR();313// Record `branch` with calling context after unwinding.314recordBranchCount(Branch, State, Repeat);315}316// As samples are aggregated on trie, record them into counter map317collectSamplesFromFrameTrie(State.getDummyRootPtr());318
319return true;320}
321
322std::unique_ptr<PerfReaderBase>323PerfReaderBase::create(ProfiledBinary *Binary, PerfInputFile &PerfInput,324std::optional<int32_t> PIDFilter) {325std::unique_ptr<PerfReaderBase> PerfReader;326
327if (PerfInput.Format == PerfFormat::UnsymbolizedProfile) {328PerfReader.reset(329new UnsymbolizedProfileReader(Binary, PerfInput.InputFile));330return PerfReader;331}332
333// For perf data input, we need to convert them into perf script first.334// If this is a kernel perf file, there is no need for retrieving PIDs.335if (PerfInput.Format == PerfFormat::PerfData)336PerfInput = PerfScriptReader::convertPerfDataToTrace(337Binary, Binary->isKernel(), PerfInput, PIDFilter);338
339assert((PerfInput.Format == PerfFormat::PerfScript) &&340"Should be a perfscript!");341
342PerfInput.Content =343PerfScriptReader::checkPerfScriptType(PerfInput.InputFile);344if (PerfInput.Content == PerfContent::LBRStack) {345PerfReader.reset(346new HybridPerfReader(Binary, PerfInput.InputFile, PIDFilter));347} else if (PerfInput.Content == PerfContent::LBR) {348PerfReader.reset(new LBRPerfReader(Binary, PerfInput.InputFile, PIDFilter));349} else {350exitWithError("Unsupported perfscript!");351}352
353return PerfReader;354}
355
356PerfInputFile
357PerfScriptReader::convertPerfDataToTrace(ProfiledBinary *Binary, bool SkipPID,358PerfInputFile &File,359std::optional<int32_t> PIDFilter) {360StringRef PerfData = File.InputFile;361// Run perf script to retrieve PIDs matching binary we're interested in.362auto PerfExecutable = sys::Process::FindInEnvPath("PATH", "perf");363if (!PerfExecutable) {364exitWithError("Perf not found.");365}366std::string PerfPath = *PerfExecutable;367SmallString<128> PerfTraceFile;368sys::fs::createUniquePath("perf-script-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%.tmp",369PerfTraceFile, /*MakeAbsolute=*/true);370std::string ErrorFile = std::string(PerfTraceFile) + ".err";371std::optional<StringRef> Redirects[] = {std::nullopt, // Stdin372StringRef(PerfTraceFile), // Stdout373StringRef(ErrorFile)}; // Stderr374PerfScriptReader::TempFileCleanups.emplace_back(PerfTraceFile);375PerfScriptReader::TempFileCleanups.emplace_back(ErrorFile);376
377std::string PIDs;378if (!SkipPID) {379StringRef ScriptMMapArgs[] = {PerfPath, "script", "--show-mmap-events",380"-F", "comm,pid", "-i",381PerfData};382sys::ExecuteAndWait(PerfPath, ScriptMMapArgs, std::nullopt, Redirects);383
384// Collect the PIDs385TraceStream TraceIt(PerfTraceFile);386std::unordered_set<int32_t> PIDSet;387while (!TraceIt.isAtEoF()) {388MMapEvent MMap;389if (isMMapEvent(TraceIt.getCurrentLine()) &&390extractMMapEventForBinary(Binary, TraceIt.getCurrentLine(), MMap)) {391auto It = PIDSet.emplace(MMap.PID);392if (It.second && (!PIDFilter || MMap.PID == *PIDFilter)) {393if (!PIDs.empty()) {394PIDs.append(",");395}396PIDs.append(utostr(MMap.PID));397}398}399TraceIt.advance();400}401
402if (PIDs.empty()) {403exitWithError("No relevant mmap event is found in perf data.");404}405}406
407// Run perf script again to retrieve events for PIDs collected above408SmallVector<StringRef, 8> ScriptSampleArgs;409ScriptSampleArgs.push_back(PerfPath);410ScriptSampleArgs.push_back("script");411ScriptSampleArgs.push_back("--show-mmap-events");412ScriptSampleArgs.push_back("-F");413ScriptSampleArgs.push_back("ip,brstack");414ScriptSampleArgs.push_back("-i");415ScriptSampleArgs.push_back(PerfData);416if (!PIDs.empty()) {417ScriptSampleArgs.push_back("--pid");418ScriptSampleArgs.push_back(PIDs);419}420sys::ExecuteAndWait(PerfPath, ScriptSampleArgs, std::nullopt, Redirects);421
422return {std::string(PerfTraceFile), PerfFormat::PerfScript,423PerfContent::UnknownContent};424}
425
426static StringRef filename(StringRef Path, bool UseBackSlash) {427llvm::sys::path::Style PathStyle =428UseBackSlash ? llvm::sys::path::Style::windows_backslash429: llvm::sys::path::Style::native;430StringRef FileName = llvm::sys::path::filename(Path, PathStyle);431
432// In case this file use \r\n as newline.433if (UseBackSlash && FileName.back() == '\r')434return FileName.drop_back();435
436return FileName;437}
438
439void PerfScriptReader::updateBinaryAddress(const MMapEvent &Event) {440// Drop the event which doesn't belong to user-provided binary441StringRef BinaryName = filename(Event.BinaryPath, Binary->isCOFF());442bool IsKernel = Binary->isKernel();443if (!IsKernel && Binary->getName() != BinaryName)444return;445if (IsKernel && !Binary->isKernelImageName(BinaryName))446return;447
448// Drop the event if process does not match pid filter449if (PIDFilter && Event.PID != *PIDFilter)450return;451
452// Drop the event if its image is loaded at the same address453if (Event.Address == Binary->getBaseAddress()) {454Binary->setIsLoadedByMMap(true);455return;456}457
458if (IsKernel || Event.Offset == Binary->getTextSegmentOffset()) {459// A binary image could be unloaded and then reloaded at different460// place, so update binary load address.461// Only update for the first executable segment and assume all other462// segments are loaded at consecutive memory addresses, which is the case on463// X64.464Binary->setBaseAddress(Event.Address);465Binary->setIsLoadedByMMap(true);466} else {467// Verify segments are loaded consecutively.468const auto &Offsets = Binary->getTextSegmentOffsets();469auto It = llvm::lower_bound(Offsets, Event.Offset);470if (It != Offsets.end() && *It == Event.Offset) {471// The event is for loading a separate executable segment.472auto I = std::distance(Offsets.begin(), It);473const auto &PreferredAddrs = Binary->getPreferredTextSegmentAddresses();474if (PreferredAddrs[I] - Binary->getPreferredBaseAddress() !=475Event.Address - Binary->getBaseAddress())476exitWithError("Executable segments not loaded consecutively");477} else {478if (It == Offsets.begin())479exitWithError("File offset not found");480else {481// Find the segment the event falls in. A large segment could be loaded482// via multiple mmap calls with consecutive memory addresses.483--It;484assert(*It < Event.Offset);485if (Event.Offset - *It != Event.Address - Binary->getBaseAddress())486exitWithError("Segment not loaded by consecutive mmaps");487}488}489}490}
491
492static std::string getContextKeyStr(ContextKey *K,493const ProfiledBinary *Binary) {494if (const auto *CtxKey = dyn_cast<StringBasedCtxKey>(K)) {495return SampleContext::getContextString(CtxKey->Context);496} else if (const auto *CtxKey = dyn_cast<AddrBasedCtxKey>(K)) {497std::ostringstream OContextStr;498for (uint32_t I = 0; I < CtxKey->Context.size(); I++) {499if (OContextStr.str().size())500OContextStr << " @ ";501uint64_t Address = CtxKey->Context[I];502if (UseOffset) {503if (UseLoadableSegmentAsBase)504Address -= Binary->getFirstLoadableAddress();505else506Address -= Binary->getPreferredBaseAddress();507}508OContextStr << "0x"509<< utohexstr(Address,510/*LowerCase=*/true);511}512return OContextStr.str();513} else {514llvm_unreachable("unexpected key type");515}516}
517
518void HybridPerfReader::unwindSamples() {519VirtualUnwinder Unwinder(&SampleCounters, Binary);520for (const auto &Item : AggregatedSamples) {521const PerfSample *Sample = Item.first.getPtr();522Unwinder.unwind(Sample, Item.second);523}524
525// Warn about untracked frames due to missing probes.526if (ShowDetailedWarning) {527for (auto Address : Unwinder.getUntrackedCallsites())528WithColor::warning() << "Profile context truncated due to missing probe "529<< "for call instruction at "530<< format("0x%" PRIx64, Address) << "\n";531}532
533emitWarningSummary(Unwinder.getUntrackedCallsites().size(),534SampleCounters.size(),535"of profiled contexts are truncated due to missing probe "536"for call instruction.");537
538emitWarningSummary(539Unwinder.NumMismatchedExtCallBranch, Unwinder.NumTotalBranches,540"of branches'source is a call instruction but doesn't match call frame "541"stack, likely due to unwinding error of external frame.");542
543emitWarningSummary(Unwinder.NumPairedExtAddr * 2, Unwinder.NumTotalBranches,544"of branches containing paired external address.");545
546emitWarningSummary(Unwinder.NumUnpairedExtAddr, Unwinder.NumTotalBranches,547"of branches containing external address but doesn't have "548"another external address to pair, likely due to "549"interrupt jmp or broken perf script.");550
551emitWarningSummary(552Unwinder.NumMismatchedProEpiBranch, Unwinder.NumTotalBranches,553"of branches'source is a call instruction but doesn't match call frame "554"stack, likely due to frame in prolog/epilog.");555
556emitWarningSummary(Unwinder.NumMissingExternalFrame,557Unwinder.NumExtCallBranch,558"of artificial call branches but doesn't have an external "559"frame to match.");560}
561
562bool PerfScriptReader::extractLBRStack(TraceStream &TraceIt,563SmallVectorImpl<LBREntry> &LBRStack) {564// The raw format of LBR stack is like:565// 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...566// ... 0x4005c8/0x4005dc/P/-/-/0567// It's in FIFO order and separated by whitespace.568SmallVector<StringRef, 32> Records;569TraceIt.getCurrentLine().rtrim().split(Records, " ", -1, false);570auto WarnInvalidLBR = [](TraceStream &TraceIt) {571WithColor::warning() << "Invalid address in LBR record at line "572<< TraceIt.getLineNumber() << ": "573<< TraceIt.getCurrentLine() << "\n";574};575
576// Skip the leading instruction pointer.577size_t Index = 0;578uint64_t LeadingAddr;579if (!Records.empty() && !Records[0].contains('/')) {580if (Records[0].getAsInteger(16, LeadingAddr)) {581WarnInvalidLBR(TraceIt);582TraceIt.advance();583return false;584}585Index = 1;586}587
588// Now extract LBR samples - note that we do not reverse the589// LBR entry order so we can unwind the sample stack as we walk590// through LBR entries.591while (Index < Records.size()) {592auto &Token = Records[Index++];593if (Token.size() == 0)594continue;595
596SmallVector<StringRef, 8> Addresses;597Token.split(Addresses, "/");598uint64_t Src;599uint64_t Dst;600
601// Stop at broken LBR records.602if (Addresses.size() < 2 || Addresses[0].substr(2).getAsInteger(16, Src) ||603Addresses[1].substr(2).getAsInteger(16, Dst)) {604WarnInvalidLBR(TraceIt);605break;606}607
608// Canonicalize to use preferred load address as base address.609Src = Binary->canonicalizeVirtualAddress(Src);610Dst = Binary->canonicalizeVirtualAddress(Dst);611bool SrcIsInternal = Binary->addressIsCode(Src);612bool DstIsInternal = Binary->addressIsCode(Dst);613if (!SrcIsInternal)614Src = ExternalAddr;615if (!DstIsInternal)616Dst = ExternalAddr;617// Filter external-to-external case to reduce LBR trace size.618if (!SrcIsInternal && !DstIsInternal)619continue;620
621LBRStack.emplace_back(LBREntry(Src, Dst));622}623TraceIt.advance();624return !LBRStack.empty();625}
626
627bool PerfScriptReader::extractCallstack(TraceStream &TraceIt,628SmallVectorImpl<uint64_t> &CallStack) {629// The raw format of call stack is like:630// 4005dc # leaf frame631// 400634632// 400684 # root frame633// It's in bottom-up order with each frame in one line.634
635// Extract stack frames from sample636while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().starts_with(" 0x")) {637StringRef FrameStr = TraceIt.getCurrentLine().ltrim();638uint64_t FrameAddr = 0;639if (FrameStr.getAsInteger(16, FrameAddr)) {640// We might parse a non-perf sample line like empty line and comments,641// skip it642TraceIt.advance();643return false;644}645TraceIt.advance();646
647FrameAddr = Binary->canonicalizeVirtualAddress(FrameAddr);648// Currently intermixed frame from different binaries is not supported.649if (!Binary->addressIsCode(FrameAddr)) {650if (CallStack.empty())651NumLeafExternalFrame++;652// Push a special value(ExternalAddr) for the external frames so that653// unwinder can still work on this with artificial Call/Return branch.654// After unwinding, the context will be truncated for external frame.655// Also deduplicate the consecutive external addresses.656if (CallStack.empty() || CallStack.back() != ExternalAddr)657CallStack.emplace_back(ExternalAddr);658continue;659}660
661// We need to translate return address to call address for non-leaf frames.662if (!CallStack.empty()) {663auto CallAddr = Binary->getCallAddrFromFrameAddr(FrameAddr);664if (!CallAddr) {665// Stop at an invalid return address caused by bad unwinding. This could666// happen to frame-pointer-based unwinding and the callee functions that667// do not have the frame pointer chain set up.668InvalidReturnAddresses.insert(FrameAddr);669break;670}671FrameAddr = CallAddr;672}673
674CallStack.emplace_back(FrameAddr);675}676
677// Strip out the bottom external addr.678if (CallStack.size() > 1 && CallStack.back() == ExternalAddr)679CallStack.pop_back();680
681// Skip other unrelated line, find the next valid LBR line682// Note that even for empty call stack, we should skip the address at the683// bottom, otherwise the following pass may generate a truncated callstack684while (!TraceIt.isAtEoF() && !TraceIt.getCurrentLine().starts_with(" 0x")) {685TraceIt.advance();686}687// Filter out broken stack sample. We may not have complete frame info688// if sample end up in prolog/epilog, the result is dangling context not689// connected to entry point. This should be relatively rare thus not much690// impact on overall profile quality. However we do want to filter them691// out to reduce the number of different calling contexts. One instance692// of such case - when sample landed in prolog/epilog, somehow stack693// walking will be broken in an unexpected way that higher frames will be694// missing.695return !CallStack.empty() &&696!Binary->addressInPrologEpilog(CallStack.front());697}
698
699void PerfScriptReader::warnIfMissingMMap() {700if (!Binary->getMissingMMapWarned() && !Binary->getIsLoadedByMMap()) {701WithColor::warning() << "No relevant mmap event is matched for "702<< Binary->getName()703<< ", will use preferred address ("704<< format("0x%" PRIx64,705Binary->getPreferredBaseAddress())706<< ") as the base loading address!\n";707// Avoid redundant warning, only warn at the first unmatched sample.708Binary->setMissingMMapWarned(true);709}710}
711
712void HybridPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {713// The raw hybird sample started with call stack in FILO order and followed714// intermediately by LBR sample715// e.g.716// 4005dc # call stack leaf717// 400634718// 400684 # call stack root719// 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...720// ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries721//722std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();723#ifndef NDEBUG724Sample->Linenum = TraceIt.getLineNumber();725#endif726// Parsing call stack and populate into PerfSample.CallStack727if (!extractCallstack(TraceIt, Sample->CallStack)) {728// Skip the next LBR line matched current call stack729if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().starts_with(" 0x"))730TraceIt.advance();731return;732}733
734warnIfMissingMMap();735
736if (!TraceIt.isAtEoF() && TraceIt.getCurrentLine().starts_with(" 0x")) {737// Parsing LBR stack and populate into PerfSample.LBRStack738if (extractLBRStack(TraceIt, Sample->LBRStack)) {739if (IgnoreStackSamples) {740Sample->CallStack.clear();741} else {742// Canonicalize stack leaf to avoid 'random' IP from leaf frame skew LBR743// ranges744Sample->CallStack.front() = Sample->LBRStack[0].Target;745}746// Record samples by aggregation747AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;748}749} else {750// LBR sample is encoded in single line after stack sample751exitWithError("'Hybrid perf sample is corrupted, No LBR sample line");752}753}
754
755void PerfScriptReader::writeUnsymbolizedProfile(StringRef Filename) {756std::error_code EC;757raw_fd_ostream OS(Filename, EC, llvm::sys::fs::OF_TextWithCRLF);758if (EC)759exitWithError(EC, Filename);760writeUnsymbolizedProfile(OS);761}
762
763// Use ordered map to make the output deterministic
764using OrderedCounterForPrint = std::map<std::string, SampleCounter *>;765
766void PerfScriptReader::writeUnsymbolizedProfile(raw_fd_ostream &OS) {767OrderedCounterForPrint OrderedCounters;768for (auto &CI : SampleCounters) {769OrderedCounters[getContextKeyStr(CI.first.getPtr(), Binary)] = &CI.second;770}771
772auto SCounterPrinter = [&](RangeSample &Counter, StringRef Separator,773uint32_t Indent) {774OS.indent(Indent);775OS << Counter.size() << "\n";776for (auto &I : Counter) {777uint64_t Start = I.first.first;778uint64_t End = I.first.second;779
780if (UseOffset) {781if (UseLoadableSegmentAsBase) {782Start -= Binary->getFirstLoadableAddress();783End -= Binary->getFirstLoadableAddress();784} else {785Start -= Binary->getPreferredBaseAddress();786End -= Binary->getPreferredBaseAddress();787}788}789
790OS.indent(Indent);791OS << Twine::utohexstr(Start) << Separator << Twine::utohexstr(End) << ":"792<< I.second << "\n";793}794};795
796for (auto &CI : OrderedCounters) {797uint32_t Indent = 0;798if (ProfileIsCS) {799// Context string key800OS << "[" << CI.first << "]\n";801Indent = 2;802}803
804SampleCounter &Counter = *CI.second;805SCounterPrinter(Counter.RangeCounter, "-", Indent);806SCounterPrinter(Counter.BranchCounter, "->", Indent);807}808}
809
810// Format of input:
811// number of entries in RangeCounter
812// from_1-to_1:count_1
813// from_2-to_2:count_2
814// ......
815// from_n-to_n:count_n
816// number of entries in BranchCounter
817// src_1->dst_1:count_1
818// src_2->dst_2:count_2
819// ......
820// src_n->dst_n:count_n
821void UnsymbolizedProfileReader::readSampleCounters(TraceStream &TraceIt,822SampleCounter &SCounters) {823auto exitWithErrorForTraceLine = [](TraceStream &TraceIt) {824std::string Msg = TraceIt.isAtEoF()825? "Invalid raw profile!"826: "Invalid raw profile at line " +827Twine(TraceIt.getLineNumber()).str() + ": " +828TraceIt.getCurrentLine().str();829exitWithError(Msg);830};831auto ReadNumber = [&](uint64_t &Num) {832if (TraceIt.isAtEoF())833exitWithErrorForTraceLine(TraceIt);834if (TraceIt.getCurrentLine().ltrim().getAsInteger(10, Num))835exitWithErrorForTraceLine(TraceIt);836TraceIt.advance();837};838
839auto ReadCounter = [&](RangeSample &Counter, StringRef Separator) {840uint64_t Num = 0;841ReadNumber(Num);842while (Num--) {843if (TraceIt.isAtEoF())844exitWithErrorForTraceLine(TraceIt);845StringRef Line = TraceIt.getCurrentLine().ltrim();846
847uint64_t Count = 0;848auto LineSplit = Line.split(":");849if (LineSplit.second.empty() || LineSplit.second.getAsInteger(10, Count))850exitWithErrorForTraceLine(TraceIt);851
852uint64_t Source = 0;853uint64_t Target = 0;854auto Range = LineSplit.first.split(Separator);855if (Range.second.empty() || Range.first.getAsInteger(16, Source) ||856Range.second.getAsInteger(16, Target))857exitWithErrorForTraceLine(TraceIt);858
859if (UseOffset) {860if (UseLoadableSegmentAsBase) {861Source += Binary->getFirstLoadableAddress();862Target += Binary->getFirstLoadableAddress();863} else {864Source += Binary->getPreferredBaseAddress();865Target += Binary->getPreferredBaseAddress();866}867}868
869Counter[{Source, Target}] += Count;870TraceIt.advance();871}872};873
874ReadCounter(SCounters.RangeCounter, "-");875ReadCounter(SCounters.BranchCounter, "->");876}
877
878void UnsymbolizedProfileReader::readUnsymbolizedProfile(StringRef FileName) {879TraceStream TraceIt(FileName);880while (!TraceIt.isAtEoF()) {881std::shared_ptr<StringBasedCtxKey> Key =882std::make_shared<StringBasedCtxKey>();883StringRef Line = TraceIt.getCurrentLine();884// Read context stack for CS profile.885if (Line.starts_with("[")) {886ProfileIsCS = true;887auto I = ContextStrSet.insert(Line.str());888SampleContext::createCtxVectorFromStr(*I.first, Key->Context);889TraceIt.advance();890}891auto Ret =892SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());893readSampleCounters(TraceIt, Ret.first->second);894}895}
896
897void UnsymbolizedProfileReader::parsePerfTraces() {898readUnsymbolizedProfile(PerfTraceFile);899}
900
901void PerfScriptReader::computeCounterFromLBR(const PerfSample *Sample,902uint64_t Repeat) {903SampleCounter &Counter = SampleCounters.begin()->second;904uint64_t EndAddress = 0;905for (const LBREntry &LBR : Sample->LBRStack) {906uint64_t SourceAddress = LBR.Source;907uint64_t TargetAddress = LBR.Target;908
909// Record the branch if its SourceAddress is external. It can be the case an910// external source call an internal function, later this branch will be used911// to generate the function's head sample.912if (Binary->addressIsCode(TargetAddress)) {913Counter.recordBranchCount(SourceAddress, TargetAddress, Repeat);914}915
916// If this not the first LBR, update the range count between TO of current917// LBR and FROM of next LBR.918uint64_t StartAddress = TargetAddress;919if (Binary->addressIsCode(StartAddress) &&920Binary->addressIsCode(EndAddress) &&921isValidFallThroughRange(StartAddress, EndAddress, Binary))922Counter.recordRangeCount(StartAddress, EndAddress, Repeat);923EndAddress = SourceAddress;924}925}
926
927void LBRPerfReader::parseSample(TraceStream &TraceIt, uint64_t Count) {928std::shared_ptr<PerfSample> Sample = std::make_shared<PerfSample>();929// Parsing LBR stack and populate into PerfSample.LBRStack930if (extractLBRStack(TraceIt, Sample->LBRStack)) {931warnIfMissingMMap();932// Record LBR only samples by aggregation933AggregatedSamples[Hashable<PerfSample>(Sample)] += Count;934}935}
936
937void PerfScriptReader::generateUnsymbolizedProfile() {938// There is no context for LBR only sample, so initialize one entry with939// fake "empty" context key.940assert(SampleCounters.empty() &&941"Sample counter map should be empty before raw profile generation");942std::shared_ptr<StringBasedCtxKey> Key =943std::make_shared<StringBasedCtxKey>();944SampleCounters.emplace(Hashable<ContextKey>(Key), SampleCounter());945for (const auto &Item : AggregatedSamples) {946const PerfSample *Sample = Item.first.getPtr();947computeCounterFromLBR(Sample, Item.second);948}949}
950
951uint64_t PerfScriptReader::parseAggregatedCount(TraceStream &TraceIt) {952// The aggregated count is optional, so do not skip the line and return 1 if953// it's unmatched954uint64_t Count = 1;955if (!TraceIt.getCurrentLine().getAsInteger(10, Count))956TraceIt.advance();957return Count;958}
959
960void PerfScriptReader::parseSample(TraceStream &TraceIt) {961NumTotalSample++;962uint64_t Count = parseAggregatedCount(TraceIt);963assert(Count >= 1 && "Aggregated count should be >= 1!");964parseSample(TraceIt, Count);965}
966
967bool PerfScriptReader::extractMMapEventForBinary(ProfiledBinary *Binary,968StringRef Line,969MMapEvent &MMap) {970// Parse a MMap2 line like:971// PERF_RECORD_MMAP2 2113428/2113428: [0x7fd4efb57000(0x204000) @ 0972// 08:04 19532229 3585508847]: r-xp /usr/lib64/libdl-2.17.so973constexpr static const char *const MMap2Pattern =974"PERF_RECORD_MMAP2 (-?[0-9]+)/[0-9]+: "975"\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "976"(0x[a-f0-9]+|0) .*\\]: [-a-z]+ (.*)";977// Parse a MMap line like978// PERF_RECORD_MMAP -1/0: [0xffffffff81e00000(0x3e8fa000) @ \979// 0xffffffff81e00000]: x [kernel.kallsyms]_text
980constexpr static const char *const MMapPattern =981"PERF_RECORD_MMAP (-?[0-9]+)/[0-9]+: "982"\\[(0x[a-f0-9]+)\\((0x[a-f0-9]+)\\) @ "983"(0x[a-f0-9]+|0)\\]: [-a-z]+ (.*)";984// Field 0 - whole line985// Field 1 - PID986// Field 2 - base address987// Field 3 - mmapped size988// Field 4 - page offset989// Field 5 - binary path990enum EventIndex {991WHOLE_LINE = 0,992PID = 1,993MMAPPED_ADDRESS = 2,994MMAPPED_SIZE = 3,995PAGE_OFFSET = 4,996BINARY_PATH = 5997};998
999bool R = false;1000SmallVector<StringRef, 6> Fields;1001if (Line.contains("PERF_RECORD_MMAP2 ")) {1002Regex RegMmap2(MMap2Pattern);1003R = RegMmap2.match(Line, &Fields);1004} else if (Line.contains("PERF_RECORD_MMAP ")) {1005Regex RegMmap(MMapPattern);1006R = RegMmap.match(Line, &Fields);1007} else1008llvm_unreachable("unexpected MMAP event entry");1009
1010if (!R) {1011std::string WarningMsg = "Cannot parse mmap event: " + Line.str() + " \n";1012WithColor::warning() << WarningMsg;1013return false;1014}1015long long MMapPID = 0;1016getAsSignedInteger(Fields[PID], 10, MMapPID);1017MMap.PID = MMapPID;1018Fields[MMAPPED_ADDRESS].getAsInteger(0, MMap.Address);1019Fields[MMAPPED_SIZE].getAsInteger(0, MMap.Size);1020Fields[PAGE_OFFSET].getAsInteger(0, MMap.Offset);1021MMap.BinaryPath = Fields[BINARY_PATH];1022if (ShowMmapEvents) {1023outs() << "Mmap: Binary " << MMap.BinaryPath << " loaded at "1024<< format("0x%" PRIx64 ":", MMap.Address) << " \n";1025}1026
1027StringRef BinaryName = filename(MMap.BinaryPath, Binary->isCOFF());1028if (Binary->isKernel()) {1029return Binary->isKernelImageName(BinaryName);1030}1031return Binary->getName() == BinaryName;1032}
1033
1034void PerfScriptReader::parseMMapEvent(TraceStream &TraceIt) {1035MMapEvent MMap;1036if (extractMMapEventForBinary(Binary, TraceIt.getCurrentLine(), MMap))1037updateBinaryAddress(MMap);1038TraceIt.advance();1039}
1040
1041void PerfScriptReader::parseEventOrSample(TraceStream &TraceIt) {1042if (isMMapEvent(TraceIt.getCurrentLine()))1043parseMMapEvent(TraceIt);1044else1045parseSample(TraceIt);1046}
1047
1048void PerfScriptReader::parseAndAggregateTrace() {1049// Trace line iterator1050TraceStream TraceIt(PerfTraceFile);1051while (!TraceIt.isAtEoF())1052parseEventOrSample(TraceIt);1053}
1054
1055// A LBR sample is like:
1056// 40062f 0x5c6313f/0x5c63170/P/-/-/0 0x5c630e7/0x5c63130/P/-/-/0 ...
1057// A heuristic for fast detection by checking whether a
1058// leading " 0x" and the '/' exist.
1059bool PerfScriptReader::isLBRSample(StringRef Line) {1060// Skip the leading instruction pointer1061SmallVector<StringRef, 32> Records;1062Line.trim().split(Records, " ", 2, false);1063if (Records.size() < 2)1064return false;1065if (Records[1].starts_with("0x") && Records[1].contains('/'))1066return true;1067return false;1068}
1069
1070bool PerfScriptReader::isMMapEvent(StringRef Line) {1071// Short cut to avoid string find is possible.1072if (Line.empty() || Line.size() < 50)1073return false;1074
1075if (std::isdigit(Line[0]))1076return false;1077
1078// PERF_RECORD_MMAP2 or PERF_RECORD_MMAP does not appear at the beginning of1079// the line for ` perf script --show-mmap-events -i ...`1080return Line.contains("PERF_RECORD_MMAP");1081}
1082
1083// The raw hybird sample is like
1084// e.g.
1085// 4005dc # call stack leaf
1086// 400634
1087// 400684 # call stack root
1088// 0x4005c8/0x4005dc/P/-/-/0 0x40062f/0x4005b0/P/-/-/0 ...
1089// ... 0x4005c8/0x4005dc/P/-/-/0 # LBR Entries
1090// Determine the perfscript contains hybrid samples(call stack + LBRs) by
1091// checking whether there is a non-empty call stack immediately followed by
1092// a LBR sample
1093PerfContent PerfScriptReader::checkPerfScriptType(StringRef FileName) {1094TraceStream TraceIt(FileName);1095uint64_t FrameAddr = 0;1096while (!TraceIt.isAtEoF()) {1097// Skip the aggregated count1098if (!TraceIt.getCurrentLine().getAsInteger(10, FrameAddr))1099TraceIt.advance();1100
1101// Detect sample with call stack1102int32_t Count = 0;1103while (!TraceIt.isAtEoF() &&1104!TraceIt.getCurrentLine().ltrim().getAsInteger(16, FrameAddr)) {1105Count++;1106TraceIt.advance();1107}1108if (!TraceIt.isAtEoF()) {1109if (isLBRSample(TraceIt.getCurrentLine())) {1110if (Count > 0)1111return PerfContent::LBRStack;1112else1113return PerfContent::LBR;1114}1115TraceIt.advance();1116}1117}1118
1119exitWithError("Invalid perf script input!");1120return PerfContent::UnknownContent;1121}
1122
1123void HybridPerfReader::generateUnsymbolizedProfile() {1124ProfileIsCS = !IgnoreStackSamples;1125if (ProfileIsCS)1126unwindSamples();1127else1128PerfScriptReader::generateUnsymbolizedProfile();1129}
1130
1131void PerfScriptReader::warnTruncatedStack() {1132if (ShowDetailedWarning) {1133for (auto Address : InvalidReturnAddresses) {1134WithColor::warning()1135<< "Truncated stack sample due to invalid return address at "1136<< format("0x%" PRIx64, Address)1137<< ", likely caused by frame pointer omission\n";1138}1139}1140emitWarningSummary(1141InvalidReturnAddresses.size(), AggregatedSamples.size(),1142"of truncated stack samples due to invalid return address, "1143"likely caused by frame pointer omission.");1144}
1145
1146void PerfScriptReader::warnInvalidRange() {1147std::unordered_map<std::pair<uint64_t, uint64_t>, uint64_t,1148pair_hash<uint64_t, uint64_t>>1149Ranges;1150
1151for (const auto &Item : AggregatedSamples) {1152const PerfSample *Sample = Item.first.getPtr();1153uint64_t Count = Item.second;1154uint64_t EndAddress = 0;1155for (const LBREntry &LBR : Sample->LBRStack) {1156uint64_t SourceAddress = LBR.Source;1157uint64_t StartAddress = LBR.Target;1158if (EndAddress != 0)1159Ranges[{StartAddress, EndAddress}] += Count;1160EndAddress = SourceAddress;1161}1162}1163
1164if (Ranges.empty()) {1165WithColor::warning() << "No samples in perf script!\n";1166return;1167}1168
1169auto WarnInvalidRange = [&](uint64_t StartAddress, uint64_t EndAddress,1170StringRef Msg) {1171if (!ShowDetailedWarning)1172return;1173WithColor::warning() << "[" << format("%8" PRIx64, StartAddress) << ","1174<< format("%8" PRIx64, EndAddress) << "]: " << Msg1175<< "\n";1176};1177
1178const char *EndNotBoundaryMsg = "Range is not on instruction boundary, "1179"likely due to profile and binary mismatch.";1180const char *DanglingRangeMsg = "Range does not belong to any functions, "1181"likely from PLT, .init or .fini section.";1182const char *RangeCrossFuncMsg =1183"Fall through range should not cross function boundaries, likely due to "1184"profile and binary mismatch.";1185const char *BogusRangeMsg = "Range start is after or too far from range end.";1186
1187uint64_t TotalRangeNum = 0;1188uint64_t InstNotBoundary = 0;1189uint64_t UnmatchedRange = 0;1190uint64_t RangeCrossFunc = 0;1191uint64_t BogusRange = 0;1192
1193for (auto &I : Ranges) {1194uint64_t StartAddress = I.first.first;1195uint64_t EndAddress = I.first.second;1196TotalRangeNum += I.second;1197
1198if (!Binary->addressIsCode(StartAddress) &&1199!Binary->addressIsCode(EndAddress))1200continue;1201
1202if (!Binary->addressIsCode(StartAddress) ||1203!Binary->addressIsTransfer(EndAddress)) {1204InstNotBoundary += I.second;1205WarnInvalidRange(StartAddress, EndAddress, EndNotBoundaryMsg);1206}1207
1208auto *FRange = Binary->findFuncRange(StartAddress);1209if (!FRange) {1210UnmatchedRange += I.second;1211WarnInvalidRange(StartAddress, EndAddress, DanglingRangeMsg);1212continue;1213}1214
1215if (EndAddress >= FRange->EndAddress) {1216RangeCrossFunc += I.second;1217WarnInvalidRange(StartAddress, EndAddress, RangeCrossFuncMsg);1218}1219
1220if (Binary->addressIsCode(StartAddress) &&1221Binary->addressIsCode(EndAddress) &&1222!isValidFallThroughRange(StartAddress, EndAddress, Binary)) {1223BogusRange += I.second;1224WarnInvalidRange(StartAddress, EndAddress, BogusRangeMsg);1225}1226}1227
1228emitWarningSummary(1229InstNotBoundary, TotalRangeNum,1230"of samples are from ranges that are not on instruction boundary.");1231emitWarningSummary(1232UnmatchedRange, TotalRangeNum,1233"of samples are from ranges that do not belong to any functions.");1234emitWarningSummary(1235RangeCrossFunc, TotalRangeNum,1236"of samples are from ranges that do cross function boundaries.");1237emitWarningSummary(1238BogusRange, TotalRangeNum,1239"of samples are from ranges that have range start after or too far from "1240"range end acrossing the unconditinal jmp.");1241}
1242
1243void PerfScriptReader::parsePerfTraces() {1244// Parse perf traces and do aggregation.1245parseAndAggregateTrace();1246if (Binary->isKernel() && !Binary->getIsLoadedByMMap()) {1247exitWithError(1248"Kernel is requested, but no kernel is found in mmap events.");1249}1250
1251emitWarningSummary(NumLeafExternalFrame, NumTotalSample,1252"of samples have leaf external frame in call stack.");1253emitWarningSummary(NumLeadingOutgoingLBR, NumTotalSample,1254"of samples have leading external LBR.");1255
1256// Generate unsymbolized profile.1257warnTruncatedStack();1258warnInvalidRange();1259generateUnsymbolizedProfile();1260AggregatedSamples.clear();1261
1262if (SkipSymbolization)1263writeUnsymbolizedProfile(OutputFilename);1264}
1265
1266SmallVector<CleanupInstaller, 2> PerfScriptReader::TempFileCleanups;1267
1268} // end namespace sampleprof1269} // end namespace llvm1270