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