blob: 65d02da84265d7c9f432b135141a598fd7916b43 [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>
50#endif
51
52#if defined(_WIN32)
53#include <windows.h>
54// This include needs to be here due to our coding conventions. Unfortunately
55// it drags in the definition of the dread ERROR macro.
56#ifdef ERROR
57#undef ERROR
58#endif
Elliott Hughese1aee692012-01-17 16:40:10 -080059#endif
60
Elliott Hughes11e45072011-08-16 17:40:46 -070061namespace art {
62
David Sehr013fd802018-01-11 22:55:24 -080063using android::base::ReadFileToString;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080064using android::base::StringPrintf;
65
Orion Hodsonaeb02232019-06-25 14:18:18 +010066#if defined(__arm__)
67
68namespace {
69
70// Bitmap of caches to flush for cacheflush(2). Must be zero for ARM.
71static constexpr int kCacheFlushFlags = 0x0;
72
73// Number of retry attempts when flushing cache ranges.
74static constexpr size_t kMaxFlushAttempts = 4;
75
76int CacheFlush(uintptr_t start, uintptr_t limit) {
77 // The signature of cacheflush(2) seems to vary by source. On ARM the system call wrapper
78 // (bionic/SYSCALLS.TXT) has the form: int cacheflush(long start, long end, long flags);
79 int r = cacheflush(start, limit, kCacheFlushFlags);
80 if (r == -1) {
81 CHECK_NE(errno, EINVAL);
82 }
83 return r;
84}
85
86bool TouchAndFlushCacheLinesWithinPage(uintptr_t start, uintptr_t limit, size_t attempts) {
87 CHECK_LT(start, limit);
88 CHECK_EQ(RoundDown(start, kPageSize), RoundDown(limit - 1, kPageSize)) << "range spans pages";
89 // Declare a volatile variable so the compiler does not elide reads from the page being touched.
90 volatile uint8_t v = 0;
91 for (size_t i = 0; i < attempts; ++i) {
92 // Touch page to maximize chance page is resident.
93 v = *reinterpret_cast<uint8_t*>(start);
94
95 if (LIKELY(CacheFlush(start, limit) == 0)) {
96 return true;
97 }
98 }
99 return false;
100}
101
102} // namespace
103
104bool FlushCpuCaches(void* begin, void* end) {
105 // This method is specialized for ARM as the generic implementation below uses the
106 // __builtin___clear_cache() intrinsic which is declared as void. On ARMv7 flushing the CPU
107 // caches is a privileged operation. The Linux kernel allows these operations to fail when they
108 // trigger a fault (e.g. page not resident). We use a wrapper for the ARM specific cacheflush()
109 // system call to detect the failure and potential erroneous state of the data and instruction
110 // caches.
111 //
112 // The Android bug for this is b/132205399 and there's a similar discussion on
113 // https://reviews.llvm.org/D37788. This is primarily an issue for the dual view JIT where the
114 // pages where code is executed are only ever RX and never RWX. When attempting to invalidate
115 // instruction cache lines in the RX mapping after writing fresh code in the RW mapping, the
116 // page may not be resident (due to memory pressure), and this means that a fault is raised in
117 // the midst of a cacheflush() call and the instruction cache lines are not invalidated and so
118 // have stale code.
119 //
120 // Other architectures fair better for reasons such as:
121 //
122 // (1) stronger coherence between the data and instruction caches.
123 //
124 // (2) fault handling that allows flushing/invalidation to continue after
125 // a missing page has been faulted in.
126
127 uintptr_t start = reinterpret_cast<uintptr_t>(begin);
128 const uintptr_t limit = reinterpret_cast<uintptr_t>(end);
129 if (LIKELY(CacheFlush(start, limit) == 0)) {
130 return true;
131 }
132
133 // A rare failure has occurred implying that part of the range (begin, end] has been swapped
134 // out. Retry flushing but this time grouping cache-line flushes on individual pages and
135 // touching each page before flushing.
136 uintptr_t next_page = RoundUp(start + 1, kPageSize);
137 while (start < limit) {
138 uintptr_t boundary = std::min(next_page, limit);
139 if (!TouchAndFlushCacheLinesWithinPage(start, boundary, kMaxFlushAttempts)) {
140 return false;
141 }
142 start = boundary;
143 next_page += kPageSize;
144 }
145 return true;
146}
147
148#else
149
150bool FlushCpuCaches(void* begin, void* end) {
151 __builtin___clear_cache(reinterpret_cast<char*>(begin), reinterpret_cast<char*>(end));
152 return true;
153}
154
155#endif
156
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800157pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -0700158#if defined(__APPLE__)
159 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700160 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -0700161 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -0700162#elif defined(__BIONIC__)
163 return gettid();
David Sehr10db8fe2018-07-18 11:01:20 -0700164#elif defined(_WIN32)
165 return static_cast<pid_t>(::GetCurrentThreadId());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800166#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -0800167 return syscall(__NR_gettid);
168#endif
169}
170
Elliott Hughes289be852012-06-12 13:57:20 -0700171std::string GetThreadName(pid_t tid) {
172 std::string result;
David Sehr10db8fe2018-07-18 11:01:20 -0700173#ifdef _WIN32
174 UNUSED(tid);
175 result = "<unknown>";
176#else
David Sehr013fd802018-01-11 22:55:24 -0800177 // TODO: make this less Linux-specific.
Elliott Hughes289be852012-06-12 13:57:20 -0700178 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700179 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -0700180 } else {
181 result = "<unknown>";
182 }
David Sehr10db8fe2018-07-18 11:01:20 -0700183#endif
Elliott Hughes289be852012-06-12 13:57:20 -0700184 return result;
185}
186
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800187std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700188 // The byte thresholds at which we display amounts. A byte count is displayed
189 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800190 static const int64_t kUnitThresholds[] = {
David Srbeckyde6c7142019-01-09 11:27:40 +0000191 0, // B up to...
192 10*KB, // KB up to...
193 10*MB, // MB up to...
194 10LL*GB // GB from here.
Elliott Hughesc967f782012-04-16 10:23:15 -0700195 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800196 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700197 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800198 const char* negative_str = "";
199 if (byte_count < 0) {
200 negative_str = "-";
201 byte_count = -byte_count;
202 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700203 int i = arraysize(kUnitThresholds);
204 while (--i > 0) {
205 if (byte_count >= kUnitThresholds[i]) {
206 break;
207 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800208 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800209 return StringPrintf("%s%" PRId64 "%s",
210 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800211}
212
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700213void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700214 const char* p = s.data();
215 const char* end = p + s.size();
216 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800217 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700218 ++p;
219 } else {
220 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800221 while (++p != end && *p != separator) {
222 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700223 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700224 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700225 }
226 }
227}
228
Elliott Hughes22869a92012-03-27 14:08:24 -0700229void SetThreadName(const char* thread_name) {
Andreas Gampe7c5acbb2018-09-20 13:54:52 -0700230 bool hasAt = false;
231 bool hasDot = false;
Elliott Hughes22869a92012-03-27 14:08:24 -0700232 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700233 while (*s) {
234 if (*s == '.') {
Andreas Gampe7c5acbb2018-09-20 13:54:52 -0700235 hasDot = true;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700236 } else if (*s == '@') {
Andreas Gampe7c5acbb2018-09-20 13:54:52 -0700237 hasAt = true;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700238 }
239 s++;
240 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700241 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700242 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700243 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700244 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700245 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700246 }
David Sehr10db8fe2018-07-18 11:01:20 -0700247#if defined(__linux__) || defined(_WIN32)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700248 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800249 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700250 strncpy(buf, s, sizeof(buf)-1);
251 buf[sizeof(buf)-1] = '\0';
252 errno = pthread_setname_np(pthread_self(), buf);
253 if (errno != 0) {
254 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
255 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800256#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700257 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700258#endif
259}
260
Brian Carlstrom29212012013-09-12 22:18:30 -0700261void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
262 *utime = *stime = *task_cpu = 0;
David Sehr10db8fe2018-07-18 11:01:20 -0700263#ifdef _WIN32
264 // TODO: implement this.
265 UNUSED(tid);
266 *state = 'S';
267#else
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700268 std::string stats;
David Sehr013fd802018-01-11 22:55:24 -0800269 // TODO: make this less Linux-specific.
Elliott Hughes8a31b502012-04-30 19:36:11 -0700270 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700271 return;
272 }
273 // Skip the command, which may contain spaces.
274 stats = stats.substr(stats.find(')') + 2);
275 // Extract the three fields we care about.
276 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700277 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700278 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700279 *utime = strtoull(fields[11].c_str(), nullptr, 10);
280 *stime = strtoull(fields[12].c_str(), nullptr, 10);
281 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
David Sehr10db8fe2018-07-18 11:01:20 -0700282#endif
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700283}
284
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800285void SleepForever() {
286 while (true) {
287 usleep(1000000);
288 }
289}
290
Wei Li8991ad02018-09-13 16:43:39 +0800291std::string GetProcessStatus(const char* key) {
292 // Build search pattern of key and separator.
293 std::string pattern(key);
294 pattern.push_back(':');
295
296 // Search for status lines starting with pattern.
297 std::ifstream fs("/proc/self/status");
298 std::string line;
299 while (std::getline(fs, line)) {
300 if (strncmp(pattern.c_str(), line.c_str(), pattern.size()) == 0) {
301 // Skip whitespace in matching line (if any).
302 size_t pos = line.find_first_not_of(" \t", pattern.size());
303 if (UNLIKELY(pos == std::string::npos)) {
304 break;
305 }
306 return std::string(line, pos);
307 }
308 }
309 return "<unknown>";
310}
311
Elliott Hughes42ee1422011-09-06 12:33:32 -0700312} // namespace art