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