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