blob: 7234ec0951aa93c85fcb764376f1cf5cf0cf91f3 [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/syscall.h>
23#include <sys/types.h>
Brian Carlstrom4cf5e572014-02-25 11:47:48 -080024#include <sys/wait.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070025#include <unistd.h>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Elliott Hughes42ee1422011-09-06 12:33:32 -070027
Brian Carlstrom6449c622014-02-10 23:48:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "dex_file-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070031#include "mirror/art_field-inl.h"
32#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070033#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/object-inl.h"
36#include "mirror/object_array-inl.h"
37#include "mirror/string.h"
buzbeec143c552011-08-20 17:38:58 -070038#include "os.h"
Kenny Root067d20f2014-03-05 14:57:21 -080039#include "scoped_thread_state_change.h"
Ian Rogersa6724902013-09-23 09:23:37 -070040#include "utf-inl.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070041
Elliott Hughesad6c9c32012-01-19 17:39:12 -080042#if !defined(HAVE_POSIX_CLOCKS)
43#include <sys/time.h>
44#endif
45
Elliott Hughesdcc24742011-09-07 14:02:44 -070046#if defined(HAVE_PRCTL)
47#include <sys/prctl.h>
48#endif
49
Elliott Hughes4ae722a2012-03-13 11:08:51 -070050#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070051#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070052#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070053#endif
54
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070055#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070056
Elliott Hughes058a6de2012-05-24 19:13:02 -070057#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080058#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080059#endif
60
Elliott Hughes11e45072011-08-16 17:40:46 -070061namespace art {
62
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080063pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070064#if defined(__APPLE__)
65 uint64_t owner;
66 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
67 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070068#elif defined(__BIONIC__)
69 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080070#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080071 return syscall(__NR_gettid);
72#endif
73}
74
Elliott Hughes289be852012-06-12 13:57:20 -070075std::string GetThreadName(pid_t tid) {
76 std::string result;
77 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070078 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070079 } else {
80 result = "<unknown>";
81 }
82 return result;
83}
84
Elliott Hughes6d3fc562014-08-27 11:47:01 -070085void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070086#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070087 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070088 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070089
90 // Check whether stack_addr is the base or end of the stack.
91 // (On Mac OS 10.7, it's the end.)
92 int stack_variable;
93 if (stack_addr > &stack_variable) {
Ian Rogers13735952014-10-08 12:43:28 -070094 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070095 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070096 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070097 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070098
99 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
100 pthread_attr_t attributes;
101 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
102 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
103 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700104#else
105 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700106 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700107 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700108 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700109 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700110
111#if defined(__GLIBC__)
112 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
113 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
114 // will be broken because we'll die long before we get close to 2GB.
115 bool is_main_thread = (::art::GetTid() == getpid());
116 if (is_main_thread) {
117 rlimit stack_limit;
118 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
119 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
120 }
121 if (stack_limit.rlim_cur == RLIM_INFINITY) {
122 size_t old_stack_size = *stack_size;
123
124 // Use the kernel default limit as our size, and adjust the base to match.
125 *stack_size = 8 * MB;
126 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
127
128 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
129 << " to " << PrettySize(*stack_size)
130 << " with base " << *stack_base;
131 }
132 }
133#endif
134
Elliott Hughese1884192012-04-23 12:38:15 -0700135#endif
136}
137
Elliott Hughesd92bec42011-09-02 17:04:36 -0700138bool ReadFileToString(const std::string& file_name, std::string* result) {
Ian Rogers700a4022014-05-19 16:49:03 -0700139 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800140 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700141 return false;
142 }
buzbeec143c552011-08-20 17:38:58 -0700143
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700144 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700145 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800146 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700147 if (n == -1) {
148 return false;
buzbeec143c552011-08-20 17:38:58 -0700149 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700150 if (n == 0) {
151 return true;
152 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700153 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700154 }
buzbeec143c552011-08-20 17:38:58 -0700155}
156
Elliott Hughese27955c2011-08-26 15:21:24 -0700157std::string GetIsoDate() {
158 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700159 tm tmbuf;
160 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700161 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
162 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
163 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
164}
165
Elliott Hughes7162ad92011-10-27 14:08:42 -0700166uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800167#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700168 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700169 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700170 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800171#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700172 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800173 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700174 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800175#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700176}
177
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800178uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800179#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700180 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800181 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700182 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800183#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700184 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800185 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700186 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800187#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800188}
189
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700190uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800191#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700192 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700193 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700194 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800195#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700196 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800197 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700198 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800199#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700200}
201
Elliott Hughes0512f022012-03-15 22:10:52 -0700202uint64_t ThreadCpuNanoTime() {
203#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700204 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700205 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700206 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0512f022012-03-15 22:10:52 -0700207#else
208 UNIMPLEMENTED(WARNING);
209 return -1;
210#endif
211}
212
Ian Rogers56edc432013-01-18 16:51:51 -0800213void NanoSleep(uint64_t ns) {
214 timespec tm;
215 tm.tv_sec = 0;
216 tm.tv_nsec = ns;
217 nanosleep(&tm, NULL);
218}
219
Brian Carlstrombcc29262012-11-02 11:36:03 -0700220void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
221 int64_t endSec;
222
223 if (absolute) {
224#if !defined(__APPLE__)
225 clock_gettime(clock, ts);
226#else
227 UNUSED(clock);
228 timeval tv;
229 gettimeofday(&tv, NULL);
230 ts->tv_sec = tv.tv_sec;
231 ts->tv_nsec = tv.tv_usec * 1000;
232#endif
233 } else {
234 ts->tv_sec = 0;
235 ts->tv_nsec = 0;
236 }
237 endSec = ts->tv_sec + ms / 1000;
238 if (UNLIKELY(endSec >= 0x7fffffff)) {
239 std::ostringstream ss;
240 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
241 endSec = 0x7ffffffe;
242 }
243 ts->tv_sec = endSec;
244 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
245
246 // Catch rollover.
247 if (ts->tv_nsec >= 1000000000L) {
248 ts->tv_sec++;
249 ts->tv_nsec -= 1000000000L;
250 }
251}
252
Ian Rogersef7d42f2014-01-06 12:55:46 -0800253std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700254 if (java_descriptor == NULL) {
255 return "null";
256 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700257 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700258}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700259
Ian Rogersef7d42f2014-01-06 12:55:46 -0800260std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800261 if (klass == NULL) {
262 return "null";
263 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700264 std::string temp;
265 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800266}
267
Ian Rogers1ff3c982014-08-12 02:30:58 -0700268std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700269 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700270 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700271 size_t dim = 0;
272 while (*c == '[') {
273 dim++;
274 c++;
275 }
276
277 // Reference or primitive?
278 if (*c == 'L') {
279 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700280 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700281 } else {
282 // "[[B" -> "byte[][]".
283 // To make life easier, we make primitives look like unqualified
284 // reference types.
285 switch (*c) {
286 case 'B': c = "byte;"; break;
287 case 'C': c = "char;"; break;
288 case 'D': c = "double;"; break;
289 case 'F': c = "float;"; break;
290 case 'I': c = "int;"; break;
291 case 'J': c = "long;"; break;
292 case 'S': c = "short;"; break;
293 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700294 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700295 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700296 }
297 }
298
299 // At this point, 'c' is a string of the form "fully/qualified/Type;"
300 // or "primitive;". Rewrite the type with '.' instead of '/':
301 std::string result;
302 const char* p = c;
303 while (*p != ';') {
304 char ch = *p++;
305 if (ch == '/') {
306 ch = '.';
307 }
308 result.push_back(ch);
309 }
310 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700311 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700312 result += "[]";
313 }
314 return result;
315}
316
Ian Rogersef7d42f2014-01-06 12:55:46 -0800317std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700318 if (f == NULL) {
319 return "null";
320 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700321 std::string result;
322 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700323 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700324 result += ' ';
325 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800326 std::string temp;
327 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700328 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700329 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700330 return result;
331}
332
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700333std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800334 if (field_idx >= dex_file.NumFieldIds()) {
335 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
336 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700337 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
338 std::string result;
339 if (with_type) {
340 result += dex_file.GetFieldTypeDescriptor(field_id);
341 result += ' ';
342 }
343 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
344 result += '.';
345 result += dex_file.GetFieldName(field_id);
346 return result;
347}
348
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700349std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800350 if (type_idx >= dex_file.NumTypeIds()) {
351 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
352 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700353 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700354 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700355}
356
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700357std::string PrettyArguments(const char* signature) {
358 std::string result;
359 result += '(';
360 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700361 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700362 while (*signature != ')') {
363 size_t argument_length = 0;
364 while (signature[argument_length] == '[') {
365 ++argument_length;
366 }
367 if (signature[argument_length] == 'L') {
368 argument_length = (strchr(signature, ';') - signature + 1);
369 } else {
370 ++argument_length;
371 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700372 {
373 std::string argument_descriptor(signature, argument_length);
374 result += PrettyDescriptor(argument_descriptor.c_str());
375 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700376 if (signature[argument_length] != ')') {
377 result += ", ";
378 }
379 signature += argument_length;
380 }
381 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700382 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700383 result += ')';
384 return result;
385}
386
387std::string PrettyReturnType(const char* signature) {
388 const char* return_type = strchr(signature, ')');
389 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700390 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700391 return PrettyDescriptor(return_type);
392}
393
Ian Rogersef7d42f2014-01-06 12:55:46 -0800394std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800395 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700396 return "null";
397 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700398 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700399 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700400 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800401 if (UNLIKELY(m->IsFastNative())) {
402 result += "!";
403 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700404 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700405 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700406 std::string sig_as_string(signature.ToString());
407 if (signature == Signature::NoSignature()) {
408 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700409 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700410 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
411 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700412 }
413 return result;
414}
415
Ian Rogers0571d352011-11-03 19:51:38 -0700416std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800417 if (method_idx >= dex_file.NumMethodIds()) {
418 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
419 }
Ian Rogers0571d352011-11-03 19:51:38 -0700420 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
421 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
422 result += '.';
423 result += dex_file.GetMethodName(method_id);
424 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700425 const Signature signature = dex_file.GetMethodSignature(method_id);
426 std::string sig_as_string(signature.ToString());
427 if (signature == Signature::NoSignature()) {
428 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700429 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700430 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
431 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700432 }
433 return result;
434}
435
Ian Rogersef7d42f2014-01-06 12:55:46 -0800436std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700437 if (obj == NULL) {
438 return "null";
439 }
440 if (obj->GetClass() == NULL) {
441 return "(raw)";
442 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700443 std::string temp;
444 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700445 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700446 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700447 }
448 return result;
449}
450
Ian Rogersef7d42f2014-01-06 12:55:46 -0800451std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700452 if (c == NULL) {
453 return "null";
454 }
455 std::string result;
456 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800457 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700458 result += ">";
459 return result;
460}
461
Ian Rogersef7d42f2014-01-06 12:55:46 -0800462std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700463 if (c == NULL) {
464 return "null";
465 }
466 std::string result;
467 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800468 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700469 result += ",";
470 result += PrettyTypeOf(c->GetClassLoader());
471 // TODO: add an identifying hash value for the loader
472 result += ">";
473 return result;
474}
475
Andreas Gampec0d82292014-09-23 10:38:30 -0700476std::string PrettyJavaAccessFlags(uint32_t access_flags) {
477 std::string result;
478 if ((access_flags & kAccPublic) != 0) {
479 result += "public ";
480 }
481 if ((access_flags & kAccProtected) != 0) {
482 result += "protected ";
483 }
484 if ((access_flags & kAccPrivate) != 0) {
485 result += "private ";
486 }
487 if ((access_flags & kAccFinal) != 0) {
488 result += "final ";
489 }
490 if ((access_flags & kAccStatic) != 0) {
491 result += "static ";
492 }
493 if ((access_flags & kAccTransient) != 0) {
494 result += "transient ";
495 }
496 if ((access_flags & kAccVolatile) != 0) {
497 result += "volatile ";
498 }
499 if ((access_flags & kAccSynchronized) != 0) {
500 result += "synchronized ";
501 }
502 return result;
503}
504
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800505std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700506 // The byte thresholds at which we display amounts. A byte count is displayed
507 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800508 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700509 0, // B up to...
510 3*1024, // KB up to...
511 2*1024*1024, // MB up to...
512 1024*1024*1024 // GB from here.
513 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800514 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700515 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800516 const char* negative_str = "";
517 if (byte_count < 0) {
518 negative_str = "-";
519 byte_count = -byte_count;
520 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700521 int i = arraysize(kUnitThresholds);
522 while (--i > 0) {
523 if (byte_count >= kUnitThresholds[i]) {
524 break;
525 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800526 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800527 return StringPrintf("%s%" PRId64 "%s",
528 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800529}
530
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700531std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800532 if (nano_duration == 0) {
533 return "0";
534 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700535 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
536 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700537 }
538}
539
540TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
541 const uint64_t one_sec = 1000 * 1000 * 1000;
542 const uint64_t one_ms = 1000 * 1000;
543 const uint64_t one_us = 1000;
544 if (nano_duration >= one_sec) {
545 return kTimeUnitSecond;
546 } else if (nano_duration >= one_ms) {
547 return kTimeUnitMillisecond;
548 } else if (nano_duration >= one_us) {
549 return kTimeUnitMicrosecond;
550 } else {
551 return kTimeUnitNanosecond;
552 }
553}
554
555uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
556 const uint64_t one_sec = 1000 * 1000 * 1000;
557 const uint64_t one_ms = 1000 * 1000;
558 const uint64_t one_us = 1000;
559
560 switch (time_unit) {
561 case kTimeUnitSecond:
562 return one_sec;
563 case kTimeUnitMillisecond:
564 return one_ms;
565 case kTimeUnitMicrosecond:
566 return one_us;
567 case kTimeUnitNanosecond:
568 return 1;
569 }
570 return 0;
571}
572
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700573std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
574 size_t max_fraction_digits) {
575 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700576 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700577 switch (time_unit) {
578 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800579 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700580 break;
581 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800582 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700583 break;
584 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800585 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700586 break;
587 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800588 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700589 break;
590 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700591 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700592 uint64_t fractional_part = nano_duration % divisor;
593 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800594 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700595 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700596 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700597 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700598 char fraction_buffer[kMaxDigits];
599 char* ptr = fraction_buffer;
600 uint64_t multiplier = 10;
601 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700602 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700603 multiplier *= 10;
604 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700605 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800606 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700607 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700608 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
609 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800610 }
611}
612
Ian Rogers576ca0c2014-06-06 15:58:22 -0700613std::string PrintableChar(uint16_t ch) {
614 std::string result;
615 result += '\'';
616 if (NeedsEscaping(ch)) {
617 StringAppendF(&result, "\\u%04x", ch);
618 } else {
619 result += ch;
620 }
621 result += '\'';
622 return result;
623}
624
Ian Rogers68b56852014-08-29 20:19:11 -0700625std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700626 std::string result;
627 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700628 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700629 size_t char_count = CountModifiedUtf8Chars(p);
630 for (size_t i = 0; i < char_count; ++i) {
631 uint16_t ch = GetUtf16FromUtf8(&p);
632 if (ch == '\\') {
633 result += "\\\\";
634 } else if (ch == '\n') {
635 result += "\\n";
636 } else if (ch == '\r') {
637 result += "\\r";
638 } else if (ch == '\t') {
639 result += "\\t";
640 } else if (NeedsEscaping(ch)) {
641 StringAppendF(&result, "\\u%04x", ch);
642 } else {
643 result += ch;
644 }
645 }
646 result += '"';
647 return result;
648}
649
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800650// See http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp615 for the full rules.
Elliott Hughes79082e32011-08-25 12:07:32 -0700651std::string MangleForJni(const std::string& s) {
652 std::string result;
653 size_t char_count = CountModifiedUtf8Chars(s.c_str());
654 const char* cp = &s[0];
655 for (size_t i = 0; i < char_count; ++i) {
656 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800657 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
658 result.push_back(ch);
659 } else if (ch == '.' || ch == '/') {
660 result += "_";
661 } else if (ch == '_') {
662 result += "_1";
663 } else if (ch == ';') {
664 result += "_2";
665 } else if (ch == '[') {
666 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700667 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800668 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700669 }
670 }
671 return result;
672}
673
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700674std::string DotToDescriptor(const char* class_name) {
675 std::string descriptor(class_name);
676 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
677 if (descriptor.length() > 0 && descriptor[0] != '[') {
678 descriptor = "L" + descriptor + ";";
679 }
680 return descriptor;
681}
682
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800683std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800684 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700685 if (length > 1) {
686 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
687 // Descriptors have the leading 'L' and trailing ';' stripped.
688 std::string result(descriptor + 1, length - 2);
689 std::replace(result.begin(), result.end(), '/', '.');
690 return result;
691 } else {
692 // For arrays the 'L' and ';' remain intact.
693 std::string result(descriptor);
694 std::replace(result.begin(), result.end(), '/', '.');
695 return result;
696 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800697 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700698 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800699 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800700}
701
702std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800703 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800704 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
705 std::string result(descriptor + 1, length - 2);
706 return result;
707 }
708 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700709}
710
Ian Rogersef7d42f2014-01-06 12:55:46 -0800711std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700712 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700713 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700714 CHECK_EQ(class_name[0], 'L') << class_name;
715 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700716 class_name.erase(0, 1);
717 class_name.erase(class_name.size() - 1, 1);
718
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700719 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700720
721 std::string short_name;
722 short_name += "Java_";
723 short_name += MangleForJni(class_name);
724 short_name += "_";
725 short_name += MangleForJni(method_name);
726 return short_name;
727}
728
Ian Rogersef7d42f2014-01-06 12:55:46 -0800729std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700730 std::string long_name;
731 long_name += JniShortName(m);
732 long_name += "__";
733
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700734 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700735 signature.erase(0, 1);
736 signature.erase(signature.begin() + signature.find(')'), signature.end());
737
738 long_name += MangleForJni(signature);
739
740 return long_name;
741}
742
jeffhao10037c82012-01-23 15:06:23 -0800743// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700744uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700745 0x00000000, // 00..1f low control characters; nothing valid
746 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
747 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
748 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700749};
750
jeffhao10037c82012-01-23 15:06:23 -0800751// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
752bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700753 /*
754 * It's a multibyte encoded character. Decode it and analyze. We
755 * accept anything that isn't (a) an improperly encoded low value,
756 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
757 * control character, or (e) a high space, layout, or special
758 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
759 * U+fff0..U+ffff). This is all specified in the dex format
760 * document.
761 */
762
763 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
764
765 // Perform follow-up tests based on the high 8 bits.
766 switch (utf16 >> 8) {
767 case 0x00:
768 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
769 return (utf16 > 0x00a0);
770 case 0xd8:
771 case 0xd9:
772 case 0xda:
773 case 0xdb:
774 // It's a leading surrogate. Check to see that a trailing
775 // surrogate follows.
776 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
777 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
778 case 0xdc:
779 case 0xdd:
780 case 0xde:
781 case 0xdf:
782 // It's a trailing surrogate, which is not valid at this point.
783 return false;
784 case 0x20:
785 case 0xff:
786 // It's in the range that has spaces, controls, and specials.
787 switch (utf16 & 0xfff8) {
788 case 0x2000:
789 case 0x2008:
790 case 0x2028:
791 case 0xfff0:
792 case 0xfff8:
793 return false;
794 }
795 break;
796 }
797 return true;
798}
799
800/* Return whether the pointed-at modified-UTF-8 encoded character is
801 * valid as part of a member name, updating the pointer to point past
802 * the consumed character. This will consume two encoded UTF-16 code
803 * points if the character is encoded as a surrogate pair. Also, if
804 * this function returns false, then the given pointer may only have
805 * been partially advanced.
806 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700807static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700808 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700809 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700810 // It's low-ascii, so check the table.
811 uint32_t wordIdx = c >> 5;
812 uint32_t bitIdx = c & 0x1f;
813 (*pUtf8Ptr)++;
814 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
815 }
816
817 // It's a multibyte encoded character. Call a non-inline function
818 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800819 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
820}
821
822bool IsValidMemberName(const char* s) {
823 bool angle_name = false;
824
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700825 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800826 case '\0':
827 // The empty string is not a valid name.
828 return false;
829 case '<':
830 angle_name = true;
831 s++;
832 break;
833 }
834
835 while (true) {
836 switch (*s) {
837 case '\0':
838 return !angle_name;
839 case '>':
840 return angle_name && s[1] == '\0';
841 }
842
843 if (!IsValidPartOfMemberNameUtf8(&s)) {
844 return false;
845 }
846 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700847}
848
Elliott Hughes906e6852011-10-28 14:52:10 -0700849enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700850template<ClassNameType kType, char kSeparator>
851static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700852 int arrayCount = 0;
853 while (*s == '[') {
854 arrayCount++;
855 s++;
856 }
857
858 if (arrayCount > 255) {
859 // Arrays may have no more than 255 dimensions.
860 return false;
861 }
862
Ian Rogers7b078e82014-09-10 14:44:24 -0700863 ClassNameType type = kType;
864 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700865 /*
866 * If we're looking at an array of some sort, then it doesn't
867 * matter if what is being asked for is a class name; the
868 * format looks the same as a type descriptor in that case, so
869 * treat it as such.
870 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700871 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700872 }
873
Elliott Hughes906e6852011-10-28 14:52:10 -0700874 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700875 /*
876 * We are looking for a descriptor. Either validate it as a
877 * single-character primitive type, or continue on to check the
878 * embedded class name (bracketed by "L" and ";").
879 */
880 switch (*(s++)) {
881 case 'B':
882 case 'C':
883 case 'D':
884 case 'F':
885 case 'I':
886 case 'J':
887 case 'S':
888 case 'Z':
889 // These are all single-character descriptors for primitive types.
890 return (*s == '\0');
891 case 'V':
892 // Non-array void is valid, but you can't have an array of void.
893 return (arrayCount == 0) && (*s == '\0');
894 case 'L':
895 // Class name: Break out and continue below.
896 break;
897 default:
898 // Oddball descriptor character.
899 return false;
900 }
901 }
902
903 /*
904 * We just consumed the 'L' that introduces a class name as part
905 * of a type descriptor, or we are looking for an unadorned class
906 * name.
907 */
908
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700909 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700910 for (;;) {
911 uint8_t c = (uint8_t) *s;
912 switch (c) {
913 case '\0':
914 /*
915 * Premature end for a type descriptor, but valid for
916 * a class name as long as we haven't encountered an
917 * empty component (including the degenerate case of
918 * the empty string "").
919 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700920 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700921 case ';':
922 /*
923 * Invalid character for a class name, but the
924 * legitimate end of a type descriptor. In the latter
925 * case, make sure that this is the end of the string
926 * and that it doesn't end with an empty component
927 * (including the degenerate case of "L;").
928 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700929 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700930 case '/':
931 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700932 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700933 // The wrong separator character.
934 return false;
935 }
936 if (sepOrFirst) {
937 // Separator at start or two separators in a row.
938 return false;
939 }
940 sepOrFirst = true;
941 s++;
942 break;
943 default:
jeffhao10037c82012-01-23 15:06:23 -0800944 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700945 return false;
946 }
947 sepOrFirst = false;
948 break;
949 }
950 }
951}
952
Elliott Hughes906e6852011-10-28 14:52:10 -0700953bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700954 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700955}
956
957bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700958 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700959}
960
961bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700962 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700963}
964
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700965void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700966 const char* p = s.data();
967 const char* end = p + s.size();
968 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800969 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700970 ++p;
971 } else {
972 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800973 while (++p != end && *p != separator) {
974 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700975 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700976 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700977 }
978 }
979}
980
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700981std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -0700982 std::string result;
983 unsigned int start_index = 0;
984 unsigned int end_index = s.size() - 1;
985
986 // Skip initial whitespace.
987 while (start_index < s.size()) {
988 if (!isspace(s[start_index])) {
989 break;
990 }
991 start_index++;
992 }
993
994 // Skip terminating whitespace.
995 while (end_index >= start_index) {
996 if (!isspace(s[end_index])) {
997 break;
998 }
999 end_index--;
1000 }
1001
1002 // All spaces, no beef.
1003 if (end_index < start_index) {
1004 return "";
1005 }
1006 // Start_index is the first non-space, end_index is the last one.
1007 return s.substr(start_index, end_index - start_index + 1);
1008}
1009
Elliott Hughes48436bb2012-02-07 15:23:28 -08001010template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001011std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -08001012 if (strings.empty()) {
1013 return "";
1014 }
1015
1016 std::string result(strings[0]);
1017 for (size_t i = 1; i < strings.size(); ++i) {
1018 result += separator;
1019 result += strings[i];
1020 }
1021 return result;
1022}
1023
1024// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001025template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
1026template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -08001027
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001028bool StartsWith(const std::string& s, const char* prefix) {
1029 return s.compare(0, strlen(prefix), prefix) == 0;
1030}
1031
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001032bool EndsWith(const std::string& s, const char* suffix) {
1033 size_t suffix_length = strlen(suffix);
1034 size_t string_length = s.size();
1035 if (suffix_length > string_length) {
1036 return false;
1037 }
1038 size_t offset = string_length - suffix_length;
1039 return s.compare(offset, suffix_length, suffix) == 0;
1040}
1041
Elliott Hughes22869a92012-03-27 14:08:24 -07001042void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -07001043 int hasAt = 0;
1044 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -07001045 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001046 while (*s) {
1047 if (*s == '.') {
1048 hasDot = 1;
1049 } else if (*s == '@') {
1050 hasAt = 1;
1051 }
1052 s++;
1053 }
Elliott Hughes22869a92012-03-27 14:08:24 -07001054 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001055 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -07001056 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001057 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001058 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001059 }
Elliott Hughes49e36ec2014-08-20 20:18:18 -07001060#if defined(__BIONIC__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001061 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001062 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1063 strncpy(buf, s, sizeof(buf)-1);
1064 buf[sizeof(buf)-1] = '\0';
1065 errno = pthread_setname_np(pthread_self(), buf);
1066 if (errno != 0) {
1067 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1068 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -07001069#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -07001070 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001071#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -07001072 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -07001073#else
Elliott Hughes22869a92012-03-27 14:08:24 -07001074 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001075#endif
1076}
1077
Brian Carlstrom29212012013-09-12 22:18:30 -07001078void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1079 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001080 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001081 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001082 return;
1083 }
1084 // Skip the command, which may contain spaces.
1085 stats = stats.substr(stats.find(')') + 2);
1086 // Extract the three fields we care about.
1087 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001088 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001089 *state = fields[0][0];
1090 *utime = strtoull(fields[11].c_str(), NULL, 10);
1091 *stime = strtoull(fields[12].c_str(), NULL, 10);
1092 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001093}
1094
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001095std::string GetSchedulerGroupName(pid_t tid) {
1096 // /proc/<pid>/cgroup looks like this:
1097 // 2:devices:/
1098 // 1:cpuacct,cpu:/
1099 // We want the third field from the line whose second field contains the "cpu" token.
1100 std::string cgroup_file;
1101 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1102 return "";
1103 }
1104 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001105 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001106 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1107 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001108 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001109 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001110 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001111 for (size_t j = 0; j < cgroups.size(); ++j) {
1112 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001113 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001114 }
1115 }
1116 }
1117 return "";
1118}
1119
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001120void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Andreas Gampe628a61a2015-01-07 22:08:35 -08001121 mirror::ArtMethod* current_method, void* ucontext_ptr) {
Ian Rogers83597d02014-11-20 10:29:00 -08001122#if __linux__
Andreas Gamped7576322014-10-24 22:13:45 -07001123 // b/18119146
1124 if (RUNNING_ON_VALGRIND != 0) {
1125 return;
1126 }
1127
Ian Rogersedfdaf32014-12-05 16:12:21 +00001128#if !defined(HAVE_ANDROID_OS)
1129 if (GetTid() != tid) {
1130 // TODO: dumping of other threads is disabled to avoid crashes during stress testing.
1131 // b/15446488.
1132 return;
1133 }
1134#endif
1135
Ian Rogers700a4022014-05-19 16:49:03 -07001136 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Andreas Gampe628a61a2015-01-07 22:08:35 -08001137 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001138 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001139 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001140 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001141 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001142 return;
1143 }
1144
Christopher Ferris943af7d2014-01-16 12:41:46 -08001145 for (Backtrace::const_iterator it = backtrace->begin();
1146 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001147 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001148 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1149 // In order for parsing tools to continue to function, the stack dump
1150 // format must at least adhere to this format:
1151 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1152 // The parsers require a single space before and after pc, and two spaces
1153 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1154 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1155 os << prefix << StringPrintf("#%02zu pc ", it->num);
1156 if (!it->map) {
1157 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001158 } else {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001159 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1160 << it->map->name << " (";
1161 if (!it->func_name.empty()) {
1162 os << it->func_name;
1163 if (it->func_offset != 0) {
1164 os << "+" << it->func_offset;
1165 }
Hiroshi Yamauchi7895d552014-08-28 14:55:56 -07001166 } else if (current_method != nullptr &&
1167 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001168 current_method->PcIsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001169 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1170 os << JniLongName(current_method) << "+"
1171 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001172 } else {
1173 os << "???";
1174 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001175 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001176 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001177 os << "\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001178 }
Nicolas Geoffraye6ac4fd2014-11-04 13:03:29 +00001179#else
1180 UNUSED(os, tid, prefix, current_method);
Ian Rogersc5f17732014-06-05 20:48:42 -07001181#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001182}
1183
Elliott Hughes058a6de2012-05-24 19:13:02 -07001184#if defined(__APPLE__)
1185
1186// TODO: is there any way to get the kernel stack on Mac OS?
1187void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1188
1189#else
1190
Elliott Hughes46e251b2012-05-22 15:10:45 -07001191void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001192 if (tid == GetTid()) {
1193 // There's no point showing that we're reading our stack out of /proc!
1194 return;
1195 }
1196
Elliott Hughes46e251b2012-05-22 15:10:45 -07001197 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1198 std::string kernel_stack;
1199 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001200 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001201 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001202 }
1203
1204 std::vector<std::string> kernel_stack_frames;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001205 Split(kernel_stack, '\n', &kernel_stack_frames);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001206 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1207 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1208 kernel_stack_frames.pop_back();
1209 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001210 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1211 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001212 const char* text = kernel_stack_frames[i].c_str();
1213 const char* close_bracket = strchr(text, ']');
1214 if (close_bracket != NULL) {
1215 text = close_bracket + 2;
1216 }
1217 os << prefix;
1218 if (include_count) {
1219 os << StringPrintf("#%02zd ", i);
1220 }
1221 os << text << "\n";
1222 }
1223}
1224
1225#endif
1226
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001227const char* GetAndroidRoot() {
1228 const char* android_root = getenv("ANDROID_ROOT");
1229 if (android_root == NULL) {
1230 if (OS::DirectoryExists("/system")) {
1231 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001232 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001233 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1234 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001235 }
1236 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001237 if (!OS::DirectoryExists(android_root)) {
1238 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001239 return "";
1240 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001241 return android_root;
1242}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001243
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001244const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001245 std::string error_msg;
1246 const char* dir = GetAndroidDataSafe(&error_msg);
1247 if (dir != nullptr) {
1248 return dir;
1249 } else {
1250 LOG(FATAL) << error_msg;
1251 return "";
1252 }
1253}
1254
1255const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001256 const char* android_data = getenv("ANDROID_DATA");
1257 if (android_data == NULL) {
1258 if (OS::DirectoryExists("/data")) {
1259 android_data = "/data";
1260 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001261 *error_msg = "ANDROID_DATA not set and /data does not exist";
1262 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001263 }
1264 }
1265 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001266 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1267 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001268 }
1269 return android_data;
1270}
1271
Alex Lighta59dd802014-07-02 16:28:08 -07001272void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001273 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001274 CHECK(subdir != nullptr);
1275 std::string error_msg;
1276 const char* android_data = GetAndroidDataSafe(&error_msg);
1277 if (android_data == nullptr) {
1278 *have_android_data = false;
1279 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001280 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001281 return;
1282 } else {
1283 *have_android_data = true;
1284 }
1285 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1286 *dalvik_cache = dalvik_cache_root + subdir;
1287 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001288 *is_global_cache = strcmp(android_data, "/data") == 0;
1289 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001290 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1291 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1292 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1293 }
1294}
1295
Narayan Kamath11d9f062014-04-23 20:24:57 +01001296std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1297 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001298 const char* android_data = GetAndroidData();
1299 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001300 const std::string dalvik_cache = dalvik_cache_root + subdir;
1301 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001302 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1303 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001304 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001305 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001306 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1307 return "";
1308 }
1309 result = mkdir(dalvik_cache.c_str(), 0700);
1310 if (result != 0) {
1311 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001312 return "";
1313 }
1314 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001315 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001316 return "";
1317 }
1318 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001319 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001320}
1321
Alex Lighta59dd802014-07-02 16:28:08 -07001322bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1323 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001324 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001325 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1326 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001327 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001328 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001329 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001330 cache_file += "/";
1331 cache_file += DexFile::kClassesDex;
1332 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001333 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001334 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1335 return true;
1336}
1337
1338std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1339 std::string ret;
1340 std::string error_msg;
1341 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1342 LOG(FATAL) << error_msg;
1343 }
1344 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001345}
1346
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001347static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001348 // in = /foo/bar/baz
1349 // out = /foo/bar/<isa>/baz
1350 size_t pos = filename->rfind('/');
1351 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1352 filename->insert(pos, "/", 1);
1353 filename->insert(pos + 1, GetInstructionSetString(isa));
1354}
1355
1356std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1357 // location = /system/framework/boot.art
1358 // filename = /system/framework/<isa>/boot.art
1359 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001360 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001361 return filename;
1362}
1363
1364std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1365 // location = /foo/bar/baz.jar
1366 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001367
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001368 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1369 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001370 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001371 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1372 CHECK_EQ('.', odex_location[dot_index]) << location;
1373 odex_location.resize(dot_index + 1);
1374 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1375 odex_location += "odex";
1376 return odex_location;
1377}
1378
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001379bool IsZipMagic(uint32_t magic) {
1380 return (('P' == ((magic >> 0) & 0xff)) &&
1381 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001382}
1383
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001384bool IsDexMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001385 return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001386}
1387
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001388bool IsOatMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001389 return (memcmp(reinterpret_cast<const uint8_t*>(magic),
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001390 OatHeader::kOatMagic,
1391 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001392}
1393
Brian Carlstrom6449c622014-02-10 23:48:36 -08001394bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1395 const std::string command_line(Join(arg_vector, ' '));
1396
1397 CHECK_GE(arg_vector.size(), 1U) << command_line;
1398
1399 // Convert the args to char pointers.
1400 const char* program = arg_vector[0].c_str();
1401 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001402 for (size_t i = 0; i < arg_vector.size(); ++i) {
1403 const std::string& arg = arg_vector[i];
1404 char* arg_str = const_cast<char*>(arg.c_str());
1405 CHECK(arg_str != nullptr) << i;
1406 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001407 }
1408 args.push_back(NULL);
1409
1410 // fork and exec
1411 pid_t pid = fork();
1412 if (pid == 0) {
1413 // no allocation allowed between fork and exec
1414
1415 // change process groups, so we don't get reaped by ProcessManager
1416 setpgid(0, 0);
1417
1418 execv(program, &args[0]);
1419
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001420 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1421 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001422 } else {
1423 if (pid == -1) {
1424 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1425 command_line.c_str(), strerror(errno));
1426 return false;
1427 }
1428
1429 // wait for subprocess to finish
1430 int status;
1431 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1432 if (got_pid != pid) {
1433 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1434 "wanted %d, got %d: %s",
1435 command_line.c_str(), pid, got_pid, strerror(errno));
1436 return false;
1437 }
1438 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1439 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1440 command_line.c_str());
1441 return false;
1442 }
1443 }
1444 return true;
1445}
1446
Tong Shen547cdfd2014-08-05 01:54:19 -07001447void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001448 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001449}
1450
1451void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001452 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001453}
1454
1455void PushWord(std::vector<uint8_t>* buf, int data) {
1456 buf->push_back(data & 0xff);
1457 buf->push_back((data >> 8) & 0xff);
1458 buf->push_back((data >> 16) & 0xff);
1459 buf->push_back((data >> 24) & 0xff);
1460}
1461
Mathieu Chartier76433272014-09-26 14:32:37 -07001462std::string PrettyDescriptor(Primitive::Type type) {
1463 return PrettyDescriptor(Primitive::Descriptor(type));
1464}
1465
Elliott Hughes42ee1422011-09-06 12:33:32 -07001466} // namespace art