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 
18 #include <stdio.h>
19 
20 #include <optional>
21 
22 #include <android-base/logging.h>
23 #include <android-base/properties.h>
24 
25 #include "command.h"
26 #include "event_attr.h"
27 #include "event_fd.h"
28 #include "event_type.h"
29 #include "record_file.h"
30 #include "test_util.h"
31 
32 #if defined(__linux__)
33 
CanSampleRegsFor32BitABI()34 static std::optional<bool> CanSampleRegsFor32BitABI() {
35   std::vector<std::unique_ptr<Workload>> workloads;
36   CreateProcesses(1, &workloads);
37   std::string pid = std::to_string(workloads[0]->GetPid());
38   std::unique_ptr<Command> cmd = CreateCommandInstance("record");
39   TemporaryFile tmpfile;
40   if (!cmd->Run({"-p", pid, "--call-graph", "dwarf,8", "--no-unwind", "-e", "cpu-clock:u",
41                  "--duration", "3", "-o", tmpfile.path})) {
42     return std::nullopt;
43   }
44   auto reader = RecordFileReader::CreateInstance(tmpfile.path);
45   if (!reader) {
46     return std::nullopt;
47   }
48   for (const std::unique_ptr<Record>& record : reader->DataSection()) {
49     if (record->type() == PERF_RECORD_SAMPLE) {
50       auto sample = static_cast<const SampleRecord*>(record.get());
51       if (sample->regs_user_data.abi == PERF_SAMPLE_REGS_ABI_32) {
52         return true;
53       }
54     }
55   }
56   return false;
57 }
58 
IsInNativeAbi()59 std::optional<bool> IsInNativeAbi() {
60   static int in_native_abi = -1;
61   if (in_native_abi == -1) {
62     FILE* fp = popen("uname -m", "re");
63     char buf[40];
64     memset(buf, '\0', sizeof(buf));
65     CHECK_EQ(fgets(buf, sizeof(buf), fp), buf);
66     pclose(fp);
67     std::string s = buf;
68     in_native_abi = 1;
69     if (GetTargetArch() == ARCH_X86_32 || GetTargetArch() == ARCH_X86_64) {
70       if (s.find("86") == std::string::npos) {
71         in_native_abi = 0;
72       }
73     } else if (GetTargetArch() == ARCH_ARM || GetTargetArch() == ARCH_ARM64) {
74       if (s.find("arm") == std::string::npos && s.find("aarch64") == std::string::npos) {
75         in_native_abi = 0;
76       }
77       if (GetTargetArch() == ARCH_ARM) {
78         // If we can't get ARM registers in samples, probably we are running with a 32-bit
79         // translator on 64-bit only CPUs. Then we should make in_native_abi = 0.
80         if (auto result = CanSampleRegsFor32BitABI(); result.has_value()) {
81           in_native_abi = result.value() ? 1 : 0;
82         } else {
83           in_native_abi = 2;
84         }
85       }
86     } else if (GetTargetArch() == ARCH_RISCV64) {
87       if (s.find("riscv") == std::string::npos) {
88         in_native_abi = 0;
89       }
90     }
91   }
92   if (in_native_abi == 2) {
93     return std::nullopt;
94   }
95   return in_native_abi == 1;
96 }
97 
98 // Check if we can get a non-zero instruction event count by monitoring current thread.
HasNonZeroInstructionEventCount()99 static bool HasNonZeroInstructionEventCount() {
100   const simpleperf::EventType* type = simpleperf::FindEventTypeByName("instructions", false);
101   if (type == nullptr) {
102     return false;
103   }
104   perf_event_attr attr = CreateDefaultPerfEventAttr(*type);
105   std::unique_ptr<EventFd> event_fd =
106       EventFd::OpenEventFile(attr, gettid(), -1, nullptr, type->name, false);
107   if (!event_fd) {
108     return false;
109   }
110   // do some cpu work.
111   for (volatile int i = 0; i < 100000; ++i) {
112   }
113   PerfCounter counter;
114   if (event_fd->ReadCounter(&counter)) {
115     return counter.value != 0;
116   }
117   return false;
118 }
119 
IsInEmulator()120 bool IsInEmulator() {
121   std::string fingerprint = android::base::GetProperty("ro.system.build.fingerprint", "");
122   return android::base::StartsWith(fingerprint, "google/sdk_gphone") ||
123          android::base::StartsWith(fingerprint, "google/sdk_gpc") ||
124          android::base::StartsWith(fingerprint, "generic/cf") ||
125          android::base::StartsWith(fingerprint, "generic/aosp_cf");
126 }
127 
HasHardwareCounter()128 bool HasHardwareCounter() {
129   static int has_hw_counter = -1;
130   if (has_hw_counter == -1) {
131     has_hw_counter = 1;
132     auto arch = GetTargetArch();
133 
134     bool in_native_abi = IsInNativeAbi() == std::optional(true);
135 
136     if (arch == ARCH_X86_64 || arch == ARCH_X86_32 || !in_native_abi || IsInEmulator()) {
137       // On x86 and x86_64, or when we are not in native abi, it's likely to run on an emulator or
138       // vm without hardware perf counters. It's hard to enumerate them all. So check the support
139       // at runtime.
140       const simpleperf::EventType* type = simpleperf::FindEventTypeByName("cpu-cycles", false);
141       CHECK(type != nullptr);
142       perf_event_attr attr = CreateDefaultPerfEventAttr(*type);
143       has_hw_counter = IsEventAttrSupported(attr, "cpu-cycles") ? 1 : 0;
144     } else if (arch == ARCH_ARM) {
145       // For arm32 devices, external non-invasive debug signal controls PMU counters. Once it is
146       // disabled for security reason, we always get zero values for PMU counters. And we want to
147       // skip hardware counter tests once we detect it.
148       has_hw_counter &= HasNonZeroInstructionEventCount() ? 1 : 0;
149     }
150   }
151   return has_hw_counter == 1;
152 }
153 
154 #else   // !defined(__linux__)
HasHardwareCounter()155 bool HasHardwareCounter() {
156   return false;
157 }
158 #endif  // !defined(__linux__)
159 
HasPmuCounter()160 bool HasPmuCounter() {
161   static int has_pmu_counter = -1;
162   if (has_pmu_counter == -1) {
163     has_pmu_counter = 0;
164     auto callback = [&](const simpleperf::EventType& event_type) {
165       if (event_type.IsPmuEvent()) {
166         has_pmu_counter = 1;
167         return false;
168       }
169       return true;
170     };
171     simpleperf::EventTypeManager::Instance().ForEachType(callback);
172   }
173   return has_pmu_counter == 1;
174 }
175 
HasTracepointEvents()176 bool HasTracepointEvents() {
177   static int has_tracepoint_events = -1;
178   if (has_tracepoint_events == -1) {
179     has_tracepoint_events = 0;
180     if (const char* dir = GetTraceFsDir(); dir != nullptr) {
181       if (IsDir(std::string(dir) + "/events/sched/sched_switch")) {
182         has_tracepoint_events = 1;
183       }
184     }
185   }
186   return has_tracepoint_events == 1;
187 }
188