blob: a0884340cbee03848e1e2801baff6e283b053676 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Elliott Hughes11e45072011-08-16 17:40:46 -070016
Elliott Hughes42ee1422011-09-06 12:33:32 -070017#include "utils.h"
18
Christopher Ferris943af7d2014-01-16 12:41:46 -080019#include <inttypes.h>
Elliott Hughes92b3b562011-09-08 16:32:26 -070020#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070021#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070022#include <sys/types.h>
23#include <unistd.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070024
Wei Li8991ad02018-09-13 16:43:39 +080025#include <fstream>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Elliott Hughes42ee1422011-09-06 12:33:32 -070027
David Sehr013fd802018-01-11 22:55:24 -080028#include "android-base/file.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080029#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080030#include "android-base/strings.h"
31
Orion Hodsonaeb02232019-06-25 14:18:18 +010032#include "bit_utils.h"
David Sehr1979c642018-04-26 14:41:18 -070033#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070034
Elliott Hughes4ae722a2012-03-13 11:08:51 -070035#if defined(__APPLE__)
David Sehrfa442002016-08-22 18:42:08 -070036#include <crt_externs.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070037#include <sys/syscall.h>
38#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughes4ae722a2012-03-13 11:08:51 -070039#endif
40
Orion Hodsonf2331362018-07-11 15:14:10 +010041#if defined(__BIONIC__)
42// membarrier(2) is only supported for target builds (b/111199492).
43#include <linux/membarrier.h>
44#include <sys/syscall.h>
45#endif
46
Elliott Hughes058a6de2012-05-24 19:13:02 -070047#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080048#include <linux/unistd.h>
David Sehr10db8fe2018-07-18 11:01:20 -070049#include <sys/syscall.h>
Nicolas Geoffray8d6651d2019-07-08 10:03:16 +010050#include <sys/utsname.h>
David Sehr10db8fe2018-07-18 11:01:20 -070051#endif
52
53#if defined(_WIN32)
54#include <windows.h>
55// This include needs to be here due to our coding conventions. Unfortunately
56// it drags in the definition of the dread ERROR macro.
57#ifdef ERROR
58#undef ERROR
59#endif
Elliott Hughese1aee692012-01-17 16:40:10 -080060#endif
61
Elliott Hughes11e45072011-08-16 17:40:46 -070062namespace art {
63
David Sehr013fd802018-01-11 22:55:24 -080064using android::base::ReadFileToString;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080065using android::base::StringPrintf;
66
Orion Hodsonaeb02232019-06-25 14:18:18 +010067#if defined(__arm__)
68
69namespace {
70
71// Bitmap of caches to flush for cacheflush(2). Must be zero for ARM.
72static constexpr int kCacheFlushFlags = 0x0;
73
74// Number of retry attempts when flushing cache ranges.
75static constexpr size_t kMaxFlushAttempts = 4;
76
77int CacheFlush(uintptr_t start, uintptr_t limit) {
78 // The signature of cacheflush(2) seems to vary by source. On ARM the system call wrapper
79 // (bionic/SYSCALLS.TXT) has the form: int cacheflush(long start, long end, long flags);
80 int r = cacheflush(start, limit, kCacheFlushFlags);
81 if (r == -1) {
82 CHECK_NE(errno, EINVAL);
83 }
84 return r;
85}
86
87bool TouchAndFlushCacheLinesWithinPage(uintptr_t start, uintptr_t limit, size_t attempts) {
88 CHECK_LT(start, limit);
89 CHECK_EQ(RoundDown(start, kPageSize), RoundDown(limit - 1, kPageSize)) << "range spans pages";
90 // Declare a volatile variable so the compiler does not elide reads from the page being touched.
91 volatile uint8_t v = 0;
92 for (size_t i = 0; i < attempts; ++i) {
93 // Touch page to maximize chance page is resident.
94 v = *reinterpret_cast<uint8_t*>(start);
95
96 if (LIKELY(CacheFlush(start, limit) == 0)) {
97 return true;
98 }
99 }
100 return false;
101}
102
103} // namespace
104
105bool FlushCpuCaches(void* begin, void* end) {
106 // This method is specialized for ARM as the generic implementation below uses the
107 // __builtin___clear_cache() intrinsic which is declared as void. On ARMv7 flushing the CPU
108 // caches is a privileged operation. The Linux kernel allows these operations to fail when they
109 // trigger a fault (e.g. page not resident). We use a wrapper for the ARM specific cacheflush()
110 // system call to detect the failure and potential erroneous state of the data and instruction
111 // caches.
112 //
113 // The Android bug for this is b/132205399 and there's a similar discussion on
114 // https://reviews.llvm.org/D37788. This is primarily an issue for the dual view JIT where the
115 // pages where code is executed are only ever RX and never RWX. When attempting to invalidate
116 // instruction cache lines in the RX mapping after writing fresh code in the RW mapping, the
117 // page may not be resident (due to memory pressure), and this means that a fault is raised in
118 // the midst of a cacheflush() call and the instruction cache lines are not invalidated and so
119 // have stale code.
120 //
121 // Other architectures fair better for reasons such as:
122 //
123 // (1) stronger coherence between the data and instruction caches.
124 //
125 // (2) fault handling that allows flushing/invalidation to continue after
126 // a missing page has been faulted in.
127
128 uintptr_t start = reinterpret_cast<uintptr_t>(begin);
129 const uintptr_t limit = reinterpret_cast<uintptr_t>(end);
130 if (LIKELY(CacheFlush(start, limit) == 0)) {
131 return true;
132 }
133
134 // A rare failure has occurred implying that part of the range (begin, end] has been swapped
135 // out. Retry flushing but this time grouping cache-line flushes on individual pages and
136 // touching each page before flushing.
137 uintptr_t next_page = RoundUp(start + 1, kPageSize);
138 while (start < limit) {
139 uintptr_t boundary = std::min(next_page, limit);
140 if (!TouchAndFlushCacheLinesWithinPage(start, boundary, kMaxFlushAttempts)) {
141 return false;
142 }
143 start = boundary;
144 next_page += kPageSize;
145 }
146 return true;
147}
148
149#else
150
151bool FlushCpuCaches(void* begin, void* end) {
152 __builtin___clear_cache(reinterpret_cast<char*>(begin), reinterpret_cast<char*>(end));
153 return true;
154}
155
156#endif
157
Nicolas Geoffray8d6651d2019-07-08 10:03:16 +0100158bool CacheOperationsMaySegFault() {
159#if defined(__linux__) && defined(__aarch64__)
160 // Avoid issue on older ARM64 kernels where data cache operations could be classified as writes
161 // and cause segmentation faults. This was fixed in Linux 3.11rc2:
162 //
163 // https://github.com/torvalds/linux/commit/db6f41063cbdb58b14846e600e6bc3f4e4c2e888
164 //
165 // This behaviour means we should avoid the dual view JIT on the device. This is just
166 // an issue when running tests on devices that have an old kernel.
167 static constexpr int kRequiredMajor = 3;
168 static constexpr int kRequiredMinor = 12;
169 struct utsname uts;
170 int major, minor;
171 if (uname(&uts) != 0 ||
172 strcmp(uts.sysname, "Linux") != 0 ||
173 sscanf(uts.release, "%d.%d", &major, &minor) != 2 ||
174 (major < kRequiredMajor || (major == kRequiredMajor && minor < kRequiredMinor))) {
175 return true;
176 }
177#endif
178 return false;
179}
180
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800181pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -0700182#if defined(__APPLE__)
183 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700184 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -0700185 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -0700186#elif defined(__BIONIC__)
187 return gettid();
David Sehr10db8fe2018-07-18 11:01:20 -0700188#elif defined(_WIN32)
189 return static_cast<pid_t>(::GetCurrentThreadId());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800190#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800191 return syscall(__NR_gettid);
192#endif
193}
194
Elliott Hughes289be852012-06-12 13:57:20 -0700195std::string GetThreadName(pid_t tid) {
196 std::string result;
David Sehr10db8fe2018-07-18 11:01:20 -0700197#ifdef _WIN32
198 UNUSED(tid);
199 result = "<unknown>";
200#else
David Sehr013fd802018-01-11 22:55:24 -0800201 // TODO: make this less Linux-specific.
Elliott Hughes289be852012-06-12 13:57:20 -0700202 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700203 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -0700204 } else {
205 result = "<unknown>";
206 }
David Sehr10db8fe2018-07-18 11:01:20 -0700207#endif
Elliott Hughes289be852012-06-12 13:57:20 -0700208 return result;
209}
210
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800211std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700212 // The byte thresholds at which we display amounts. A byte count is displayed
213 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800214 static const int64_t kUnitThresholds[] = {
David Srbeckyde6c7142019-01-09 11:27:40 +0000215 0, // B up to...
216 10*KB, // KB up to...
217 10*MB, // MB up to...
218 10LL*GB // GB from here.
Elliott Hughesc967f782012-04-16 10:23:15 -0700219 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800220 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700221 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800222 const char* negative_str = "";
223 if (byte_count < 0) {
224 negative_str = "-";
225 byte_count = -byte_count;
226 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700227 int i = arraysize(kUnitThresholds);
228 while (--i > 0) {
229 if (byte_count >= kUnitThresholds[i]) {
230 break;
231 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800232 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800233 return StringPrintf("%s%" PRId64 "%s",
234 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800235}
236
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700237void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700238 const char* p = s.data();
239 const char* end = p + s.size();
240 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800241 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700242 ++p;
243 } else {
244 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800245 while (++p != end && *p != separator) {
246 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700247 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700248 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700249 }
250 }
251}
252
Elliott Hughes22869a92012-03-27 14:08:24 -0700253void SetThreadName(const char* thread_name) {
Andreas Gampe7c5acbb2018-09-20 13:54:52 -0700254 bool hasAt = false;
255 bool hasDot = false;
Elliott Hughes22869a92012-03-27 14:08:24 -0700256 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700257 while (*s) {
258 if (*s == '.') {
Andreas Gampe7c5acbb2018-09-20 13:54:52 -0700259 hasDot = true;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700260 } else if (*s == '@') {
Andreas Gampe7c5acbb2018-09-20 13:54:52 -0700261 hasAt = true;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700262 }
263 s++;
264 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700265 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700266 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700267 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700268 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700269 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700270 }
David Sehr10db8fe2018-07-18 11:01:20 -0700271#if defined(__linux__) || defined(_WIN32)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700272 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800273 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700274 strncpy(buf, s, sizeof(buf)-1);
275 buf[sizeof(buf)-1] = '\0';
276 errno = pthread_setname_np(pthread_self(), buf);
277 if (errno != 0) {
278 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
279 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800280#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700281 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700282#endif
283}
284
Brian Carlstrom29212012013-09-12 22:18:30 -0700285void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
286 *utime = *stime = *task_cpu = 0;
David Sehr10db8fe2018-07-18 11:01:20 -0700287#ifdef _WIN32
288 // TODO: implement this.
289 UNUSED(tid);
290 *state = 'S';
291#else
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700292 std::string stats;
David Sehr013fd802018-01-11 22:55:24 -0800293 // TODO: make this less Linux-specific.
Elliott Hughes8a31b502012-04-30 19:36:11 -0700294 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700295 return;
296 }
297 // Skip the command, which may contain spaces.
298 stats = stats.substr(stats.find(')') + 2);
299 // Extract the three fields we care about.
300 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700301 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700302 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700303 *utime = strtoull(fields[11].c_str(), nullptr, 10);
304 *stime = strtoull(fields[12].c_str(), nullptr, 10);
305 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
David Sehr10db8fe2018-07-18 11:01:20 -0700306#endif
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700307}
308
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800309void SleepForever() {
310 while (true) {
311 usleep(1000000);
312 }
313}
314
Wei Li8991ad02018-09-13 16:43:39 +0800315std::string GetProcessStatus(const char* key) {
316 // Build search pattern of key and separator.
317 std::string pattern(key);
318 pattern.push_back(':');
319
320 // Search for status lines starting with pattern.
321 std::ifstream fs("/proc/self/status");
322 std::string line;
323 while (std::getline(fs, line)) {
324 if (strncmp(pattern.c_str(), line.c_str(), pattern.size()) == 0) {
325 // Skip whitespace in matching line (if any).
326 size_t pos = line.find_first_not_of(" \t", pattern.size());
327 if (UNLIKELY(pos == std::string::npos)) {
328 break;
329 }
330 return std::string(line, pos);
331 }
332 }
333 return "<unknown>";
334}
335
Nicolas Geoffrayccb0b5f2019-08-15 18:10:50 +0100336bool IsAddressKnownBackedByFileOrShared(const void* addr) {
337 // We use the Linux pagemap interface for knowing if an address is backed
338 // by a file or is shared. See:
339 // https://www.kernel.org/doc/Documentation/vm/pagemap.txt
340 uintptr_t vmstart = reinterpret_cast<uintptr_t>(AlignDown(addr, kPageSize));
341 off_t index = (vmstart / kPageSize) * sizeof(uint64_t);
342 android::base::unique_fd pagemap(open("/proc/self/pagemap", O_RDONLY | O_CLOEXEC));
343 if (pagemap == -1) {
344 return false;
345 }
346 if (lseek(pagemap, index, SEEK_SET) != index) {
347 return false;
348 }
349 uint64_t flags;
350 if (read(pagemap, &flags, sizeof(uint64_t)) != sizeof(uint64_t)) {
351 return false;
352 }
353 // From https://www.kernel.org/doc/Documentation/vm/pagemap.txt:
354 // * Bit 61 page is file-page or shared-anon (since 3.5)
355 return (flags & (1LL << 61)) != 0;
356}
357
Elliott Hughes42ee1422011-09-06 12:33:32 -0700358} // namespace art