blob: 2123753de73fb83b3ee11b6b7e5a9695c9b55a00 [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 Hughes4ae722a2012-03-13 11:08:51 -070042#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070043#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070044#include <sys/syscall.h>
Elliott Hughes0a18df82015-01-09 15:16:16 -080045#include <sys/time.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070046#endif
47
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070048#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070049
Elliott Hughes058a6de2012-05-24 19:13:02 -070050#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080051#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080052#endif
53
Elliott Hughes11e45072011-08-16 17:40:46 -070054namespace art {
55
Andreas Gampe8e1cb912015-01-08 20:11:09 -080056#if defined(__linux__)
57static constexpr bool kUseAddr2line = !kIsTargetBuild;
58#endif
59
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080060pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070061#if defined(__APPLE__)
62 uint64_t owner;
63 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
64 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070065#elif defined(__BIONIC__)
66 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080067#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080068 return syscall(__NR_gettid);
69#endif
70}
71
Elliott Hughes289be852012-06-12 13:57:20 -070072std::string GetThreadName(pid_t tid) {
73 std::string result;
74 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070075 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070076 } else {
77 result = "<unknown>";
78 }
79 return result;
80}
81
Elliott Hughes6d3fc562014-08-27 11:47:01 -070082void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070083#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070084 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070085 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070086
87 // Check whether stack_addr is the base or end of the stack.
88 // (On Mac OS 10.7, it's the end.)
89 int stack_variable;
90 if (stack_addr > &stack_variable) {
Ian Rogers13735952014-10-08 12:43:28 -070091 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070092 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070093 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070094 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070095
96 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
97 pthread_attr_t attributes;
98 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
99 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
100 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700101#else
102 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700103 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700104 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700105 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700106 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700107
108#if defined(__GLIBC__)
109 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
110 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
111 // will be broken because we'll die long before we get close to 2GB.
112 bool is_main_thread = (::art::GetTid() == getpid());
113 if (is_main_thread) {
114 rlimit stack_limit;
115 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
116 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
117 }
118 if (stack_limit.rlim_cur == RLIM_INFINITY) {
119 size_t old_stack_size = *stack_size;
120
121 // Use the kernel default limit as our size, and adjust the base to match.
122 *stack_size = 8 * MB;
123 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
124
125 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
126 << " to " << PrettySize(*stack_size)
127 << " with base " << *stack_base;
128 }
129 }
130#endif
131
Elliott Hughese1884192012-04-23 12:38:15 -0700132#endif
133}
134
Elliott Hughesd92bec42011-09-02 17:04:36 -0700135bool ReadFileToString(const std::string& file_name, std::string* result) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800136 File file;
137 if (!file.Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700138 return false;
139 }
buzbeec143c552011-08-20 17:38:58 -0700140
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700141 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700142 while (true) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800143 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700144 if (n == -1) {
145 return false;
buzbeec143c552011-08-20 17:38:58 -0700146 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700147 if (n == 0) {
148 return true;
149 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700150 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700151 }
buzbeec143c552011-08-20 17:38:58 -0700152}
153
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800154bool PrintFileToLog(const std::string& file_name, LogSeverity level) {
155 File file;
156 if (!file.Open(file_name, O_RDONLY)) {
157 return false;
158 }
159
160 constexpr size_t kBufSize = 256; // Small buffer. Avoid stack overflow and stack size warnings.
161 char buf[kBufSize + 1]; // +1 for terminator.
162 size_t filled_to = 0;
163 while (true) {
164 DCHECK_LT(filled_to, kBufSize);
165 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[filled_to], kBufSize - filled_to));
166 if (n <= 0) {
167 // Print the rest of the buffer, if it exists.
168 if (filled_to > 0) {
169 buf[filled_to] = 0;
170 LOG(level) << buf;
171 }
172 return n == 0;
173 }
174 // Scan for '\n'.
175 size_t i = filled_to;
176 bool found_newline = false;
177 for (; i < filled_to + n; ++i) {
178 if (buf[i] == '\n') {
179 // Found a line break, that's something to print now.
180 buf[i] = 0;
181 LOG(level) << buf;
182 // Copy the rest to the front.
183 if (i + 1 < filled_to + n) {
184 memmove(&buf[0], &buf[i + 1], filled_to + n - i - 1);
185 filled_to = filled_to + n - i - 1;
186 } else {
187 filled_to = 0;
188 }
189 found_newline = true;
190 break;
191 }
192 }
193 if (found_newline) {
194 continue;
195 } else {
196 filled_to += n;
197 // Check if we must flush now.
198 if (filled_to == kBufSize) {
199 buf[kBufSize] = 0;
200 LOG(level) << buf;
201 filled_to = 0;
202 }
203 }
204 }
205}
206
Elliott Hughese27955c2011-08-26 15:21:24 -0700207std::string GetIsoDate() {
208 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700209 tm tmbuf;
210 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700211 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
212 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
213 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
214}
215
Elliott Hughes7162ad92011-10-27 14:08:42 -0700216uint64_t MilliTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800217#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700218 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700219 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700220 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800221#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700222 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800223 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700224 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800225#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700226}
227
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800228uint64_t MicroTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800229#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700230 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800231 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700232 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800233#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700234 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800235 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700236 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800237#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800238}
239
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700240uint64_t NanoTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800241#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700242 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700243 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700244 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0a18df82015-01-09 15:16:16 -0800245#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700246 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800247 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700248 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800249#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700250}
251
Elliott Hughes0512f022012-03-15 22:10:52 -0700252uint64_t ThreadCpuNanoTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800253#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700254 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700255 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700256 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0a18df82015-01-09 15:16:16 -0800257#else // __APPLE__
Elliott Hughes0512f022012-03-15 22:10:52 -0700258 UNIMPLEMENTED(WARNING);
259 return -1;
260#endif
261}
262
Ian Rogers56edc432013-01-18 16:51:51 -0800263void NanoSleep(uint64_t ns) {
264 timespec tm;
265 tm.tv_sec = 0;
266 tm.tv_nsec = ns;
267 nanosleep(&tm, NULL);
268}
269
Brian Carlstrombcc29262012-11-02 11:36:03 -0700270void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
271 int64_t endSec;
272
273 if (absolute) {
274#if !defined(__APPLE__)
275 clock_gettime(clock, ts);
276#else
277 UNUSED(clock);
278 timeval tv;
279 gettimeofday(&tv, NULL);
280 ts->tv_sec = tv.tv_sec;
281 ts->tv_nsec = tv.tv_usec * 1000;
282#endif
283 } else {
284 ts->tv_sec = 0;
285 ts->tv_nsec = 0;
286 }
287 endSec = ts->tv_sec + ms / 1000;
288 if (UNLIKELY(endSec >= 0x7fffffff)) {
289 std::ostringstream ss;
290 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
291 endSec = 0x7ffffffe;
292 }
293 ts->tv_sec = endSec;
294 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
295
296 // Catch rollover.
297 if (ts->tv_nsec >= 1000000000L) {
298 ts->tv_sec++;
299 ts->tv_nsec -= 1000000000L;
300 }
301}
302
Ian Rogersef7d42f2014-01-06 12:55:46 -0800303std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700304 if (java_descriptor == NULL) {
305 return "null";
306 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700307 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700308}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700309
Ian Rogersef7d42f2014-01-06 12:55:46 -0800310std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800311 if (klass == NULL) {
312 return "null";
313 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700314 std::string temp;
315 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800316}
317
Ian Rogers1ff3c982014-08-12 02:30:58 -0700318std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700319 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700320 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700321 size_t dim = 0;
322 while (*c == '[') {
323 dim++;
324 c++;
325 }
326
327 // Reference or primitive?
328 if (*c == 'L') {
329 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700330 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700331 } else {
332 // "[[B" -> "byte[][]".
333 // To make life easier, we make primitives look like unqualified
334 // reference types.
335 switch (*c) {
336 case 'B': c = "byte;"; break;
337 case 'C': c = "char;"; break;
338 case 'D': c = "double;"; break;
339 case 'F': c = "float;"; break;
340 case 'I': c = "int;"; break;
341 case 'J': c = "long;"; break;
342 case 'S': c = "short;"; break;
343 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700344 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700345 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700346 }
347 }
348
349 // At this point, 'c' is a string of the form "fully/qualified/Type;"
350 // or "primitive;". Rewrite the type with '.' instead of '/':
351 std::string result;
352 const char* p = c;
353 while (*p != ';') {
354 char ch = *p++;
355 if (ch == '/') {
356 ch = '.';
357 }
358 result.push_back(ch);
359 }
360 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700361 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700362 result += "[]";
363 }
364 return result;
365}
366
Ian Rogersef7d42f2014-01-06 12:55:46 -0800367std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700368 if (f == NULL) {
369 return "null";
370 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700371 std::string result;
372 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700373 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700374 result += ' ';
375 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800376 std::string temp;
377 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700378 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700379 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700380 return result;
381}
382
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700383std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800384 if (field_idx >= dex_file.NumFieldIds()) {
385 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
386 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700387 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
388 std::string result;
389 if (with_type) {
390 result += dex_file.GetFieldTypeDescriptor(field_id);
391 result += ' ';
392 }
393 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
394 result += '.';
395 result += dex_file.GetFieldName(field_id);
396 return result;
397}
398
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700399std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800400 if (type_idx >= dex_file.NumTypeIds()) {
401 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
402 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700403 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700404 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700405}
406
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700407std::string PrettyArguments(const char* signature) {
408 std::string result;
409 result += '(';
410 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700411 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700412 while (*signature != ')') {
413 size_t argument_length = 0;
414 while (signature[argument_length] == '[') {
415 ++argument_length;
416 }
417 if (signature[argument_length] == 'L') {
418 argument_length = (strchr(signature, ';') - signature + 1);
419 } else {
420 ++argument_length;
421 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700422 {
423 std::string argument_descriptor(signature, argument_length);
424 result += PrettyDescriptor(argument_descriptor.c_str());
425 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700426 if (signature[argument_length] != ')') {
427 result += ", ";
428 }
429 signature += argument_length;
430 }
431 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700432 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700433 result += ')';
434 return result;
435}
436
437std::string PrettyReturnType(const char* signature) {
438 const char* return_type = strchr(signature, ')');
439 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700440 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700441 return PrettyDescriptor(return_type);
442}
443
Ian Rogersef7d42f2014-01-06 12:55:46 -0800444std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800445 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700446 return "null";
447 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700448 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700449 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700450 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800451 if (UNLIKELY(m->IsFastNative())) {
452 result += "!";
453 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700454 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700455 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700456 std::string sig_as_string(signature.ToString());
457 if (signature == Signature::NoSignature()) {
458 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700459 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700460 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
461 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700462 }
463 return result;
464}
465
Ian Rogers0571d352011-11-03 19:51:38 -0700466std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800467 if (method_idx >= dex_file.NumMethodIds()) {
468 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
469 }
Ian Rogers0571d352011-11-03 19:51:38 -0700470 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
471 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
472 result += '.';
473 result += dex_file.GetMethodName(method_id);
474 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700475 const Signature signature = dex_file.GetMethodSignature(method_id);
476 std::string sig_as_string(signature.ToString());
477 if (signature == Signature::NoSignature()) {
478 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700479 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700480 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
481 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700482 }
483 return result;
484}
485
Ian Rogersef7d42f2014-01-06 12:55:46 -0800486std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700487 if (obj == NULL) {
488 return "null";
489 }
490 if (obj->GetClass() == NULL) {
491 return "(raw)";
492 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700493 std::string temp;
494 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700495 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700496 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700497 }
498 return result;
499}
500
Ian Rogersef7d42f2014-01-06 12:55:46 -0800501std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700502 if (c == NULL) {
503 return "null";
504 }
505 std::string result;
506 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800507 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700508 result += ">";
509 return result;
510}
511
Ian Rogersef7d42f2014-01-06 12:55:46 -0800512std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700513 if (c == NULL) {
514 return "null";
515 }
516 std::string result;
517 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800518 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700519 result += ",";
520 result += PrettyTypeOf(c->GetClassLoader());
521 // TODO: add an identifying hash value for the loader
522 result += ">";
523 return result;
524}
525
Andreas Gampec0d82292014-09-23 10:38:30 -0700526std::string PrettyJavaAccessFlags(uint32_t access_flags) {
527 std::string result;
528 if ((access_flags & kAccPublic) != 0) {
529 result += "public ";
530 }
531 if ((access_flags & kAccProtected) != 0) {
532 result += "protected ";
533 }
534 if ((access_flags & kAccPrivate) != 0) {
535 result += "private ";
536 }
537 if ((access_flags & kAccFinal) != 0) {
538 result += "final ";
539 }
540 if ((access_flags & kAccStatic) != 0) {
541 result += "static ";
542 }
543 if ((access_flags & kAccTransient) != 0) {
544 result += "transient ";
545 }
546 if ((access_flags & kAccVolatile) != 0) {
547 result += "volatile ";
548 }
549 if ((access_flags & kAccSynchronized) != 0) {
550 result += "synchronized ";
551 }
552 return result;
553}
554
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800555std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700556 // The byte thresholds at which we display amounts. A byte count is displayed
557 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800558 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700559 0, // B up to...
560 3*1024, // KB up to...
561 2*1024*1024, // MB up to...
562 1024*1024*1024 // GB from here.
563 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800564 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700565 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800566 const char* negative_str = "";
567 if (byte_count < 0) {
568 negative_str = "-";
569 byte_count = -byte_count;
570 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700571 int i = arraysize(kUnitThresholds);
572 while (--i > 0) {
573 if (byte_count >= kUnitThresholds[i]) {
574 break;
575 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800576 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800577 return StringPrintf("%s%" PRId64 "%s",
578 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800579}
580
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700581std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800582 if (nano_duration == 0) {
583 return "0";
584 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700585 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
586 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700587 }
588}
589
590TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
591 const uint64_t one_sec = 1000 * 1000 * 1000;
592 const uint64_t one_ms = 1000 * 1000;
593 const uint64_t one_us = 1000;
594 if (nano_duration >= one_sec) {
595 return kTimeUnitSecond;
596 } else if (nano_duration >= one_ms) {
597 return kTimeUnitMillisecond;
598 } else if (nano_duration >= one_us) {
599 return kTimeUnitMicrosecond;
600 } else {
601 return kTimeUnitNanosecond;
602 }
603}
604
605uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
606 const uint64_t one_sec = 1000 * 1000 * 1000;
607 const uint64_t one_ms = 1000 * 1000;
608 const uint64_t one_us = 1000;
609
610 switch (time_unit) {
611 case kTimeUnitSecond:
612 return one_sec;
613 case kTimeUnitMillisecond:
614 return one_ms;
615 case kTimeUnitMicrosecond:
616 return one_us;
617 case kTimeUnitNanosecond:
618 return 1;
619 }
620 return 0;
621}
622
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700623std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
624 size_t max_fraction_digits) {
625 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700626 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700627 switch (time_unit) {
628 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800629 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700630 break;
631 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800632 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700633 break;
634 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800635 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700636 break;
637 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800638 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700639 break;
640 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700641 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700642 uint64_t fractional_part = nano_duration % divisor;
643 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800644 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700645 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700646 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700647 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700648 char fraction_buffer[kMaxDigits];
649 char* ptr = fraction_buffer;
650 uint64_t multiplier = 10;
651 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700652 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700653 multiplier *= 10;
654 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700655 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800656 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700657 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700658 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
659 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800660 }
661}
662
Ian Rogers576ca0c2014-06-06 15:58:22 -0700663std::string PrintableChar(uint16_t ch) {
664 std::string result;
665 result += '\'';
666 if (NeedsEscaping(ch)) {
667 StringAppendF(&result, "\\u%04x", ch);
668 } else {
669 result += ch;
670 }
671 result += '\'';
672 return result;
673}
674
Ian Rogers68b56852014-08-29 20:19:11 -0700675std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700676 std::string result;
677 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700678 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700679 size_t char_count = CountModifiedUtf8Chars(p);
680 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000681 uint32_t ch = GetUtf16FromUtf8(&p);
Elliott Hughes82914b62012-04-09 15:56:29 -0700682 if (ch == '\\') {
683 result += "\\\\";
684 } else if (ch == '\n') {
685 result += "\\n";
686 } else if (ch == '\r') {
687 result += "\\r";
688 } else if (ch == '\t') {
689 result += "\\t";
Elliott Hughes82914b62012-04-09 15:56:29 -0700690 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000691 const uint16_t leading = GetLeadingUtf16Char(ch);
692
693 if (NeedsEscaping(leading)) {
694 StringAppendF(&result, "\\u%04x", leading);
695 } else {
696 result += leading;
697 }
698
699 const uint32_t trailing = GetTrailingUtf16Char(ch);
700 if (trailing != 0) {
701 // All high surrogates will need escaping.
702 StringAppendF(&result, "\\u%04x", trailing);
703 }
Elliott Hughes82914b62012-04-09 15:56:29 -0700704 }
705 }
706 result += '"';
707 return result;
708}
709
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800710// 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 -0700711std::string MangleForJni(const std::string& s) {
712 std::string result;
713 size_t char_count = CountModifiedUtf8Chars(s.c_str());
714 const char* cp = &s[0];
715 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000716 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800717 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
718 result.push_back(ch);
719 } else if (ch == '.' || ch == '/') {
720 result += "_";
721 } else if (ch == '_') {
722 result += "_1";
723 } else if (ch == ';') {
724 result += "_2";
725 } else if (ch == '[') {
726 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700727 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000728 const uint16_t leading = GetLeadingUtf16Char(ch);
729 const uint32_t trailing = GetTrailingUtf16Char(ch);
730
731 StringAppendF(&result, "_0%04x", leading);
732 if (trailing != 0) {
733 StringAppendF(&result, "_0%04x", trailing);
734 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700735 }
736 }
737 return result;
738}
739
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700740std::string DotToDescriptor(const char* class_name) {
741 std::string descriptor(class_name);
742 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
743 if (descriptor.length() > 0 && descriptor[0] != '[') {
744 descriptor = "L" + descriptor + ";";
745 }
746 return descriptor;
747}
748
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800749std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800750 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700751 if (length > 1) {
752 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
753 // Descriptors have the leading 'L' and trailing ';' stripped.
754 std::string result(descriptor + 1, length - 2);
755 std::replace(result.begin(), result.end(), '/', '.');
756 return result;
757 } else {
758 // For arrays the 'L' and ';' remain intact.
759 std::string result(descriptor);
760 std::replace(result.begin(), result.end(), '/', '.');
761 return result;
762 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800763 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700764 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800765 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800766}
767
768std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800769 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800770 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
771 std::string result(descriptor + 1, length - 2);
772 return result;
773 }
774 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700775}
776
Ian Rogersef7d42f2014-01-06 12:55:46 -0800777std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700778 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700779 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700780 CHECK_EQ(class_name[0], 'L') << class_name;
781 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700782 class_name.erase(0, 1);
783 class_name.erase(class_name.size() - 1, 1);
784
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700785 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700786
787 std::string short_name;
788 short_name += "Java_";
789 short_name += MangleForJni(class_name);
790 short_name += "_";
791 short_name += MangleForJni(method_name);
792 return short_name;
793}
794
Ian Rogersef7d42f2014-01-06 12:55:46 -0800795std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700796 std::string long_name;
797 long_name += JniShortName(m);
798 long_name += "__";
799
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700800 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700801 signature.erase(0, 1);
802 signature.erase(signature.begin() + signature.find(')'), signature.end());
803
804 long_name += MangleForJni(signature);
805
806 return long_name;
807}
808
jeffhao10037c82012-01-23 15:06:23 -0800809// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700810uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700811 0x00000000, // 00..1f low control characters; nothing valid
812 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
813 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
814 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700815};
816
jeffhao10037c82012-01-23 15:06:23 -0800817// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
818bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700819 /*
820 * It's a multibyte encoded character. Decode it and analyze. We
821 * accept anything that isn't (a) an improperly encoded low value,
822 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
823 * control character, or (e) a high space, layout, or special
824 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
825 * U+fff0..U+ffff). This is all specified in the dex format
826 * document.
827 */
828
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000829 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700830
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000831 const uint16_t leading = GetLeadingUtf16Char(pair);
832 const uint32_t trailing = GetTrailingUtf16Char(pair);
833
834 if (trailing == 0) {
835 // Perform follow-up tests based on the high 8 bits of the
836 // lower surrogate.
837 switch (leading >> 8) {
838 case 0x00:
839 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
840 return (leading > 0x00a0);
841 case 0xd8:
842 case 0xd9:
843 case 0xda:
844 case 0xdb:
845 // It looks like a leading surrogate but we didn't find a trailing
846 // surrogate if we're here.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700847 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000848 case 0xdc:
849 case 0xdd:
850 case 0xde:
851 case 0xdf:
852 // It's a trailing surrogate, which is not valid at this point.
853 return false;
854 case 0x20:
855 case 0xff:
856 // It's in the range that has spaces, controls, and specials.
857 switch (leading & 0xfff8) {
858 case 0x2000:
859 case 0x2008:
860 case 0x2028:
861 case 0xfff0:
862 case 0xfff8:
863 return false;
864 }
865 break;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700866 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000867
868 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700869 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000870
871 // We have a surrogate pair. Check that trailing surrogate is well formed.
872 return (trailing >= 0xdc00 && trailing <= 0xdfff);
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700873}
874
875/* Return whether the pointed-at modified-UTF-8 encoded character is
876 * valid as part of a member name, updating the pointer to point past
877 * the consumed character. This will consume two encoded UTF-16 code
878 * points if the character is encoded as a surrogate pair. Also, if
879 * this function returns false, then the given pointer may only have
880 * been partially advanced.
881 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700882static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700883 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700884 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700885 // It's low-ascii, so check the table.
886 uint32_t wordIdx = c >> 5;
887 uint32_t bitIdx = c & 0x1f;
888 (*pUtf8Ptr)++;
889 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
890 }
891
892 // It's a multibyte encoded character. Call a non-inline function
893 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800894 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
895}
896
897bool IsValidMemberName(const char* s) {
898 bool angle_name = false;
899
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700900 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800901 case '\0':
902 // The empty string is not a valid name.
903 return false;
904 case '<':
905 angle_name = true;
906 s++;
907 break;
908 }
909
910 while (true) {
911 switch (*s) {
912 case '\0':
913 return !angle_name;
914 case '>':
915 return angle_name && s[1] == '\0';
916 }
917
918 if (!IsValidPartOfMemberNameUtf8(&s)) {
919 return false;
920 }
921 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700922}
923
Elliott Hughes906e6852011-10-28 14:52:10 -0700924enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700925template<ClassNameType kType, char kSeparator>
926static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700927 int arrayCount = 0;
928 while (*s == '[') {
929 arrayCount++;
930 s++;
931 }
932
933 if (arrayCount > 255) {
934 // Arrays may have no more than 255 dimensions.
935 return false;
936 }
937
Ian Rogers7b078e82014-09-10 14:44:24 -0700938 ClassNameType type = kType;
939 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700940 /*
941 * If we're looking at an array of some sort, then it doesn't
942 * matter if what is being asked for is a class name; the
943 * format looks the same as a type descriptor in that case, so
944 * treat it as such.
945 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700946 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700947 }
948
Elliott Hughes906e6852011-10-28 14:52:10 -0700949 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700950 /*
951 * We are looking for a descriptor. Either validate it as a
952 * single-character primitive type, or continue on to check the
953 * embedded class name (bracketed by "L" and ";").
954 */
955 switch (*(s++)) {
956 case 'B':
957 case 'C':
958 case 'D':
959 case 'F':
960 case 'I':
961 case 'J':
962 case 'S':
963 case 'Z':
964 // These are all single-character descriptors for primitive types.
965 return (*s == '\0');
966 case 'V':
967 // Non-array void is valid, but you can't have an array of void.
968 return (arrayCount == 0) && (*s == '\0');
969 case 'L':
970 // Class name: Break out and continue below.
971 break;
972 default:
973 // Oddball descriptor character.
974 return false;
975 }
976 }
977
978 /*
979 * We just consumed the 'L' that introduces a class name as part
980 * of a type descriptor, or we are looking for an unadorned class
981 * name.
982 */
983
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700984 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700985 for (;;) {
986 uint8_t c = (uint8_t) *s;
987 switch (c) {
988 case '\0':
989 /*
990 * Premature end for a type descriptor, but valid for
991 * a class name as long as we haven't encountered an
992 * empty component (including the degenerate case of
993 * the empty string "").
994 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700995 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700996 case ';':
997 /*
998 * Invalid character for a class name, but the
999 * legitimate end of a type descriptor. In the latter
1000 * case, make sure that this is the end of the string
1001 * and that it doesn't end with an empty component
1002 * (including the degenerate case of "L;").
1003 */
Elliott Hughes906e6852011-10-28 14:52:10 -07001004 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -07001005 case '/':
1006 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -07001007 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -07001008 // The wrong separator character.
1009 return false;
1010 }
1011 if (sepOrFirst) {
1012 // Separator at start or two separators in a row.
1013 return false;
1014 }
1015 sepOrFirst = true;
1016 s++;
1017 break;
1018 default:
jeffhao10037c82012-01-23 15:06:23 -08001019 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -07001020 return false;
1021 }
1022 sepOrFirst = false;
1023 break;
1024 }
1025 }
1026}
1027
Elliott Hughes906e6852011-10-28 14:52:10 -07001028bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001029 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -07001030}
1031
1032bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001033 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -07001034}
1035
1036bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001037 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -07001038}
1039
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001040void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -07001041 const char* p = s.data();
1042 const char* end = p + s.size();
1043 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -08001044 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -07001045 ++p;
1046 } else {
1047 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -08001048 while (++p != end && *p != separator) {
1049 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -07001050 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001051 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -07001052 }
1053 }
1054}
1055
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001056std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -07001057 std::string result;
1058 unsigned int start_index = 0;
1059 unsigned int end_index = s.size() - 1;
1060
1061 // Skip initial whitespace.
1062 while (start_index < s.size()) {
1063 if (!isspace(s[start_index])) {
1064 break;
1065 }
1066 start_index++;
1067 }
1068
1069 // Skip terminating whitespace.
1070 while (end_index >= start_index) {
1071 if (!isspace(s[end_index])) {
1072 break;
1073 }
1074 end_index--;
1075 }
1076
1077 // All spaces, no beef.
1078 if (end_index < start_index) {
1079 return "";
1080 }
1081 // Start_index is the first non-space, end_index is the last one.
1082 return s.substr(start_index, end_index - start_index + 1);
1083}
1084
Elliott Hughes48436bb2012-02-07 15:23:28 -08001085template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001086std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -08001087 if (strings.empty()) {
1088 return "";
1089 }
1090
1091 std::string result(strings[0]);
1092 for (size_t i = 1; i < strings.size(); ++i) {
1093 result += separator;
1094 result += strings[i];
1095 }
1096 return result;
1097}
1098
1099// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001100template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
1101template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -08001102
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001103bool StartsWith(const std::string& s, const char* prefix) {
1104 return s.compare(0, strlen(prefix), prefix) == 0;
1105}
1106
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001107bool EndsWith(const std::string& s, const char* suffix) {
1108 size_t suffix_length = strlen(suffix);
1109 size_t string_length = s.size();
1110 if (suffix_length > string_length) {
1111 return false;
1112 }
1113 size_t offset = string_length - suffix_length;
1114 return s.compare(offset, suffix_length, suffix) == 0;
1115}
1116
Elliott Hughes22869a92012-03-27 14:08:24 -07001117void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -07001118 int hasAt = 0;
1119 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -07001120 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001121 while (*s) {
1122 if (*s == '.') {
1123 hasDot = 1;
1124 } else if (*s == '@') {
1125 hasAt = 1;
1126 }
1127 s++;
1128 }
Elliott Hughes22869a92012-03-27 14:08:24 -07001129 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001130 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -07001131 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001132 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001133 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001134 }
Elliott Hughes0a18df82015-01-09 15:16:16 -08001135#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001136 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -08001137 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001138 strncpy(buf, s, sizeof(buf)-1);
1139 buf[sizeof(buf)-1] = '\0';
1140 errno = pthread_setname_np(pthread_self(), buf);
1141 if (errno != 0) {
1142 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1143 }
Elliott Hughes0a18df82015-01-09 15:16:16 -08001144#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -07001145 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001146#endif
1147}
1148
Brian Carlstrom29212012013-09-12 22:18:30 -07001149void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1150 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001151 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001152 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001153 return;
1154 }
1155 // Skip the command, which may contain spaces.
1156 stats = stats.substr(stats.find(')') + 2);
1157 // Extract the three fields we care about.
1158 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001159 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001160 *state = fields[0][0];
1161 *utime = strtoull(fields[11].c_str(), NULL, 10);
1162 *stime = strtoull(fields[12].c_str(), NULL, 10);
1163 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001164}
1165
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001166std::string GetSchedulerGroupName(pid_t tid) {
1167 // /proc/<pid>/cgroup looks like this:
1168 // 2:devices:/
1169 // 1:cpuacct,cpu:/
1170 // We want the third field from the line whose second field contains the "cpu" token.
1171 std::string cgroup_file;
1172 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1173 return "";
1174 }
1175 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001176 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001177 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1178 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001179 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001180 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001181 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001182 for (size_t j = 0; j < cgroups.size(); ++j) {
1183 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001184 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001185 }
1186 }
1187 }
1188 return "";
1189}
1190
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001191#if defined(__linux__)
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001192
1193ALWAYS_INLINE
1194static inline void WritePrefix(std::ostream* os, const char* prefix, bool odd) {
1195 if (prefix != nullptr) {
1196 *os << prefix;
1197 }
1198 *os << " ";
1199 if (!odd) {
1200 *os << " ";
1201 }
1202}
1203
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001204static bool RunCommand(std::string cmd, std::ostream* os, const char* prefix) {
1205 FILE* stream = popen(cmd.c_str(), "r");
1206 if (stream) {
1207 if (os != nullptr) {
1208 bool odd_line = true; // We indent them differently.
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001209 bool wrote_prefix = false; // Have we already written a prefix?
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001210 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
1211 // alt stack, but just to be sure...
1212 char buffer[kMaxBuffer];
1213 while (!feof(stream)) {
1214 if (fgets(buffer, kMaxBuffer, stream) != nullptr) {
1215 // Split on newlines.
1216 char* tmp = buffer;
1217 for (;;) {
1218 char* new_line = strchr(tmp, '\n');
1219 if (new_line == nullptr) {
1220 // Print the rest.
1221 if (*tmp != 0) {
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001222 if (!wrote_prefix) {
1223 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001224 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001225 wrote_prefix = true;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001226 *os << tmp;
1227 }
1228 break;
1229 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001230 if (!wrote_prefix) {
1231 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001232 }
1233 char saved = *(new_line + 1);
1234 *(new_line + 1) = 0;
1235 *os << tmp;
1236 *(new_line + 1) = saved;
1237 tmp = new_line + 1;
1238 odd_line = !odd_line;
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001239 wrote_prefix = false;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001240 }
1241 }
1242 }
1243 }
1244 pclose(stream);
1245 return true;
1246 } else {
1247 return false;
1248 }
1249}
1250
1251static void Addr2line(const std::string& map_src, uintptr_t offset, std::ostream& os,
1252 const char* prefix) {
1253 std::string cmdline(StringPrintf("addr2line --functions --inlines --demangle -e %s %zx",
1254 map_src.c_str(), offset));
1255 RunCommand(cmdline.c_str(), &os, prefix);
1256}
1257#endif
1258
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001259void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Andreas Gampe628a61a2015-01-07 22:08:35 -08001260 mirror::ArtMethod* current_method, void* ucontext_ptr) {
Ian Rogers83597d02014-11-20 10:29:00 -08001261#if __linux__
Andreas Gamped7576322014-10-24 22:13:45 -07001262 // b/18119146
1263 if (RUNNING_ON_VALGRIND != 0) {
1264 return;
1265 }
1266
Ian Rogersedfdaf32014-12-05 16:12:21 +00001267#if !defined(HAVE_ANDROID_OS)
1268 if (GetTid() != tid) {
1269 // TODO: dumping of other threads is disabled to avoid crashes during stress testing.
1270 // b/15446488.
1271 return;
1272 }
1273#endif
1274
Ian Rogers700a4022014-05-19 16:49:03 -07001275 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Andreas Gampe628a61a2015-01-07 22:08:35 -08001276 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001277 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001278 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001279 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001280 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001281 return;
1282 }
1283
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001284 // Check whether we have and should use addr2line.
1285 bool use_addr2line;
1286 if (kUseAddr2line) {
1287 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
1288 // and print to stderr.
Andreas Gampe941c5512015-01-15 10:38:19 -08001289 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h", nullptr, nullptr);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001290 } else {
1291 use_addr2line = false;
1292 }
1293
Christopher Ferris943af7d2014-01-16 12:41:46 -08001294 for (Backtrace::const_iterator it = backtrace->begin();
1295 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001296 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001297 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1298 // In order for parsing tools to continue to function, the stack dump
1299 // format must at least adhere to this format:
1300 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1301 // The parsers require a single space before and after pc, and two spaces
1302 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1303 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1304 os << prefix << StringPrintf("#%02zu pc ", it->num);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001305 bool try_addr2line = false;
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001306 if (!BacktraceMap::IsValid(it->map)) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001307 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001308 } else {
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001309 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map.start);
1310 os << it->map.name;
Andreas Gampe3ef69b42015-01-26 10:38:34 -08001311 os << " (";
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001312 if (!it->func_name.empty()) {
1313 os << it->func_name;
1314 if (it->func_offset != 0) {
1315 os << "+" << it->func_offset;
1316 }
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001317 try_addr2line = true;
Hiroshi Yamauchi7895d552014-08-28 14:55:56 -07001318 } else if (current_method != nullptr &&
1319 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001320 current_method->PcIsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001321 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1322 os << JniLongName(current_method) << "+"
1323 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001324 } else {
1325 os << "???";
1326 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001327 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001328 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001329 os << "\n";
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001330 if (try_addr2line && use_addr2line) {
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001331 Addr2line(it->map.name, it->pc - it->map.start, os, prefix);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001332 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001333 }
Nicolas Geoffraye6ac4fd2014-11-04 13:03:29 +00001334#else
Andreas Gampe9387c722015-01-08 11:32:22 -08001335 UNUSED(os, tid, prefix, current_method, ucontext_ptr);
Ian Rogersc5f17732014-06-05 20:48:42 -07001336#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001337}
1338
Elliott Hughes058a6de2012-05-24 19:13:02 -07001339#if defined(__APPLE__)
1340
1341// TODO: is there any way to get the kernel stack on Mac OS?
1342void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1343
1344#else
1345
Elliott Hughes46e251b2012-05-22 15:10:45 -07001346void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001347 if (tid == GetTid()) {
1348 // There's no point showing that we're reading our stack out of /proc!
1349 return;
1350 }
1351
Elliott Hughes46e251b2012-05-22 15:10:45 -07001352 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1353 std::string kernel_stack;
1354 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001355 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001356 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001357 }
1358
1359 std::vector<std::string> kernel_stack_frames;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001360 Split(kernel_stack, '\n', &kernel_stack_frames);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001361 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1362 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1363 kernel_stack_frames.pop_back();
1364 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001365 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1366 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001367 const char* text = kernel_stack_frames[i].c_str();
1368 const char* close_bracket = strchr(text, ']');
1369 if (close_bracket != NULL) {
1370 text = close_bracket + 2;
1371 }
1372 os << prefix;
1373 if (include_count) {
1374 os << StringPrintf("#%02zd ", i);
1375 }
1376 os << text << "\n";
1377 }
1378}
1379
1380#endif
1381
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001382const char* GetAndroidRoot() {
1383 const char* android_root = getenv("ANDROID_ROOT");
1384 if (android_root == NULL) {
1385 if (OS::DirectoryExists("/system")) {
1386 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001387 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001388 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1389 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001390 }
1391 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001392 if (!OS::DirectoryExists(android_root)) {
1393 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001394 return "";
1395 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001396 return android_root;
1397}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001398
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001399const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001400 std::string error_msg;
1401 const char* dir = GetAndroidDataSafe(&error_msg);
1402 if (dir != nullptr) {
1403 return dir;
1404 } else {
1405 LOG(FATAL) << error_msg;
1406 return "";
1407 }
1408}
1409
1410const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001411 const char* android_data = getenv("ANDROID_DATA");
1412 if (android_data == NULL) {
1413 if (OS::DirectoryExists("/data")) {
1414 android_data = "/data";
1415 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001416 *error_msg = "ANDROID_DATA not set and /data does not exist";
1417 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001418 }
1419 }
1420 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001421 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1422 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001423 }
1424 return android_data;
1425}
1426
Alex Lighta59dd802014-07-02 16:28:08 -07001427void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001428 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001429 CHECK(subdir != nullptr);
1430 std::string error_msg;
1431 const char* android_data = GetAndroidDataSafe(&error_msg);
1432 if (android_data == nullptr) {
1433 *have_android_data = false;
1434 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001435 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001436 return;
1437 } else {
1438 *have_android_data = true;
1439 }
1440 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1441 *dalvik_cache = dalvik_cache_root + subdir;
1442 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001443 *is_global_cache = strcmp(android_data, "/data") == 0;
1444 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001445 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1446 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1447 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1448 }
1449}
1450
Narayan Kamath11d9f062014-04-23 20:24:57 +01001451std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1452 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001453 const char* android_data = GetAndroidData();
1454 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001455 const std::string dalvik_cache = dalvik_cache_root + subdir;
1456 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001457 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1458 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001459 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001460 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001461 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1462 return "";
1463 }
1464 result = mkdir(dalvik_cache.c_str(), 0700);
1465 if (result != 0) {
1466 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001467 return "";
1468 }
1469 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001470 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001471 return "";
1472 }
1473 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001474 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001475}
1476
Alex Lighta59dd802014-07-02 16:28:08 -07001477bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1478 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001479 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001480 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1481 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001482 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001483 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001484 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001485 cache_file += "/";
1486 cache_file += DexFile::kClassesDex;
1487 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001488 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001489 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1490 return true;
1491}
1492
1493std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1494 std::string ret;
1495 std::string error_msg;
1496 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1497 LOG(FATAL) << error_msg;
1498 }
1499 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001500}
1501
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001502static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001503 // in = /foo/bar/baz
1504 // out = /foo/bar/<isa>/baz
1505 size_t pos = filename->rfind('/');
1506 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1507 filename->insert(pos, "/", 1);
1508 filename->insert(pos + 1, GetInstructionSetString(isa));
1509}
1510
1511std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1512 // location = /system/framework/boot.art
1513 // filename = /system/framework/<isa>/boot.art
1514 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001515 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001516 return filename;
1517}
1518
1519std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1520 // location = /foo/bar/baz.jar
1521 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001522
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001523 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1524 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001525 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001526 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1527 CHECK_EQ('.', odex_location[dot_index]) << location;
1528 odex_location.resize(dot_index + 1);
1529 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1530 odex_location += "odex";
1531 return odex_location;
1532}
1533
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001534bool IsZipMagic(uint32_t magic) {
1535 return (('P' == ((magic >> 0) & 0xff)) &&
1536 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001537}
1538
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001539bool IsDexMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001540 return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001541}
1542
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001543bool IsOatMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001544 return (memcmp(reinterpret_cast<const uint8_t*>(magic),
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001545 OatHeader::kOatMagic,
1546 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001547}
1548
Brian Carlstrom6449c622014-02-10 23:48:36 -08001549bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1550 const std::string command_line(Join(arg_vector, ' '));
1551
1552 CHECK_GE(arg_vector.size(), 1U) << command_line;
1553
1554 // Convert the args to char pointers.
1555 const char* program = arg_vector[0].c_str();
1556 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001557 for (size_t i = 0; i < arg_vector.size(); ++i) {
1558 const std::string& arg = arg_vector[i];
1559 char* arg_str = const_cast<char*>(arg.c_str());
1560 CHECK(arg_str != nullptr) << i;
1561 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001562 }
1563 args.push_back(NULL);
1564
1565 // fork and exec
1566 pid_t pid = fork();
1567 if (pid == 0) {
1568 // no allocation allowed between fork and exec
1569
1570 // change process groups, so we don't get reaped by ProcessManager
1571 setpgid(0, 0);
1572
1573 execv(program, &args[0]);
1574
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001575 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1576 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001577 } else {
1578 if (pid == -1) {
1579 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1580 command_line.c_str(), strerror(errno));
1581 return false;
1582 }
1583
1584 // wait for subprocess to finish
1585 int status;
1586 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1587 if (got_pid != pid) {
1588 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1589 "wanted %d, got %d: %s",
1590 command_line.c_str(), pid, got_pid, strerror(errno));
1591 return false;
1592 }
1593 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1594 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1595 command_line.c_str());
1596 return false;
1597 }
1598 }
1599 return true;
1600}
1601
Tong Shen547cdfd2014-08-05 01:54:19 -07001602void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001603 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001604}
1605
1606void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001607 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001608}
1609
Mathieu Chartier76433272014-09-26 14:32:37 -07001610std::string PrettyDescriptor(Primitive::Type type) {
1611 return PrettyDescriptor(Primitive::Descriptor(type));
1612}
1613
Elliott Hughes42ee1422011-09-06 12:33:32 -07001614} // namespace art