1 /*
2 * Copyright (C) 2011 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 "utils.h"
18
19 #include <dirent.h>
20 #include <inttypes.h>
21 #include <pthread.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25
26 #include <fstream>
27 #include <memory>
28 #include <string>
29
30 #include "android-base/file.h"
31 #include "android-base/stringprintf.h"
32 #include "android-base/strings.h"
33
34 #include "base/stl_util.h"
35 #include "bit_utils.h"
36 #include "os.h"
37
38 #if defined(__APPLE__)
39 #include <crt_externs.h>
40 // NOLINTNEXTLINE - inclusion of syscall is dependent on arch
41 #include <sys/syscall.h>
42 #include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
43 #endif
44
45 #if defined(__BIONIC__)
46 // membarrier(2) is only supported for target builds (b/111199492).
47 #include <linux/membarrier.h>
48 // NOLINTNEXTLINE - inclusion of syscall is dependent on arch
49 #include <sys/syscall.h>
50 #endif
51
52 #if defined(__linux__)
53 #include <linux/unistd.h>
54 // NOLINTNEXTLINE - inclusion of syscall is dependent on arch
55 #include <sys/syscall.h>
56 #endif
57
58 #if defined(_WIN32)
59 #include <windows.h>
60 // This include needs to be here due to our coding conventions. Unfortunately
61 // it drags in the definition of the dread ERROR macro.
62 #ifdef ERROR
63 #undef ERROR
64 #endif
65 #endif
66
67 namespace art {
68
69 using android::base::ReadFileToString; // NOLINT - ReadFileToString is actually used
70 using android::base::StringPrintf;
71
72 #if defined(__arm__)
73
74 namespace {
75
76 // Bitmap of caches to flush for cacheflush(2). Must be zero for ARM.
77 static constexpr int kCacheFlushFlags = 0x0;
78
79 // Number of retry attempts when flushing cache ranges.
80 static constexpr size_t kMaxFlushAttempts = 4;
81
CacheFlush(uintptr_t start,uintptr_t limit)82 int CacheFlush(uintptr_t start, uintptr_t limit) {
83 // The signature of cacheflush(2) seems to vary by source. On ARM the system call wrapper
84 // (bionic/SYSCALLS.TXT) has the form: int cacheflush(long start, long end, long flags);
85 int r = cacheflush(start, limit, kCacheFlushFlags);
86 if (r == -1) {
87 CHECK_NE(errno, EINVAL);
88 }
89 return r;
90 }
91
TouchAndFlushCacheLinesWithinPage(uintptr_t start,uintptr_t limit,size_t attempts)92 bool TouchAndFlushCacheLinesWithinPage(uintptr_t start, uintptr_t limit, size_t attempts) {
93 CHECK_LT(start, limit);
94 CHECK_EQ(RoundDown(start, kPageSize), RoundDown(limit - 1, kPageSize)) << "range spans pages";
95 // Declare a volatile variable so the compiler does not elide reads from the page being touched.
96 [[maybe_unused]] volatile uint8_t v = 0;
97 for (size_t i = 0; i < attempts; ++i) {
98 // Touch page to maximize chance page is resident.
99 v = *reinterpret_cast<uint8_t*>(start);
100
101 if (LIKELY(CacheFlush(start, limit) == 0)) {
102 return true;
103 }
104 }
105 return false;
106 }
107
108 } // namespace
109
FlushCpuCaches(void * begin,void * end)110 bool FlushCpuCaches(void* begin, void* end) {
111 // This method is specialized for ARM as the generic implementation below uses the
112 // __builtin___clear_cache() intrinsic which is declared as void. On ARMv7 flushing the CPU
113 // caches is a privileged operation. The Linux kernel allows these operations to fail when they
114 // trigger a fault (e.g. page not resident). We use a wrapper for the ARM specific cacheflush()
115 // system call to detect the failure and potential erroneous state of the data and instruction
116 // caches.
117 //
118 // The Android bug for this is b/132205399 and there's a similar discussion on
119 // https://reviews.llvm.org/D37788. This is primarily an issue for the dual view JIT where the
120 // pages where code is executed are only ever RX and never RWX. When attempting to invalidate
121 // instruction cache lines in the RX mapping after writing fresh code in the RW mapping, the
122 // page may not be resident (due to memory pressure), and this means that a fault is raised in
123 // the midst of a cacheflush() call and the instruction cache lines are not invalidated and so
124 // have stale code.
125 //
126 // Other architectures fair better for reasons such as:
127 //
128 // (1) stronger coherence between the data and instruction caches.
129 //
130 // (2) fault handling that allows flushing/invalidation to continue after
131 // a missing page has been faulted in.
132
133 uintptr_t start = reinterpret_cast<uintptr_t>(begin);
134 const uintptr_t limit = reinterpret_cast<uintptr_t>(end);
135 if (LIKELY(CacheFlush(start, limit) == 0)) {
136 return true;
137 }
138
139 // A rare failure has occurred implying that part of the range (begin, end] has been swapped
140 // out. Retry flushing but this time grouping cache-line flushes on individual pages and
141 // touching each page before flushing.
142 uintptr_t next_page = RoundUp(start + 1, kPageSize);
143 while (start < limit) {
144 uintptr_t boundary = std::min(next_page, limit);
145 if (!TouchAndFlushCacheLinesWithinPage(start, boundary, kMaxFlushAttempts)) {
146 return false;
147 }
148 start = boundary;
149 next_page += kPageSize;
150 }
151 return true;
152 }
153
154 #else
155
FlushCpuCaches(void * begin,void * end)156 bool FlushCpuCaches(void* begin, void* end) {
157 __builtin___clear_cache(reinterpret_cast<char*>(begin), reinterpret_cast<char*>(end));
158 return true;
159 }
160
161 #endif
162
163 #if defined(__linux__)
IsKernelVersionAtLeast(int reqd_major,int reqd_minor)164 bool IsKernelVersionAtLeast(int reqd_major, int reqd_minor) {
165 struct utsname uts;
166 int major, minor;
167 CHECK_EQ(uname(&uts), 0);
168 CHECK_EQ(strcmp(uts.sysname, "Linux"), 0);
169 CHECK_EQ(sscanf(uts.release, "%d.%d:", &major, &minor), 2);
170 return major > reqd_major || (major == reqd_major && minor >= reqd_minor);
171 }
172 #endif
173
CacheOperationsMaySegFault()174 bool CacheOperationsMaySegFault() {
175 #if defined(__linux__) && defined(__aarch64__)
176 // Avoid issue on older ARM64 kernels where data cache operations could be classified as writes
177 // and cause segmentation faults. This was fixed in Linux 3.11rc2:
178 //
179 // https://github.com/torvalds/linux/commit/db6f41063cbdb58b14846e600e6bc3f4e4c2e888
180 //
181 // This behaviour means we should avoid the dual view JIT on the device. This is just
182 // an issue when running tests on devices that have an old kernel.
183 return !IsKernelVersionAtLeast(3, 12);
184 #else
185 return false;
186 #endif
187 }
188
GetTid()189 uint32_t GetTid() {
190 #if defined(__APPLE__)
191 uint64_t owner;
192 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
193 return owner;
194 #elif defined(__BIONIC__)
195 return gettid();
196 #elif defined(_WIN32)
197 return static_cast<pid_t>(::GetCurrentThreadId());
198 #else
199 return syscall(__NR_gettid);
200 #endif
201 }
202
GetThreadName(pid_t tid)203 std::string GetThreadName(pid_t tid) {
204 std::string result;
205 #ifdef _WIN32
206 UNUSED(tid);
207 result = "<unknown>";
208 #else
209 // TODO: make this less Linux-specific.
210 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
211 result.resize(result.size() - 1); // Lose the trailing '\n'.
212 } else {
213 result = "<unknown>";
214 }
215 #endif
216 return result;
217 }
218
PrettySize(uint64_t byte_count)219 std::string PrettySize(uint64_t byte_count) {
220 // The byte thresholds at which we display amounts. A byte count is displayed
221 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
222 static const uint64_t kUnitThresholds[] = {
223 0, // B up to...
224 10*KB, // KB up to...
225 10*MB, // MB up to...
226 10ULL*GB // GB from here.
227 };
228 static const uint64_t kBytesPerUnit[] = { 1, KB, MB, GB };
229 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
230 int i = arraysize(kUnitThresholds);
231 while (--i > 0) {
232 if (byte_count >= kUnitThresholds[i]) {
233 break;
234 }
235 }
236 return StringPrintf("%" PRIu64 "%s",
237 byte_count / kBytesPerUnit[i], kUnitStrings[i]);
238 }
239
240 template <typename StrIn, typename Str>
Split(const StrIn & s,char separator,std::vector<Str> * out_result)241 void Split(const StrIn& s, char separator, std::vector<Str>* out_result) {
242 auto split = SplitString(std::string_view(s), separator);
243 for (std::string_view p : split) {
244 if (p.empty()) {
245 continue;
246 }
247 out_result->push_back(Str(p));
248 }
249 }
250
251 template void Split(const char *const& s, char separator, std::vector<std::string>* out_result);
252 template void Split(const std::string& s, char separator, std::vector<std::string>* out_result);
253 template void Split(const char *const& s, char separator, std::vector<std::string_view>* out_result);
254 template void Split(const std::string_view& s,
255 char separator,
256 std::vector<std::string_view>* out_result);
257 template void Split(const std::string_view& s,
258 char separator,
259 std::vector<std::string>* out_result);
260
261 template <typename Str>
Split(const Str & s,char separator,size_t len,Str * out_result)262 void Split(const Str& s, char separator, size_t len, Str* out_result) {
263 Str* last = out_result + len;
264 auto split = SplitString(std::string_view(s), separator);
265 for (std::string_view p : split) {
266 if (p.empty()) {
267 continue;
268 }
269 if (out_result == last) {
270 return;
271 }
272 *out_result++ = Str(p);
273 }
274 }
275
276 template void Split(const std::string& s, char separator, size_t len, std::string* out_result);
277 template void Split(const std::string_view& s,
278 char separator,
279 size_t len,
280 std::string_view* out_result);
281
SetThreadName(const char * thread_name)282 void SetThreadName(const char* thread_name) {
283 bool hasAt = false;
284 bool hasDot = false;
285 const char* s = thread_name;
286 while (*s) {
287 if (*s == '.') {
288 hasDot = true;
289 } else if (*s == '@') {
290 hasAt = true;
291 }
292 s++;
293 }
294 int len = s - thread_name;
295 if (len < 15 || hasAt || !hasDot) {
296 s = thread_name;
297 } else {
298 s = thread_name + len - 15;
299 }
300 #if defined(__linux__) || defined(_WIN32)
301 // pthread_setname_np fails rather than truncating long strings.
302 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
303 strncpy(buf, s, sizeof(buf)-1);
304 buf[sizeof(buf)-1] = '\0';
305 errno = pthread_setname_np(pthread_self(), buf);
306 if (errno != 0) {
307 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
308 }
309 #else // __APPLE__
310 pthread_setname_np(thread_name);
311 #endif
312 }
313
GetTaskStats(pid_t tid,char * state,int * utime,int * stime,int * task_cpu)314 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
315 *utime = *stime = *task_cpu = 0;
316 #ifdef _WIN32
317 // TODO: implement this.
318 UNUSED(tid);
319 *state = 'S';
320 #else
321 std::string stats;
322 // TODO: make this less Linux-specific.
323 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
324 return;
325 }
326 // Skip the command, which may contain spaces.
327 stats = stats.substr(stats.find(')') + 2);
328 // Extract the three fields we care about.
329 std::vector<std::string> fields;
330 Split(stats, ' ', &fields);
331 *state = fields[0][0];
332 *utime = strtoull(fields[11].c_str(), nullptr, 10);
333 *stime = strtoull(fields[12].c_str(), nullptr, 10);
334 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
335 #endif
336 }
337
SleepForever()338 void SleepForever() {
339 while (true) {
340 sleep(100000000);
341 }
342 }
343
GetProcessStatus(const char * key)344 std::string GetProcessStatus(const char* key) {
345 // Build search pattern of key and separator.
346 std::string pattern(key);
347 pattern.push_back(':');
348
349 // Search for status lines starting with pattern.
350 std::ifstream fs("/proc/self/status");
351 std::string line;
352 while (std::getline(fs, line)) {
353 if (strncmp(pattern.c_str(), line.c_str(), pattern.size()) == 0) {
354 // Skip whitespace in matching line (if any).
355 size_t pos = line.find_first_not_of(" \t", pattern.size());
356 if (UNLIKELY(pos == std::string::npos)) {
357 break;
358 }
359 return std::string(line, pos);
360 }
361 }
362 return "<unknown>";
363 }
364
IsAddressKnownBackedByFileOrShared(const void * addr)365 bool IsAddressKnownBackedByFileOrShared(const void* addr) {
366 // We use the Linux pagemap interface for knowing if an address is backed
367 // by a file or is shared. See:
368 // https://www.kernel.org/doc/Documentation/vm/pagemap.txt
369 uintptr_t vmstart = reinterpret_cast<uintptr_t>(AlignDown(addr, kPageSize));
370 off_t index = (vmstart / kPageSize) * sizeof(uint64_t);
371 android::base::unique_fd pagemap(open("/proc/self/pagemap", O_RDONLY | O_CLOEXEC));
372 if (pagemap == -1) {
373 return false;
374 }
375 if (lseek(pagemap, index, SEEK_SET) != index) {
376 return false;
377 }
378 uint64_t flags;
379 if (read(pagemap, &flags, sizeof(uint64_t)) != sizeof(uint64_t)) {
380 return false;
381 }
382 // From https://www.kernel.org/doc/Documentation/vm/pagemap.txt:
383 // * Bit 61 page is file-page or shared-anon (since 3.5)
384 return (flags & (1LL << 61)) != 0;
385 }
386
GetTaskCount()387 int GetTaskCount() {
388 DIR* directory = opendir("/proc/self/task");
389 if (directory == nullptr) {
390 return -1;
391 }
392
393 uint32_t count = 0;
394 struct dirent* entry = nullptr;
395 while ((entry = readdir(directory)) != nullptr) {
396 if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0)) {
397 continue;
398 }
399 ++count;
400 }
401 closedir(directory);
402 return count;
403 }
404
405 } // namespace art
406