1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <inttypes.h> 20 #include <stdio.h> 21 22 #include <atomic> 23 #include <functional> 24 #include <memory> 25 #include <thread> 26 #include <unordered_set> 27 #include <vector> 28 29 #include "event_attr.h" 30 #include "record.h" 31 32 namespace simpleperf { 33 34 class MapRecordReader { 35 public: MapRecordReader(const perf_event_attr & attr,uint64_t event_id,bool keep_non_executable_maps)36 MapRecordReader(const perf_event_attr& attr, uint64_t event_id, bool keep_non_executable_maps) 37 : attr_(attr), event_id_(event_id), keep_non_executable_maps_(keep_non_executable_maps) {} 38 Attr()39 const perf_event_attr& Attr() { return attr_; } SetCallback(const std::function<bool (Record *)> & callback)40 void SetCallback(const std::function<bool(Record*)>& callback) { callback_ = callback; } 41 bool ReadKernelMaps(); 42 // Read process maps and all thread names in a process. 43 bool ReadProcessMaps(pid_t pid, uint64_t timestamp); 44 // Read process maps and selected thread names in a process. 45 bool ReadProcessMaps(pid_t pid, const std::unordered_set<pid_t>& tids, uint64_t timestamp); 46 47 private: 48 const perf_event_attr& attr_; 49 const uint64_t event_id_; 50 const bool keep_non_executable_maps_; 51 std::function<bool(Record*)> callback_; 52 }; 53 54 // Create a thread for reading maps while recording. The maps are stored in a temporary file, and 55 // read back after recording. 56 class MapRecordThread { 57 public: 58 MapRecordThread(const MapRecordReader& map_record_reader); 59 ~MapRecordThread(); 60 61 bool Join(); 62 bool ReadMapRecords(const std::function<bool(Record*)>& callback); 63 64 private: 65 // functions running in the map record thread 66 bool RunThread(); 67 bool WriteRecordToFile(Record* record); 68 69 MapRecordReader map_record_reader_; 70 std::unique_ptr<TemporaryFile> tmpfile_; 71 std::unique_ptr<FILE, decltype(&fclose)> fp_; 72 std::thread thread_; 73 std::atomic<bool> early_stop_ = false; 74 std::atomic<bool> thread_result_ = false; 75 }; 76 77 } // namespace simpleperf 78