1 /* 2 * Copyright (c) Facebook, Inc. 3 * Licensed under the Apache License, Version 2.0 (the "License") 4 */ 5 6 #pragma once 7 8 #include <string> 9 #include <unordered_map> 10 #include <vector> 11 12 #include <linux/perf_event.h> 13 #include <sys/types.h> 14 15 #include "BPF.h" 16 #include "PyPerfSampleProcessor.h" 17 #include "PyPerfType.h" 18 19 namespace ebpf { 20 namespace pyperf { 21 22 class PyPerfUtil { 23 public: 24 enum class PyPerfResult : int { 25 SUCCESS = 0, 26 INIT_FAIL, 27 PERF_BUF_OPEN_FAIL, 28 NO_INIT, 29 EVENT_ATTACH_FAIL, 30 EVENT_DETACH_FAIL 31 }; 32 33 // init must be invoked exactly once before invoking profile 34 PyPerfResult init(); 35 36 PyPerfResult profile(int64_t sampleRate, int64_t durationMs, 37 PyPerfSampleProcessor* processor); 38 39 std::unordered_map<int32_t, std::string> getSymbolMapping(); 40 getTotalSamples()41 uint32_t getTotalSamples() const { return totalSamples_; } 42 getLostSamples()43 uint32_t getLostSamples() const { return lostSamples_; } 44 45 private: 46 uint32_t totalSamples_ = 0, lostSamples_ = 0; 47 48 ebpf::BPF bpf_{0, nullptr, false, "", true}; 49 std::vector<PyPerfSample> samples_; 50 bool initCompleted_{false}; 51 52 void handleSample(const void* data, int dataSize); 53 void handleLostSamples(int lostCnt); 54 friend void handleLostSamplesCallback(void*, uint64_t); 55 friend void handleSampleCallback(void*, void*, int); 56 57 std::string getSymbolName(Symbol& sym) const; 58 59 bool tryTargetPid(int pid, PidData& data); 60 }; 61 } // namespace pyperf 62 } // namespace ebpf 63