blob: dbd22139ea5aad4471767ad8d8dc8922aca74aa2 [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"
Ian Rogers22d5e732014-07-15 22:23:51 -070031#include "field_helper.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070032#include "mirror/art_field-inl.h"
33#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "mirror/object-inl.h"
37#include "mirror/object_array-inl.h"
38#include "mirror/string.h"
buzbeec143c552011-08-20 17:38:58 -070039#include "os.h"
Kenny Root067d20f2014-03-05 14:57:21 -080040#include "scoped_thread_state_change.h"
Ian Rogersa6724902013-09-23 09:23:37 -070041#include "utf-inl.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070042
Elliott Hughesad6c9c32012-01-19 17:39:12 -080043#if !defined(HAVE_POSIX_CLOCKS)
44#include <sys/time.h>
45#endif
46
Elliott Hughesdcc24742011-09-07 14:02:44 -070047#if defined(HAVE_PRCTL)
48#include <sys/prctl.h>
49#endif
50
Elliott Hughes4ae722a2012-03-13 11:08:51 -070051#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070052#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070053#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070054#endif
55
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070056#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070057
Elliott Hughes058a6de2012-05-24 19:13:02 -070058#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080059#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080060#endif
61
Elliott Hughes11e45072011-08-16 17:40:46 -070062namespace art {
63
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080064pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070065#if defined(__APPLE__)
66 uint64_t owner;
67 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
68 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070069#elif defined(__BIONIC__)
70 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080071#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080072 return syscall(__NR_gettid);
73#endif
74}
75
Elliott Hughes289be852012-06-12 13:57:20 -070076std::string GetThreadName(pid_t tid) {
77 std::string result;
78 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070079 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070080 } else {
81 result = "<unknown>";
82 }
83 return result;
84}
85
Elliott Hughes6d3fc562014-08-27 11:47:01 -070086void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070087#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070088 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070089 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070090
91 // Check whether stack_addr is the base or end of the stack.
92 // (On Mac OS 10.7, it's the end.)
93 int stack_variable;
94 if (stack_addr > &stack_variable) {
Brian Carlstrom29212012013-09-12 22:18:30 -070095 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070096 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070097 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070098 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070099
100 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
101 pthread_attr_t attributes;
102 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
103 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
104 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700105#else
106 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700107 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700108 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700109 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700110 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700111
112#if defined(__GLIBC__)
113 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
114 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
115 // will be broken because we'll die long before we get close to 2GB.
116 bool is_main_thread = (::art::GetTid() == getpid());
117 if (is_main_thread) {
118 rlimit stack_limit;
119 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
120 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
121 }
122 if (stack_limit.rlim_cur == RLIM_INFINITY) {
123 size_t old_stack_size = *stack_size;
124
125 // Use the kernel default limit as our size, and adjust the base to match.
126 *stack_size = 8 * MB;
127 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
128
129 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
130 << " to " << PrettySize(*stack_size)
131 << " with base " << *stack_base;
132 }
133 }
134#endif
135
Elliott Hughese1884192012-04-23 12:38:15 -0700136#endif
137}
138
Elliott Hughesd92bec42011-09-02 17:04:36 -0700139bool ReadFileToString(const std::string& file_name, std::string* result) {
Ian Rogers700a4022014-05-19 16:49:03 -0700140 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800141 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700142 return false;
143 }
buzbeec143c552011-08-20 17:38:58 -0700144
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700145 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700146 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800147 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700148 if (n == -1) {
149 return false;
buzbeec143c552011-08-20 17:38:58 -0700150 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700151 if (n == 0) {
152 return true;
153 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700154 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700155 }
buzbeec143c552011-08-20 17:38:58 -0700156}
157
Elliott Hughese27955c2011-08-26 15:21:24 -0700158std::string GetIsoDate() {
159 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700160 tm tmbuf;
161 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700162 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
163 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
164 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
165}
166
Elliott Hughes7162ad92011-10-27 14:08:42 -0700167uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800168#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700169 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700170 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700171 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800172#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700173 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800174 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700175 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800176#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700177}
178
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800179uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800180#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700181 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800182 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700183 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800184#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700185 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800186 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700187 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800188#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800189}
190
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700191uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800192#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700193 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700194 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700195 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800196#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700197 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800198 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700199 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800200#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700201}
202
Elliott Hughes0512f022012-03-15 22:10:52 -0700203uint64_t ThreadCpuNanoTime() {
204#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700205 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700206 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700207 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0512f022012-03-15 22:10:52 -0700208#else
209 UNIMPLEMENTED(WARNING);
210 return -1;
211#endif
212}
213
Ian Rogers56edc432013-01-18 16:51:51 -0800214void NanoSleep(uint64_t ns) {
215 timespec tm;
216 tm.tv_sec = 0;
217 tm.tv_nsec = ns;
218 nanosleep(&tm, NULL);
219}
220
Brian Carlstrombcc29262012-11-02 11:36:03 -0700221void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
222 int64_t endSec;
223
224 if (absolute) {
225#if !defined(__APPLE__)
226 clock_gettime(clock, ts);
227#else
228 UNUSED(clock);
229 timeval tv;
230 gettimeofday(&tv, NULL);
231 ts->tv_sec = tv.tv_sec;
232 ts->tv_nsec = tv.tv_usec * 1000;
233#endif
234 } else {
235 ts->tv_sec = 0;
236 ts->tv_nsec = 0;
237 }
238 endSec = ts->tv_sec + ms / 1000;
239 if (UNLIKELY(endSec >= 0x7fffffff)) {
240 std::ostringstream ss;
241 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
242 endSec = 0x7ffffffe;
243 }
244 ts->tv_sec = endSec;
245 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
246
247 // Catch rollover.
248 if (ts->tv_nsec >= 1000000000L) {
249 ts->tv_sec++;
250 ts->tv_nsec -= 1000000000L;
251 }
252}
253
Ian Rogersef7d42f2014-01-06 12:55:46 -0800254std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700255 if (java_descriptor == NULL) {
256 return "null";
257 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700258 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700259}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700260
Ian Rogersef7d42f2014-01-06 12:55:46 -0800261std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800262 if (klass == NULL) {
263 return "null";
264 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700265 std::string temp;
266 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800267}
268
Ian Rogers1ff3c982014-08-12 02:30:58 -0700269std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700270 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700271 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700272 size_t dim = 0;
273 while (*c == '[') {
274 dim++;
275 c++;
276 }
277
278 // Reference or primitive?
279 if (*c == 'L') {
280 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700281 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700282 } else {
283 // "[[B" -> "byte[][]".
284 // To make life easier, we make primitives look like unqualified
285 // reference types.
286 switch (*c) {
287 case 'B': c = "byte;"; break;
288 case 'C': c = "char;"; break;
289 case 'D': c = "double;"; break;
290 case 'F': c = "float;"; break;
291 case 'I': c = "int;"; break;
292 case 'J': c = "long;"; break;
293 case 'S': c = "short;"; break;
294 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700295 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700296 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700297 }
298 }
299
300 // At this point, 'c' is a string of the form "fully/qualified/Type;"
301 // or "primitive;". Rewrite the type with '.' instead of '/':
302 std::string result;
303 const char* p = c;
304 while (*p != ';') {
305 char ch = *p++;
306 if (ch == '/') {
307 ch = '.';
308 }
309 result.push_back(ch);
310 }
311 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700312 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700313 result += "[]";
314 }
315 return result;
316}
317
Ian Rogersef7d42f2014-01-06 12:55:46 -0800318std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700319 if (f == NULL) {
320 return "null";
321 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700322 std::string result;
323 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700324 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700325 result += ' ';
326 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700327 StackHandleScope<1> hs(Thread::Current());
328 result += PrettyDescriptor(FieldHelper(hs.NewHandle(f)).GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700329 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700330 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700331 return result;
332}
333
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700334std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800335 if (field_idx >= dex_file.NumFieldIds()) {
336 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
337 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700338 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
339 std::string result;
340 if (with_type) {
341 result += dex_file.GetFieldTypeDescriptor(field_id);
342 result += ' ';
343 }
344 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
345 result += '.';
346 result += dex_file.GetFieldName(field_id);
347 return result;
348}
349
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700350std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800351 if (type_idx >= dex_file.NumTypeIds()) {
352 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
353 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700354 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700355 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700356}
357
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700358std::string PrettyArguments(const char* signature) {
359 std::string result;
360 result += '(';
361 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700362 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700363 while (*signature != ')') {
364 size_t argument_length = 0;
365 while (signature[argument_length] == '[') {
366 ++argument_length;
367 }
368 if (signature[argument_length] == 'L') {
369 argument_length = (strchr(signature, ';') - signature + 1);
370 } else {
371 ++argument_length;
372 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700373 {
374 std::string argument_descriptor(signature, argument_length);
375 result += PrettyDescriptor(argument_descriptor.c_str());
376 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700377 if (signature[argument_length] != ')') {
378 result += ", ";
379 }
380 signature += argument_length;
381 }
382 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700383 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700384 result += ')';
385 return result;
386}
387
388std::string PrettyReturnType(const char* signature) {
389 const char* return_type = strchr(signature, ')');
390 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700391 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700392 return PrettyDescriptor(return_type);
393}
394
Ian Rogersef7d42f2014-01-06 12:55:46 -0800395std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800396 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700397 return "null";
398 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700399 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700400 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700401 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800402 if (UNLIKELY(m->IsFastNative())) {
403 result += "!";
404 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700405 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700406 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700407 std::string sig_as_string(signature.ToString());
408 if (signature == Signature::NoSignature()) {
409 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700410 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700411 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
412 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700413 }
414 return result;
415}
416
Ian Rogers0571d352011-11-03 19:51:38 -0700417std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800418 if (method_idx >= dex_file.NumMethodIds()) {
419 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
420 }
Ian Rogers0571d352011-11-03 19:51:38 -0700421 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
422 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
423 result += '.';
424 result += dex_file.GetMethodName(method_id);
425 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700426 const Signature signature = dex_file.GetMethodSignature(method_id);
427 std::string sig_as_string(signature.ToString());
428 if (signature == Signature::NoSignature()) {
429 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700430 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700431 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
432 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700433 }
434 return result;
435}
436
Ian Rogersef7d42f2014-01-06 12:55:46 -0800437std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700438 if (obj == NULL) {
439 return "null";
440 }
441 if (obj->GetClass() == NULL) {
442 return "(raw)";
443 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700444 std::string temp;
445 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700446 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700447 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700448 }
449 return result;
450}
451
Ian Rogersef7d42f2014-01-06 12:55:46 -0800452std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700453 if (c == NULL) {
454 return "null";
455 }
456 std::string result;
457 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800458 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700459 result += ">";
460 return result;
461}
462
Ian Rogersef7d42f2014-01-06 12:55:46 -0800463std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700464 if (c == NULL) {
465 return "null";
466 }
467 std::string result;
468 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800469 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700470 result += ",";
471 result += PrettyTypeOf(c->GetClassLoader());
472 // TODO: add an identifying hash value for the loader
473 result += ">";
474 return result;
475}
476
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800477std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700478 // The byte thresholds at which we display amounts. A byte count is displayed
479 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800480 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700481 0, // B up to...
482 3*1024, // KB up to...
483 2*1024*1024, // MB up to...
484 1024*1024*1024 // GB from here.
485 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800486 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700487 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800488 const char* negative_str = "";
489 if (byte_count < 0) {
490 negative_str = "-";
491 byte_count = -byte_count;
492 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700493 int i = arraysize(kUnitThresholds);
494 while (--i > 0) {
495 if (byte_count >= kUnitThresholds[i]) {
496 break;
497 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800498 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800499 return StringPrintf("%s%" PRId64 "%s",
500 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800501}
502
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700503std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800504 if (nano_duration == 0) {
505 return "0";
506 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700507 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
508 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700509 }
510}
511
512TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
513 const uint64_t one_sec = 1000 * 1000 * 1000;
514 const uint64_t one_ms = 1000 * 1000;
515 const uint64_t one_us = 1000;
516 if (nano_duration >= one_sec) {
517 return kTimeUnitSecond;
518 } else if (nano_duration >= one_ms) {
519 return kTimeUnitMillisecond;
520 } else if (nano_duration >= one_us) {
521 return kTimeUnitMicrosecond;
522 } else {
523 return kTimeUnitNanosecond;
524 }
525}
526
527uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
528 const uint64_t one_sec = 1000 * 1000 * 1000;
529 const uint64_t one_ms = 1000 * 1000;
530 const uint64_t one_us = 1000;
531
532 switch (time_unit) {
533 case kTimeUnitSecond:
534 return one_sec;
535 case kTimeUnitMillisecond:
536 return one_ms;
537 case kTimeUnitMicrosecond:
538 return one_us;
539 case kTimeUnitNanosecond:
540 return 1;
541 }
542 return 0;
543}
544
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700545std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
546 size_t max_fraction_digits) {
547 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700548 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700549 switch (time_unit) {
550 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800551 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700552 break;
553 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800554 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700555 break;
556 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800557 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700558 break;
559 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800560 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700561 break;
562 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700563 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700564 uint64_t fractional_part = nano_duration % divisor;
565 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800566 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700567 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700568 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700569 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700570 char fraction_buffer[kMaxDigits];
571 char* ptr = fraction_buffer;
572 uint64_t multiplier = 10;
573 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700574 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700575 multiplier *= 10;
576 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700577 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800578 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700579 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700580 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
581 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800582 }
583}
584
Ian Rogers576ca0c2014-06-06 15:58:22 -0700585std::string PrintableChar(uint16_t ch) {
586 std::string result;
587 result += '\'';
588 if (NeedsEscaping(ch)) {
589 StringAppendF(&result, "\\u%04x", ch);
590 } else {
591 result += ch;
592 }
593 result += '\'';
594 return result;
595}
596
Ian Rogers68b56852014-08-29 20:19:11 -0700597std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700598 std::string result;
599 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700600 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700601 size_t char_count = CountModifiedUtf8Chars(p);
602 for (size_t i = 0; i < char_count; ++i) {
603 uint16_t ch = GetUtf16FromUtf8(&p);
604 if (ch == '\\') {
605 result += "\\\\";
606 } else if (ch == '\n') {
607 result += "\\n";
608 } else if (ch == '\r') {
609 result += "\\r";
610 } else if (ch == '\t') {
611 result += "\\t";
612 } else if (NeedsEscaping(ch)) {
613 StringAppendF(&result, "\\u%04x", ch);
614 } else {
615 result += ch;
616 }
617 }
618 result += '"';
619 return result;
620}
621
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800622// 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 -0700623std::string MangleForJni(const std::string& s) {
624 std::string result;
625 size_t char_count = CountModifiedUtf8Chars(s.c_str());
626 const char* cp = &s[0];
627 for (size_t i = 0; i < char_count; ++i) {
628 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800629 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
630 result.push_back(ch);
631 } else if (ch == '.' || ch == '/') {
632 result += "_";
633 } else if (ch == '_') {
634 result += "_1";
635 } else if (ch == ';') {
636 result += "_2";
637 } else if (ch == '[') {
638 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700639 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800640 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700641 }
642 }
643 return result;
644}
645
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700646std::string DotToDescriptor(const char* class_name) {
647 std::string descriptor(class_name);
648 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
649 if (descriptor.length() > 0 && descriptor[0] != '[') {
650 descriptor = "L" + descriptor + ";";
651 }
652 return descriptor;
653}
654
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800655std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800656 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700657 if (length > 1) {
658 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
659 // Descriptors have the leading 'L' and trailing ';' stripped.
660 std::string result(descriptor + 1, length - 2);
661 std::replace(result.begin(), result.end(), '/', '.');
662 return result;
663 } else {
664 // For arrays the 'L' and ';' remain intact.
665 std::string result(descriptor);
666 std::replace(result.begin(), result.end(), '/', '.');
667 return result;
668 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800669 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700670 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800671 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800672}
673
674std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800675 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800676 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
677 std::string result(descriptor + 1, length - 2);
678 return result;
679 }
680 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700681}
682
Ian Rogersef7d42f2014-01-06 12:55:46 -0800683std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700684 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700685 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700686 CHECK_EQ(class_name[0], 'L') << class_name;
687 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700688 class_name.erase(0, 1);
689 class_name.erase(class_name.size() - 1, 1);
690
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700691 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700692
693 std::string short_name;
694 short_name += "Java_";
695 short_name += MangleForJni(class_name);
696 short_name += "_";
697 short_name += MangleForJni(method_name);
698 return short_name;
699}
700
Ian Rogersef7d42f2014-01-06 12:55:46 -0800701std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700702 std::string long_name;
703 long_name += JniShortName(m);
704 long_name += "__";
705
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700706 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700707 signature.erase(0, 1);
708 signature.erase(signature.begin() + signature.find(')'), signature.end());
709
710 long_name += MangleForJni(signature);
711
712 return long_name;
713}
714
jeffhao10037c82012-01-23 15:06:23 -0800715// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700716uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700717 0x00000000, // 00..1f low control characters; nothing valid
718 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
719 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
720 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700721};
722
jeffhao10037c82012-01-23 15:06:23 -0800723// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
724bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700725 /*
726 * It's a multibyte encoded character. Decode it and analyze. We
727 * accept anything that isn't (a) an improperly encoded low value,
728 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
729 * control character, or (e) a high space, layout, or special
730 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
731 * U+fff0..U+ffff). This is all specified in the dex format
732 * document.
733 */
734
735 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
736
737 // Perform follow-up tests based on the high 8 bits.
738 switch (utf16 >> 8) {
739 case 0x00:
740 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
741 return (utf16 > 0x00a0);
742 case 0xd8:
743 case 0xd9:
744 case 0xda:
745 case 0xdb:
746 // It's a leading surrogate. Check to see that a trailing
747 // surrogate follows.
748 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
749 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
750 case 0xdc:
751 case 0xdd:
752 case 0xde:
753 case 0xdf:
754 // It's a trailing surrogate, which is not valid at this point.
755 return false;
756 case 0x20:
757 case 0xff:
758 // It's in the range that has spaces, controls, and specials.
759 switch (utf16 & 0xfff8) {
760 case 0x2000:
761 case 0x2008:
762 case 0x2028:
763 case 0xfff0:
764 case 0xfff8:
765 return false;
766 }
767 break;
768 }
769 return true;
770}
771
772/* Return whether the pointed-at modified-UTF-8 encoded character is
773 * valid as part of a member name, updating the pointer to point past
774 * the consumed character. This will consume two encoded UTF-16 code
775 * points if the character is encoded as a surrogate pair. Also, if
776 * this function returns false, then the given pointer may only have
777 * been partially advanced.
778 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700779static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700780 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700781 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700782 // It's low-ascii, so check the table.
783 uint32_t wordIdx = c >> 5;
784 uint32_t bitIdx = c & 0x1f;
785 (*pUtf8Ptr)++;
786 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
787 }
788
789 // It's a multibyte encoded character. Call a non-inline function
790 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800791 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
792}
793
794bool IsValidMemberName(const char* s) {
795 bool angle_name = false;
796
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700797 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800798 case '\0':
799 // The empty string is not a valid name.
800 return false;
801 case '<':
802 angle_name = true;
803 s++;
804 break;
805 }
806
807 while (true) {
808 switch (*s) {
809 case '\0':
810 return !angle_name;
811 case '>':
812 return angle_name && s[1] == '\0';
813 }
814
815 if (!IsValidPartOfMemberNameUtf8(&s)) {
816 return false;
817 }
818 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700819}
820
Elliott Hughes906e6852011-10-28 14:52:10 -0700821enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700822template<ClassNameType kType, char kSeparator>
823static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700824 int arrayCount = 0;
825 while (*s == '[') {
826 arrayCount++;
827 s++;
828 }
829
830 if (arrayCount > 255) {
831 // Arrays may have no more than 255 dimensions.
832 return false;
833 }
834
Ian Rogers7b078e82014-09-10 14:44:24 -0700835 ClassNameType type = kType;
836 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700837 /*
838 * If we're looking at an array of some sort, then it doesn't
839 * matter if what is being asked for is a class name; the
840 * format looks the same as a type descriptor in that case, so
841 * treat it as such.
842 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700843 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700844 }
845
Elliott Hughes906e6852011-10-28 14:52:10 -0700846 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700847 /*
848 * We are looking for a descriptor. Either validate it as a
849 * single-character primitive type, or continue on to check the
850 * embedded class name (bracketed by "L" and ";").
851 */
852 switch (*(s++)) {
853 case 'B':
854 case 'C':
855 case 'D':
856 case 'F':
857 case 'I':
858 case 'J':
859 case 'S':
860 case 'Z':
861 // These are all single-character descriptors for primitive types.
862 return (*s == '\0');
863 case 'V':
864 // Non-array void is valid, but you can't have an array of void.
865 return (arrayCount == 0) && (*s == '\0');
866 case 'L':
867 // Class name: Break out and continue below.
868 break;
869 default:
870 // Oddball descriptor character.
871 return false;
872 }
873 }
874
875 /*
876 * We just consumed the 'L' that introduces a class name as part
877 * of a type descriptor, or we are looking for an unadorned class
878 * name.
879 */
880
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700881 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700882 for (;;) {
883 uint8_t c = (uint8_t) *s;
884 switch (c) {
885 case '\0':
886 /*
887 * Premature end for a type descriptor, but valid for
888 * a class name as long as we haven't encountered an
889 * empty component (including the degenerate case of
890 * the empty string "").
891 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700892 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700893 case ';':
894 /*
895 * Invalid character for a class name, but the
896 * legitimate end of a type descriptor. In the latter
897 * case, make sure that this is the end of the string
898 * and that it doesn't end with an empty component
899 * (including the degenerate case of "L;").
900 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700901 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700902 case '/':
903 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700904 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700905 // The wrong separator character.
906 return false;
907 }
908 if (sepOrFirst) {
909 // Separator at start or two separators in a row.
910 return false;
911 }
912 sepOrFirst = true;
913 s++;
914 break;
915 default:
jeffhao10037c82012-01-23 15:06:23 -0800916 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700917 return false;
918 }
919 sepOrFirst = false;
920 break;
921 }
922 }
923}
924
Elliott Hughes906e6852011-10-28 14:52:10 -0700925bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700926 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700927}
928
929bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700930 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700931}
932
933bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700934 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700935}
936
Elliott Hughes48436bb2012-02-07 15:23:28 -0800937void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700938 const char* p = s.data();
939 const char* end = p + s.size();
940 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800941 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700942 ++p;
943 } else {
944 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800945 while (++p != end && *p != separator) {
946 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700947 }
948 result.push_back(std::string(start, p - start));
949 }
950 }
951}
952
Dave Allison70202782013-10-22 17:52:19 -0700953std::string Trim(std::string s) {
954 std::string result;
955 unsigned int start_index = 0;
956 unsigned int end_index = s.size() - 1;
957
958 // Skip initial whitespace.
959 while (start_index < s.size()) {
960 if (!isspace(s[start_index])) {
961 break;
962 }
963 start_index++;
964 }
965
966 // Skip terminating whitespace.
967 while (end_index >= start_index) {
968 if (!isspace(s[end_index])) {
969 break;
970 }
971 end_index--;
972 }
973
974 // All spaces, no beef.
975 if (end_index < start_index) {
976 return "";
977 }
978 // Start_index is the first non-space, end_index is the last one.
979 return s.substr(start_index, end_index - start_index + 1);
980}
981
Elliott Hughes48436bb2012-02-07 15:23:28 -0800982template <typename StringT>
983std::string Join(std::vector<StringT>& strings, char separator) {
984 if (strings.empty()) {
985 return "";
986 }
987
988 std::string result(strings[0]);
989 for (size_t i = 1; i < strings.size(); ++i) {
990 result += separator;
991 result += strings[i];
992 }
993 return result;
994}
995
996// Explicit instantiations.
997template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
998template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
999template std::string Join<char*>(std::vector<char*>& strings, char separator);
1000
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001001bool StartsWith(const std::string& s, const char* prefix) {
1002 return s.compare(0, strlen(prefix), prefix) == 0;
1003}
1004
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001005bool EndsWith(const std::string& s, const char* suffix) {
1006 size_t suffix_length = strlen(suffix);
1007 size_t string_length = s.size();
1008 if (suffix_length > string_length) {
1009 return false;
1010 }
1011 size_t offset = string_length - suffix_length;
1012 return s.compare(offset, suffix_length, suffix) == 0;
1013}
1014
Elliott Hughes22869a92012-03-27 14:08:24 -07001015void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -07001016 int hasAt = 0;
1017 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -07001018 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001019 while (*s) {
1020 if (*s == '.') {
1021 hasDot = 1;
1022 } else if (*s == '@') {
1023 hasAt = 1;
1024 }
1025 s++;
1026 }
Elliott Hughes22869a92012-03-27 14:08:24 -07001027 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001028 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -07001029 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001030 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001031 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001032 }
Elliott Hughes49e36ec2014-08-20 20:18:18 -07001033#if defined(__BIONIC__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001034 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001035 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1036 strncpy(buf, s, sizeof(buf)-1);
1037 buf[sizeof(buf)-1] = '\0';
1038 errno = pthread_setname_np(pthread_self(), buf);
1039 if (errno != 0) {
1040 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1041 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -07001042#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -07001043 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001044#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -07001045 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -07001046#else
Elliott Hughes22869a92012-03-27 14:08:24 -07001047 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001048#endif
1049}
1050
Brian Carlstrom29212012013-09-12 22:18:30 -07001051void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1052 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001053 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001054 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001055 return;
1056 }
1057 // Skip the command, which may contain spaces.
1058 stats = stats.substr(stats.find(')') + 2);
1059 // Extract the three fields we care about.
1060 std::vector<std::string> fields;
1061 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001062 *state = fields[0][0];
1063 *utime = strtoull(fields[11].c_str(), NULL, 10);
1064 *stime = strtoull(fields[12].c_str(), NULL, 10);
1065 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001066}
1067
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001068std::string GetSchedulerGroupName(pid_t tid) {
1069 // /proc/<pid>/cgroup looks like this:
1070 // 2:devices:/
1071 // 1:cpuacct,cpu:/
1072 // We want the third field from the line whose second field contains the "cpu" token.
1073 std::string cgroup_file;
1074 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1075 return "";
1076 }
1077 std::vector<std::string> cgroup_lines;
1078 Split(cgroup_file, '\n', cgroup_lines);
1079 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1080 std::vector<std::string> cgroup_fields;
1081 Split(cgroup_lines[i], ':', cgroup_fields);
1082 std::vector<std::string> cgroups;
1083 Split(cgroup_fields[1], ',', cgroups);
1084 for (size_t i = 0; i < cgroups.size(); ++i) {
1085 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001086 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001087 }
1088 }
1089 }
1090 return "";
1091}
1092
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001093void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Kenny Root067d20f2014-03-05 14:57:21 -08001094 mirror::ArtMethod* current_method) {
Ian Rogersc5f17732014-06-05 20:48:42 -07001095#ifdef __linux__
Ian Rogers700a4022014-05-19 16:49:03 -07001096 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001097 if (!backtrace->Unwind(0)) {
1098 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001099 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001100 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001101 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001102 return;
1103 }
1104
Christopher Ferris943af7d2014-01-16 12:41:46 -08001105 for (Backtrace::const_iterator it = backtrace->begin();
1106 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001107 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001108 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1109 // In order for parsing tools to continue to function, the stack dump
1110 // format must at least adhere to this format:
1111 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1112 // The parsers require a single space before and after pc, and two spaces
1113 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1114 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1115 os << prefix << StringPrintf("#%02zu pc ", it->num);
1116 if (!it->map) {
1117 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001118 } else {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001119 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1120 << it->map->name << " (";
1121 if (!it->func_name.empty()) {
1122 os << it->func_name;
1123 if (it->func_offset != 0) {
1124 os << "+" << it->func_offset;
1125 }
Hiroshi Yamauchi7895d552014-08-28 14:55:56 -07001126 } else if (current_method != nullptr &&
1127 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
1128 current_method->IsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001129 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1130 os << JniLongName(current_method) << "+"
1131 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001132 } else {
1133 os << "???";
1134 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001135 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001136 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001137 os << "\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001138 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001139#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001140}
1141
Elliott Hughes058a6de2012-05-24 19:13:02 -07001142#if defined(__APPLE__)
1143
1144// TODO: is there any way to get the kernel stack on Mac OS?
1145void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1146
1147#else
1148
Elliott Hughes46e251b2012-05-22 15:10:45 -07001149void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001150 if (tid == GetTid()) {
1151 // There's no point showing that we're reading our stack out of /proc!
1152 return;
1153 }
1154
Elliott Hughes46e251b2012-05-22 15:10:45 -07001155 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1156 std::string kernel_stack;
1157 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001158 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001159 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001160 }
1161
1162 std::vector<std::string> kernel_stack_frames;
1163 Split(kernel_stack, '\n', kernel_stack_frames);
1164 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1165 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1166 kernel_stack_frames.pop_back();
1167 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001168 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1169 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001170 const char* text = kernel_stack_frames[i].c_str();
1171 const char* close_bracket = strchr(text, ']');
1172 if (close_bracket != NULL) {
1173 text = close_bracket + 2;
1174 }
1175 os << prefix;
1176 if (include_count) {
1177 os << StringPrintf("#%02zd ", i);
1178 }
1179 os << text << "\n";
1180 }
1181}
1182
1183#endif
1184
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001185const char* GetAndroidRoot() {
1186 const char* android_root = getenv("ANDROID_ROOT");
1187 if (android_root == NULL) {
1188 if (OS::DirectoryExists("/system")) {
1189 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001190 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001191 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1192 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001193 }
1194 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001195 if (!OS::DirectoryExists(android_root)) {
1196 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001197 return "";
1198 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001199 return android_root;
1200}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001201
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001202const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001203 std::string error_msg;
1204 const char* dir = GetAndroidDataSafe(&error_msg);
1205 if (dir != nullptr) {
1206 return dir;
1207 } else {
1208 LOG(FATAL) << error_msg;
1209 return "";
1210 }
1211}
1212
1213const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001214 const char* android_data = getenv("ANDROID_DATA");
1215 if (android_data == NULL) {
1216 if (OS::DirectoryExists("/data")) {
1217 android_data = "/data";
1218 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001219 *error_msg = "ANDROID_DATA not set and /data does not exist";
1220 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001221 }
1222 }
1223 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001224 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1225 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001226 }
1227 return android_data;
1228}
1229
Alex Lighta59dd802014-07-02 16:28:08 -07001230void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001231 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001232 CHECK(subdir != nullptr);
1233 std::string error_msg;
1234 const char* android_data = GetAndroidDataSafe(&error_msg);
1235 if (android_data == nullptr) {
1236 *have_android_data = false;
1237 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001238 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001239 return;
1240 } else {
1241 *have_android_data = true;
1242 }
1243 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1244 *dalvik_cache = dalvik_cache_root + subdir;
1245 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001246 *is_global_cache = strcmp(android_data, "/data") == 0;
1247 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001248 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1249 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1250 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1251 }
1252}
1253
Narayan Kamath11d9f062014-04-23 20:24:57 +01001254std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1255 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001256 const char* android_data = GetAndroidData();
1257 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001258 const std::string dalvik_cache = dalvik_cache_root + subdir;
1259 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001260 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1261 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001262 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001263 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001264 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1265 return "";
1266 }
1267 result = mkdir(dalvik_cache.c_str(), 0700);
1268 if (result != 0) {
1269 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001270 return "";
1271 }
1272 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001273 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001274 return "";
1275 }
1276 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001277 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001278}
1279
Alex Lighta59dd802014-07-02 16:28:08 -07001280bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1281 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001282 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001283 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1284 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001285 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001286 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001287 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001288 cache_file += "/";
1289 cache_file += DexFile::kClassesDex;
1290 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001291 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001292 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1293 return true;
1294}
1295
1296std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1297 std::string ret;
1298 std::string error_msg;
1299 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1300 LOG(FATAL) << error_msg;
1301 }
1302 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001303}
1304
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001305static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001306 // in = /foo/bar/baz
1307 // out = /foo/bar/<isa>/baz
1308 size_t pos = filename->rfind('/');
1309 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1310 filename->insert(pos, "/", 1);
1311 filename->insert(pos + 1, GetInstructionSetString(isa));
1312}
1313
1314std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1315 // location = /system/framework/boot.art
1316 // filename = /system/framework/<isa>/boot.art
1317 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001318 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001319 return filename;
1320}
1321
1322std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1323 // location = /foo/bar/baz.jar
1324 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001325
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001326 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1327 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001328 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001329 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1330 CHECK_EQ('.', odex_location[dot_index]) << location;
1331 odex_location.resize(dot_index + 1);
1332 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1333 odex_location += "odex";
1334 return odex_location;
1335}
1336
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001337bool IsZipMagic(uint32_t magic) {
1338 return (('P' == ((magic >> 0) & 0xff)) &&
1339 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001340}
1341
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001342bool IsDexMagic(uint32_t magic) {
1343 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001344}
1345
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001346bool IsOatMagic(uint32_t magic) {
1347 return (memcmp(reinterpret_cast<const byte*>(magic),
1348 OatHeader::kOatMagic,
1349 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001350}
1351
Brian Carlstrom6449c622014-02-10 23:48:36 -08001352bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1353 const std::string command_line(Join(arg_vector, ' '));
1354
1355 CHECK_GE(arg_vector.size(), 1U) << command_line;
1356
1357 // Convert the args to char pointers.
1358 const char* program = arg_vector[0].c_str();
1359 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001360 for (size_t i = 0; i < arg_vector.size(); ++i) {
1361 const std::string& arg = arg_vector[i];
1362 char* arg_str = const_cast<char*>(arg.c_str());
1363 CHECK(arg_str != nullptr) << i;
1364 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001365 }
1366 args.push_back(NULL);
1367
1368 // fork and exec
1369 pid_t pid = fork();
1370 if (pid == 0) {
1371 // no allocation allowed between fork and exec
1372
1373 // change process groups, so we don't get reaped by ProcessManager
1374 setpgid(0, 0);
1375
1376 execv(program, &args[0]);
1377
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001378 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1379 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001380 } else {
1381 if (pid == -1) {
1382 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1383 command_line.c_str(), strerror(errno));
1384 return false;
1385 }
1386
1387 // wait for subprocess to finish
1388 int status;
1389 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1390 if (got_pid != pid) {
1391 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1392 "wanted %d, got %d: %s",
1393 command_line.c_str(), pid, got_pid, strerror(errno));
1394 return false;
1395 }
1396 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1397 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1398 command_line.c_str());
1399 return false;
1400 }
1401 }
1402 return true;
1403}
1404
Tong Shen547cdfd2014-08-05 01:54:19 -07001405void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001406 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001407}
1408
1409void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001410 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001411}
1412
1413void PushWord(std::vector<uint8_t>* buf, int data) {
1414 buf->push_back(data & 0xff);
1415 buf->push_back((data >> 8) & 0xff);
1416 buf->push_back((data >> 16) & 0xff);
1417 buf->push_back((data >> 24) & 0xff);
1418}
1419
Mathieu Chartier76433272014-09-26 14:32:37 -07001420std::string PrettyDescriptor(Primitive::Type type) {
1421 return PrettyDescriptor(Primitive::Descriptor(type));
1422}
1423
Elliott Hughes42ee1422011-09-06 12:33:32 -07001424} // namespace art