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 #include "MapRecordReader.h"
18
19 #include <optional>
20
21 #include <gtest/gtest.h>
22
23 #include "environment.h"
24 #include "event_attr.h"
25 #include "event_type.h"
26
27 using namespace simpleperf;
28
29 class MapRecordReaderTest : public ::testing::Test {
30 protected:
CreateMapRecordReader()31 bool CreateMapRecordReader() {
32 const EventType* event_type = FindEventTypeByName("cpu-clock");
33 if (event_type == nullptr) {
34 return false;
35 }
36 attr_ = CreateDefaultPerfEventAttr(*event_type);
37 reader_.emplace(attr_, 0, true);
38 reader_->SetCallback([this](Record* r) { return CountRecord(r); });
39 return true;
40 }
41
CountRecord(Record * r)42 bool CountRecord(Record* r) {
43 if (r->type() == PERF_RECORD_MMAP || r->type() == PERF_RECORD_MMAP2) {
44 map_record_count_++;
45 } else if (r->type() == PERF_RECORD_COMM) {
46 comm_record_count_++;
47 }
48 return true;
49 }
50
51 perf_event_attr attr_;
52 std::optional<MapRecordReader> reader_;
53 size_t map_record_count_ = 0;
54 size_t comm_record_count_ = 0;
55 };
56
TEST_F(MapRecordReaderTest,ReadKernelMaps)57 TEST_F(MapRecordReaderTest, ReadKernelMaps) {
58 ASSERT_TRUE(CreateMapRecordReader());
59 ASSERT_TRUE(reader_->ReadKernelMaps());
60 ASSERT_GT(map_record_count_, 0);
61 }
62
TEST_F(MapRecordReaderTest,ReadProcessMaps)63 TEST_F(MapRecordReaderTest, ReadProcessMaps) {
64 ASSERT_TRUE(CreateMapRecordReader());
65 ASSERT_TRUE(reader_->ReadProcessMaps(getpid(), 0));
66 ASSERT_GT(map_record_count_, 0);
67 ASSERT_GT(comm_record_count_, 0);
68 }
69
TEST_F(MapRecordReaderTest,MapRecordThread)70 TEST_F(MapRecordReaderTest, MapRecordThread) {
71 #ifdef __ANDROID__
72 std::string tmpdir = "/data/local/tmp";
73 #else
74 std::string tmpdir = "/tmp";
75 #endif
76 auto scoped_temp_files = ScopedTempFiles::Create(tmpdir);
77 ASSERT_TRUE(scoped_temp_files);
78 ASSERT_TRUE(CreateMapRecordReader());
79 MapRecordThread thread(*reader_);
80 ASSERT_TRUE(thread.Join());
81 ASSERT_TRUE(thread.ReadMapRecords([this](Record* r) { return CountRecord(r); }));
82 ASSERT_GT(map_record_count_, 0);
83 ASSERT_GT(comm_record_count_, 0);
84 }
85