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