blob: 3ec9561f4ddf6d2197a7d70838d109cc21aa4817 [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) {
Ian Rogers700a4022014-05-19 16:49:03 -0700136 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800137 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) {
Elliott Hughes76160052012-12-12 16:31:20 -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
Elliott Hughese27955c2011-08-26 15:21:24 -0700154std::string GetIsoDate() {
155 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700156 tm tmbuf;
157 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700158 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
159 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
160 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
161}
162
Elliott Hughes7162ad92011-10-27 14:08:42 -0700163uint64_t MilliTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800164#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700165 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700166 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700167 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800168#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700169 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800170 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700171 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800172#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700173}
174
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800175uint64_t MicroTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800176#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700177 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800178 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700179 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800180#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700181 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800182 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700183 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800184#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800185}
186
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700187uint64_t NanoTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800188#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700189 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700190 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700191 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0a18df82015-01-09 15:16:16 -0800192#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700193 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800194 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700195 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800196#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700197}
198
Elliott Hughes0512f022012-03-15 22:10:52 -0700199uint64_t ThreadCpuNanoTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800200#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700201 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700202 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700203 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0a18df82015-01-09 15:16:16 -0800204#else // __APPLE__
Elliott Hughes0512f022012-03-15 22:10:52 -0700205 UNIMPLEMENTED(WARNING);
206 return -1;
207#endif
208}
209
Ian Rogers56edc432013-01-18 16:51:51 -0800210void NanoSleep(uint64_t ns) {
211 timespec tm;
212 tm.tv_sec = 0;
213 tm.tv_nsec = ns;
214 nanosleep(&tm, NULL);
215}
216
Brian Carlstrombcc29262012-11-02 11:36:03 -0700217void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
218 int64_t endSec;
219
220 if (absolute) {
221#if !defined(__APPLE__)
222 clock_gettime(clock, ts);
223#else
224 UNUSED(clock);
225 timeval tv;
226 gettimeofday(&tv, NULL);
227 ts->tv_sec = tv.tv_sec;
228 ts->tv_nsec = tv.tv_usec * 1000;
229#endif
230 } else {
231 ts->tv_sec = 0;
232 ts->tv_nsec = 0;
233 }
234 endSec = ts->tv_sec + ms / 1000;
235 if (UNLIKELY(endSec >= 0x7fffffff)) {
236 std::ostringstream ss;
237 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
238 endSec = 0x7ffffffe;
239 }
240 ts->tv_sec = endSec;
241 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
242
243 // Catch rollover.
244 if (ts->tv_nsec >= 1000000000L) {
245 ts->tv_sec++;
246 ts->tv_nsec -= 1000000000L;
247 }
248}
249
Ian Rogersef7d42f2014-01-06 12:55:46 -0800250std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700251 if (java_descriptor == NULL) {
252 return "null";
253 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700254 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700255}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700256
Ian Rogersef7d42f2014-01-06 12:55:46 -0800257std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800258 if (klass == NULL) {
259 return "null";
260 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700261 std::string temp;
262 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800263}
264
Ian Rogers1ff3c982014-08-12 02:30:58 -0700265std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700266 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700267 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700268 size_t dim = 0;
269 while (*c == '[') {
270 dim++;
271 c++;
272 }
273
274 // Reference or primitive?
275 if (*c == 'L') {
276 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700277 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700278 } else {
279 // "[[B" -> "byte[][]".
280 // To make life easier, we make primitives look like unqualified
281 // reference types.
282 switch (*c) {
283 case 'B': c = "byte;"; break;
284 case 'C': c = "char;"; break;
285 case 'D': c = "double;"; break;
286 case 'F': c = "float;"; break;
287 case 'I': c = "int;"; break;
288 case 'J': c = "long;"; break;
289 case 'S': c = "short;"; break;
290 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700291 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700292 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700293 }
294 }
295
296 // At this point, 'c' is a string of the form "fully/qualified/Type;"
297 // or "primitive;". Rewrite the type with '.' instead of '/':
298 std::string result;
299 const char* p = c;
300 while (*p != ';') {
301 char ch = *p++;
302 if (ch == '/') {
303 ch = '.';
304 }
305 result.push_back(ch);
306 }
307 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700308 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700309 result += "[]";
310 }
311 return result;
312}
313
Ian Rogersef7d42f2014-01-06 12:55:46 -0800314std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700315 if (f == NULL) {
316 return "null";
317 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700318 std::string result;
319 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700320 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700321 result += ' ';
322 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800323 std::string temp;
324 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700325 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700326 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700327 return result;
328}
329
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700330std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800331 if (field_idx >= dex_file.NumFieldIds()) {
332 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
333 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700334 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
335 std::string result;
336 if (with_type) {
337 result += dex_file.GetFieldTypeDescriptor(field_id);
338 result += ' ';
339 }
340 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
341 result += '.';
342 result += dex_file.GetFieldName(field_id);
343 return result;
344}
345
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700346std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800347 if (type_idx >= dex_file.NumTypeIds()) {
348 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
349 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700350 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700351 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700352}
353
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700354std::string PrettyArguments(const char* signature) {
355 std::string result;
356 result += '(';
357 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700358 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700359 while (*signature != ')') {
360 size_t argument_length = 0;
361 while (signature[argument_length] == '[') {
362 ++argument_length;
363 }
364 if (signature[argument_length] == 'L') {
365 argument_length = (strchr(signature, ';') - signature + 1);
366 } else {
367 ++argument_length;
368 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700369 {
370 std::string argument_descriptor(signature, argument_length);
371 result += PrettyDescriptor(argument_descriptor.c_str());
372 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700373 if (signature[argument_length] != ')') {
374 result += ", ";
375 }
376 signature += argument_length;
377 }
378 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700379 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700380 result += ')';
381 return result;
382}
383
384std::string PrettyReturnType(const char* signature) {
385 const char* return_type = strchr(signature, ')');
386 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700387 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700388 return PrettyDescriptor(return_type);
389}
390
Ian Rogersef7d42f2014-01-06 12:55:46 -0800391std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800392 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700393 return "null";
394 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700395 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700396 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700397 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800398 if (UNLIKELY(m->IsFastNative())) {
399 result += "!";
400 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700401 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700402 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700403 std::string sig_as_string(signature.ToString());
404 if (signature == Signature::NoSignature()) {
405 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700406 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700407 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
408 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700409 }
410 return result;
411}
412
Ian Rogers0571d352011-11-03 19:51:38 -0700413std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800414 if (method_idx >= dex_file.NumMethodIds()) {
415 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
416 }
Ian Rogers0571d352011-11-03 19:51:38 -0700417 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
418 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
419 result += '.';
420 result += dex_file.GetMethodName(method_id);
421 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700422 const Signature signature = dex_file.GetMethodSignature(method_id);
423 std::string sig_as_string(signature.ToString());
424 if (signature == Signature::NoSignature()) {
425 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700426 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700427 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
428 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700429 }
430 return result;
431}
432
Ian Rogersef7d42f2014-01-06 12:55:46 -0800433std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700434 if (obj == NULL) {
435 return "null";
436 }
437 if (obj->GetClass() == NULL) {
438 return "(raw)";
439 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700440 std::string temp;
441 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700442 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700443 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700444 }
445 return result;
446}
447
Ian Rogersef7d42f2014-01-06 12:55:46 -0800448std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700449 if (c == NULL) {
450 return "null";
451 }
452 std::string result;
453 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800454 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700455 result += ">";
456 return result;
457}
458
Ian Rogersef7d42f2014-01-06 12:55:46 -0800459std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700460 if (c == NULL) {
461 return "null";
462 }
463 std::string result;
464 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800465 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700466 result += ",";
467 result += PrettyTypeOf(c->GetClassLoader());
468 // TODO: add an identifying hash value for the loader
469 result += ">";
470 return result;
471}
472
Andreas Gampec0d82292014-09-23 10:38:30 -0700473std::string PrettyJavaAccessFlags(uint32_t access_flags) {
474 std::string result;
475 if ((access_flags & kAccPublic) != 0) {
476 result += "public ";
477 }
478 if ((access_flags & kAccProtected) != 0) {
479 result += "protected ";
480 }
481 if ((access_flags & kAccPrivate) != 0) {
482 result += "private ";
483 }
484 if ((access_flags & kAccFinal) != 0) {
485 result += "final ";
486 }
487 if ((access_flags & kAccStatic) != 0) {
488 result += "static ";
489 }
490 if ((access_flags & kAccTransient) != 0) {
491 result += "transient ";
492 }
493 if ((access_flags & kAccVolatile) != 0) {
494 result += "volatile ";
495 }
496 if ((access_flags & kAccSynchronized) != 0) {
497 result += "synchronized ";
498 }
499 return result;
500}
501
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800502std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700503 // The byte thresholds at which we display amounts. A byte count is displayed
504 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800505 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700506 0, // B up to...
507 3*1024, // KB up to...
508 2*1024*1024, // MB up to...
509 1024*1024*1024 // GB from here.
510 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800511 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700512 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800513 const char* negative_str = "";
514 if (byte_count < 0) {
515 negative_str = "-";
516 byte_count = -byte_count;
517 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700518 int i = arraysize(kUnitThresholds);
519 while (--i > 0) {
520 if (byte_count >= kUnitThresholds[i]) {
521 break;
522 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800523 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800524 return StringPrintf("%s%" PRId64 "%s",
525 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800526}
527
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700528std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800529 if (nano_duration == 0) {
530 return "0";
531 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700532 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
533 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700534 }
535}
536
537TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
538 const uint64_t one_sec = 1000 * 1000 * 1000;
539 const uint64_t one_ms = 1000 * 1000;
540 const uint64_t one_us = 1000;
541 if (nano_duration >= one_sec) {
542 return kTimeUnitSecond;
543 } else if (nano_duration >= one_ms) {
544 return kTimeUnitMillisecond;
545 } else if (nano_duration >= one_us) {
546 return kTimeUnitMicrosecond;
547 } else {
548 return kTimeUnitNanosecond;
549 }
550}
551
552uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
553 const uint64_t one_sec = 1000 * 1000 * 1000;
554 const uint64_t one_ms = 1000 * 1000;
555 const uint64_t one_us = 1000;
556
557 switch (time_unit) {
558 case kTimeUnitSecond:
559 return one_sec;
560 case kTimeUnitMillisecond:
561 return one_ms;
562 case kTimeUnitMicrosecond:
563 return one_us;
564 case kTimeUnitNanosecond:
565 return 1;
566 }
567 return 0;
568}
569
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700570std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
571 size_t max_fraction_digits) {
572 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700573 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700574 switch (time_unit) {
575 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800576 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700577 break;
578 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800579 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700580 break;
581 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800582 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700583 break;
584 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800585 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700586 break;
587 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700588 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700589 uint64_t fractional_part = nano_duration % divisor;
590 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800591 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700592 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700593 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700594 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700595 char fraction_buffer[kMaxDigits];
596 char* ptr = fraction_buffer;
597 uint64_t multiplier = 10;
598 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700599 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700600 multiplier *= 10;
601 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700602 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800603 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700604 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700605 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
606 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800607 }
608}
609
Ian Rogers576ca0c2014-06-06 15:58:22 -0700610std::string PrintableChar(uint16_t ch) {
611 std::string result;
612 result += '\'';
613 if (NeedsEscaping(ch)) {
614 StringAppendF(&result, "\\u%04x", ch);
615 } else {
616 result += ch;
617 }
618 result += '\'';
619 return result;
620}
621
Ian Rogers68b56852014-08-29 20:19:11 -0700622std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700623 std::string result;
624 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700625 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700626 size_t char_count = CountModifiedUtf8Chars(p);
627 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000628 uint32_t ch = GetUtf16FromUtf8(&p);
Elliott Hughes82914b62012-04-09 15:56:29 -0700629 if (ch == '\\') {
630 result += "\\\\";
631 } else if (ch == '\n') {
632 result += "\\n";
633 } else if (ch == '\r') {
634 result += "\\r";
635 } else if (ch == '\t') {
636 result += "\\t";
Elliott Hughes82914b62012-04-09 15:56:29 -0700637 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000638 const uint16_t leading = GetLeadingUtf16Char(ch);
639
640 if (NeedsEscaping(leading)) {
641 StringAppendF(&result, "\\u%04x", leading);
642 } else {
643 result += leading;
644 }
645
646 const uint32_t trailing = GetTrailingUtf16Char(ch);
647 if (trailing != 0) {
648 // All high surrogates will need escaping.
649 StringAppendF(&result, "\\u%04x", trailing);
650 }
Elliott Hughes82914b62012-04-09 15:56:29 -0700651 }
652 }
653 result += '"';
654 return result;
655}
656
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800657// 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 -0700658std::string MangleForJni(const std::string& s) {
659 std::string result;
660 size_t char_count = CountModifiedUtf8Chars(s.c_str());
661 const char* cp = &s[0];
662 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000663 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800664 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
665 result.push_back(ch);
666 } else if (ch == '.' || ch == '/') {
667 result += "_";
668 } else if (ch == '_') {
669 result += "_1";
670 } else if (ch == ';') {
671 result += "_2";
672 } else if (ch == '[') {
673 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700674 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000675 const uint16_t leading = GetLeadingUtf16Char(ch);
676 const uint32_t trailing = GetTrailingUtf16Char(ch);
677
678 StringAppendF(&result, "_0%04x", leading);
679 if (trailing != 0) {
680 StringAppendF(&result, "_0%04x", trailing);
681 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700682 }
683 }
684 return result;
685}
686
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700687std::string DotToDescriptor(const char* class_name) {
688 std::string descriptor(class_name);
689 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
690 if (descriptor.length() > 0 && descriptor[0] != '[') {
691 descriptor = "L" + descriptor + ";";
692 }
693 return descriptor;
694}
695
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800696std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800697 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700698 if (length > 1) {
699 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
700 // Descriptors have the leading 'L' and trailing ';' stripped.
701 std::string result(descriptor + 1, length - 2);
702 std::replace(result.begin(), result.end(), '/', '.');
703 return result;
704 } else {
705 // For arrays the 'L' and ';' remain intact.
706 std::string result(descriptor);
707 std::replace(result.begin(), result.end(), '/', '.');
708 return result;
709 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800710 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700711 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800712 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800713}
714
715std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800716 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800717 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
718 std::string result(descriptor + 1, length - 2);
719 return result;
720 }
721 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700722}
723
Ian Rogersef7d42f2014-01-06 12:55:46 -0800724std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700725 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700726 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700727 CHECK_EQ(class_name[0], 'L') << class_name;
728 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700729 class_name.erase(0, 1);
730 class_name.erase(class_name.size() - 1, 1);
731
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700732 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700733
734 std::string short_name;
735 short_name += "Java_";
736 short_name += MangleForJni(class_name);
737 short_name += "_";
738 short_name += MangleForJni(method_name);
739 return short_name;
740}
741
Ian Rogersef7d42f2014-01-06 12:55:46 -0800742std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700743 std::string long_name;
744 long_name += JniShortName(m);
745 long_name += "__";
746
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700747 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700748 signature.erase(0, 1);
749 signature.erase(signature.begin() + signature.find(')'), signature.end());
750
751 long_name += MangleForJni(signature);
752
753 return long_name;
754}
755
jeffhao10037c82012-01-23 15:06:23 -0800756// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700757uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700758 0x00000000, // 00..1f low control characters; nothing valid
759 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
760 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
761 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700762};
763
jeffhao10037c82012-01-23 15:06:23 -0800764// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
765bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700766 /*
767 * It's a multibyte encoded character. Decode it and analyze. We
768 * accept anything that isn't (a) an improperly encoded low value,
769 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
770 * control character, or (e) a high space, layout, or special
771 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
772 * U+fff0..U+ffff). This is all specified in the dex format
773 * document.
774 */
775
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000776 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700777
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000778 const uint16_t leading = GetLeadingUtf16Char(pair);
779 const uint32_t trailing = GetTrailingUtf16Char(pair);
780
781 if (trailing == 0) {
782 // Perform follow-up tests based on the high 8 bits of the
783 // lower surrogate.
784 switch (leading >> 8) {
785 case 0x00:
786 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
787 return (leading > 0x00a0);
788 case 0xd8:
789 case 0xd9:
790 case 0xda:
791 case 0xdb:
792 // It looks like a leading surrogate but we didn't find a trailing
793 // surrogate if we're here.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700794 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000795 case 0xdc:
796 case 0xdd:
797 case 0xde:
798 case 0xdf:
799 // It's a trailing surrogate, which is not valid at this point.
800 return false;
801 case 0x20:
802 case 0xff:
803 // It's in the range that has spaces, controls, and specials.
804 switch (leading & 0xfff8) {
805 case 0x2000:
806 case 0x2008:
807 case 0x2028:
808 case 0xfff0:
809 case 0xfff8:
810 return false;
811 }
812 break;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700813 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000814
815 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700816 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000817
818 // We have a surrogate pair. Check that trailing surrogate is well formed.
819 return (trailing >= 0xdc00 && trailing <= 0xdfff);
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700820}
821
822/* Return whether the pointed-at modified-UTF-8 encoded character is
823 * valid as part of a member name, updating the pointer to point past
824 * the consumed character. This will consume two encoded UTF-16 code
825 * points if the character is encoded as a surrogate pair. Also, if
826 * this function returns false, then the given pointer may only have
827 * been partially advanced.
828 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700829static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700830 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700831 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700832 // It's low-ascii, so check the table.
833 uint32_t wordIdx = c >> 5;
834 uint32_t bitIdx = c & 0x1f;
835 (*pUtf8Ptr)++;
836 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
837 }
838
839 // It's a multibyte encoded character. Call a non-inline function
840 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800841 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
842}
843
844bool IsValidMemberName(const char* s) {
845 bool angle_name = false;
846
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700847 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800848 case '\0':
849 // The empty string is not a valid name.
850 return false;
851 case '<':
852 angle_name = true;
853 s++;
854 break;
855 }
856
857 while (true) {
858 switch (*s) {
859 case '\0':
860 return !angle_name;
861 case '>':
862 return angle_name && s[1] == '\0';
863 }
864
865 if (!IsValidPartOfMemberNameUtf8(&s)) {
866 return false;
867 }
868 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700869}
870
Elliott Hughes906e6852011-10-28 14:52:10 -0700871enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700872template<ClassNameType kType, char kSeparator>
873static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700874 int arrayCount = 0;
875 while (*s == '[') {
876 arrayCount++;
877 s++;
878 }
879
880 if (arrayCount > 255) {
881 // Arrays may have no more than 255 dimensions.
882 return false;
883 }
884
Ian Rogers7b078e82014-09-10 14:44:24 -0700885 ClassNameType type = kType;
886 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700887 /*
888 * If we're looking at an array of some sort, then it doesn't
889 * matter if what is being asked for is a class name; the
890 * format looks the same as a type descriptor in that case, so
891 * treat it as such.
892 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700893 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700894 }
895
Elliott Hughes906e6852011-10-28 14:52:10 -0700896 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700897 /*
898 * We are looking for a descriptor. Either validate it as a
899 * single-character primitive type, or continue on to check the
900 * embedded class name (bracketed by "L" and ";").
901 */
902 switch (*(s++)) {
903 case 'B':
904 case 'C':
905 case 'D':
906 case 'F':
907 case 'I':
908 case 'J':
909 case 'S':
910 case 'Z':
911 // These are all single-character descriptors for primitive types.
912 return (*s == '\0');
913 case 'V':
914 // Non-array void is valid, but you can't have an array of void.
915 return (arrayCount == 0) && (*s == '\0');
916 case 'L':
917 // Class name: Break out and continue below.
918 break;
919 default:
920 // Oddball descriptor character.
921 return false;
922 }
923 }
924
925 /*
926 * We just consumed the 'L' that introduces a class name as part
927 * of a type descriptor, or we are looking for an unadorned class
928 * name.
929 */
930
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700931 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700932 for (;;) {
933 uint8_t c = (uint8_t) *s;
934 switch (c) {
935 case '\0':
936 /*
937 * Premature end for a type descriptor, but valid for
938 * a class name as long as we haven't encountered an
939 * empty component (including the degenerate case of
940 * the empty string "").
941 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700942 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700943 case ';':
944 /*
945 * Invalid character for a class name, but the
946 * legitimate end of a type descriptor. In the latter
947 * case, make sure that this is the end of the string
948 * and that it doesn't end with an empty component
949 * (including the degenerate case of "L;").
950 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700951 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700952 case '/':
953 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700954 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700955 // The wrong separator character.
956 return false;
957 }
958 if (sepOrFirst) {
959 // Separator at start or two separators in a row.
960 return false;
961 }
962 sepOrFirst = true;
963 s++;
964 break;
965 default:
jeffhao10037c82012-01-23 15:06:23 -0800966 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700967 return false;
968 }
969 sepOrFirst = false;
970 break;
971 }
972 }
973}
974
Elliott Hughes906e6852011-10-28 14:52:10 -0700975bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700976 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700977}
978
979bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700980 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700981}
982
983bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700984 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700985}
986
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700987void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700988 const char* p = s.data();
989 const char* end = p + s.size();
990 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800991 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700992 ++p;
993 } else {
994 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800995 while (++p != end && *p != separator) {
996 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700997 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700998 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700999 }
1000 }
1001}
1002
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001003std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -07001004 std::string result;
1005 unsigned int start_index = 0;
1006 unsigned int end_index = s.size() - 1;
1007
1008 // Skip initial whitespace.
1009 while (start_index < s.size()) {
1010 if (!isspace(s[start_index])) {
1011 break;
1012 }
1013 start_index++;
1014 }
1015
1016 // Skip terminating whitespace.
1017 while (end_index >= start_index) {
1018 if (!isspace(s[end_index])) {
1019 break;
1020 }
1021 end_index--;
1022 }
1023
1024 // All spaces, no beef.
1025 if (end_index < start_index) {
1026 return "";
1027 }
1028 // Start_index is the first non-space, end_index is the last one.
1029 return s.substr(start_index, end_index - start_index + 1);
1030}
1031
Elliott Hughes48436bb2012-02-07 15:23:28 -08001032template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001033std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -08001034 if (strings.empty()) {
1035 return "";
1036 }
1037
1038 std::string result(strings[0]);
1039 for (size_t i = 1; i < strings.size(); ++i) {
1040 result += separator;
1041 result += strings[i];
1042 }
1043 return result;
1044}
1045
1046// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001047template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
1048template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -08001049
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001050bool StartsWith(const std::string& s, const char* prefix) {
1051 return s.compare(0, strlen(prefix), prefix) == 0;
1052}
1053
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001054bool EndsWith(const std::string& s, const char* suffix) {
1055 size_t suffix_length = strlen(suffix);
1056 size_t string_length = s.size();
1057 if (suffix_length > string_length) {
1058 return false;
1059 }
1060 size_t offset = string_length - suffix_length;
1061 return s.compare(offset, suffix_length, suffix) == 0;
1062}
1063
Elliott Hughes22869a92012-03-27 14:08:24 -07001064void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -07001065 int hasAt = 0;
1066 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -07001067 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001068 while (*s) {
1069 if (*s == '.') {
1070 hasDot = 1;
1071 } else if (*s == '@') {
1072 hasAt = 1;
1073 }
1074 s++;
1075 }
Elliott Hughes22869a92012-03-27 14:08:24 -07001076 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001077 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -07001078 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001079 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001080 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001081 }
Elliott Hughes0a18df82015-01-09 15:16:16 -08001082#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001083 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -08001084 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001085 strncpy(buf, s, sizeof(buf)-1);
1086 buf[sizeof(buf)-1] = '\0';
1087 errno = pthread_setname_np(pthread_self(), buf);
1088 if (errno != 0) {
1089 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1090 }
Elliott Hughes0a18df82015-01-09 15:16:16 -08001091#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -07001092 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001093#endif
1094}
1095
Brian Carlstrom29212012013-09-12 22:18:30 -07001096void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1097 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001098 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001099 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001100 return;
1101 }
1102 // Skip the command, which may contain spaces.
1103 stats = stats.substr(stats.find(')') + 2);
1104 // Extract the three fields we care about.
1105 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001106 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001107 *state = fields[0][0];
1108 *utime = strtoull(fields[11].c_str(), NULL, 10);
1109 *stime = strtoull(fields[12].c_str(), NULL, 10);
1110 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001111}
1112
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001113std::string GetSchedulerGroupName(pid_t tid) {
1114 // /proc/<pid>/cgroup looks like this:
1115 // 2:devices:/
1116 // 1:cpuacct,cpu:/
1117 // We want the third field from the line whose second field contains the "cpu" token.
1118 std::string cgroup_file;
1119 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1120 return "";
1121 }
1122 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001123 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001124 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1125 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001126 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001127 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001128 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001129 for (size_t j = 0; j < cgroups.size(); ++j) {
1130 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001131 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001132 }
1133 }
1134 }
1135 return "";
1136}
1137
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001138#if defined(__linux__)
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001139
1140ALWAYS_INLINE
1141static inline void WritePrefix(std::ostream* os, const char* prefix, bool odd) {
1142 if (prefix != nullptr) {
1143 *os << prefix;
1144 }
1145 *os << " ";
1146 if (!odd) {
1147 *os << " ";
1148 }
1149}
1150
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001151static bool RunCommand(std::string cmd, std::ostream* os, const char* prefix) {
1152 FILE* stream = popen(cmd.c_str(), "r");
1153 if (stream) {
1154 if (os != nullptr) {
1155 bool odd_line = true; // We indent them differently.
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001156 bool wrote_prefix = false; // Have we already written a prefix?
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001157 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
1158 // alt stack, but just to be sure...
1159 char buffer[kMaxBuffer];
1160 while (!feof(stream)) {
1161 if (fgets(buffer, kMaxBuffer, stream) != nullptr) {
1162 // Split on newlines.
1163 char* tmp = buffer;
1164 for (;;) {
1165 char* new_line = strchr(tmp, '\n');
1166 if (new_line == nullptr) {
1167 // Print the rest.
1168 if (*tmp != 0) {
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001169 if (!wrote_prefix) {
1170 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001171 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001172 wrote_prefix = true;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001173 *os << tmp;
1174 }
1175 break;
1176 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001177 if (!wrote_prefix) {
1178 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001179 }
1180 char saved = *(new_line + 1);
1181 *(new_line + 1) = 0;
1182 *os << tmp;
1183 *(new_line + 1) = saved;
1184 tmp = new_line + 1;
1185 odd_line = !odd_line;
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001186 wrote_prefix = false;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001187 }
1188 }
1189 }
1190 }
1191 pclose(stream);
1192 return true;
1193 } else {
1194 return false;
1195 }
1196}
1197
1198static void Addr2line(const std::string& map_src, uintptr_t offset, std::ostream& os,
1199 const char* prefix) {
1200 std::string cmdline(StringPrintf("addr2line --functions --inlines --demangle -e %s %zx",
1201 map_src.c_str(), offset));
1202 RunCommand(cmdline.c_str(), &os, prefix);
1203}
1204#endif
1205
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001206void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Andreas Gampe628a61a2015-01-07 22:08:35 -08001207 mirror::ArtMethod* current_method, void* ucontext_ptr) {
Ian Rogers83597d02014-11-20 10:29:00 -08001208#if __linux__
Andreas Gamped7576322014-10-24 22:13:45 -07001209 // b/18119146
1210 if (RUNNING_ON_VALGRIND != 0) {
1211 return;
1212 }
1213
Ian Rogersedfdaf32014-12-05 16:12:21 +00001214#if !defined(HAVE_ANDROID_OS)
1215 if (GetTid() != tid) {
1216 // TODO: dumping of other threads is disabled to avoid crashes during stress testing.
1217 // b/15446488.
1218 return;
1219 }
1220#endif
1221
Ian Rogers700a4022014-05-19 16:49:03 -07001222 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Andreas Gampe628a61a2015-01-07 22:08:35 -08001223 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001224 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001225 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001226 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001227 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001228 return;
1229 }
1230
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001231 // Check whether we have and should use addr2line.
1232 bool use_addr2line;
1233 if (kUseAddr2line) {
1234 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
1235 // and print to stderr.
Andreas Gampe941c5512015-01-15 10:38:19 -08001236 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h", nullptr, nullptr);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001237 } else {
1238 use_addr2line = false;
1239 }
1240
Christopher Ferris943af7d2014-01-16 12:41:46 -08001241 for (Backtrace::const_iterator it = backtrace->begin();
1242 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001243 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001244 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1245 // In order for parsing tools to continue to function, the stack dump
1246 // format must at least adhere to this format:
1247 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1248 // The parsers require a single space before and after pc, and two spaces
1249 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1250 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1251 os << prefix << StringPrintf("#%02zu pc ", it->num);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001252 bool try_addr2line = false;
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001253 if (!BacktraceMap::IsValid(it->map)) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001254 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001255 } else {
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001256 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map.start);
1257 os << it->map.name;
Andreas Gampe3ef69b42015-01-26 10:38:34 -08001258 os << " (";
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001259 if (!it->func_name.empty()) {
1260 os << it->func_name;
1261 if (it->func_offset != 0) {
1262 os << "+" << it->func_offset;
1263 }
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001264 try_addr2line = true;
Hiroshi Yamauchi7895d552014-08-28 14:55:56 -07001265 } else if (current_method != nullptr &&
1266 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001267 current_method->PcIsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001268 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1269 os << JniLongName(current_method) << "+"
1270 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001271 } else {
1272 os << "???";
1273 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001274 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001275 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001276 os << "\n";
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001277 if (try_addr2line && use_addr2line) {
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001278 Addr2line(it->map.name, it->pc - it->map.start, os, prefix);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001279 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001280 }
Nicolas Geoffraye6ac4fd2014-11-04 13:03:29 +00001281#else
Andreas Gampe9387c722015-01-08 11:32:22 -08001282 UNUSED(os, tid, prefix, current_method, ucontext_ptr);
Ian Rogersc5f17732014-06-05 20:48:42 -07001283#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001284}
1285
Elliott Hughes058a6de2012-05-24 19:13:02 -07001286#if defined(__APPLE__)
1287
1288// TODO: is there any way to get the kernel stack on Mac OS?
1289void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1290
1291#else
1292
Elliott Hughes46e251b2012-05-22 15:10:45 -07001293void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001294 if (tid == GetTid()) {
1295 // There's no point showing that we're reading our stack out of /proc!
1296 return;
1297 }
1298
Elliott Hughes46e251b2012-05-22 15:10:45 -07001299 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1300 std::string kernel_stack;
1301 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001302 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001303 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001304 }
1305
1306 std::vector<std::string> kernel_stack_frames;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001307 Split(kernel_stack, '\n', &kernel_stack_frames);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001308 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1309 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1310 kernel_stack_frames.pop_back();
1311 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001312 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1313 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001314 const char* text = kernel_stack_frames[i].c_str();
1315 const char* close_bracket = strchr(text, ']');
1316 if (close_bracket != NULL) {
1317 text = close_bracket + 2;
1318 }
1319 os << prefix;
1320 if (include_count) {
1321 os << StringPrintf("#%02zd ", i);
1322 }
1323 os << text << "\n";
1324 }
1325}
1326
1327#endif
1328
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001329const char* GetAndroidRoot() {
1330 const char* android_root = getenv("ANDROID_ROOT");
1331 if (android_root == NULL) {
1332 if (OS::DirectoryExists("/system")) {
1333 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001334 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001335 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1336 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001337 }
1338 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001339 if (!OS::DirectoryExists(android_root)) {
1340 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001341 return "";
1342 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001343 return android_root;
1344}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001345
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001346const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001347 std::string error_msg;
1348 const char* dir = GetAndroidDataSafe(&error_msg);
1349 if (dir != nullptr) {
1350 return dir;
1351 } else {
1352 LOG(FATAL) << error_msg;
1353 return "";
1354 }
1355}
1356
1357const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001358 const char* android_data = getenv("ANDROID_DATA");
1359 if (android_data == NULL) {
1360 if (OS::DirectoryExists("/data")) {
1361 android_data = "/data";
1362 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001363 *error_msg = "ANDROID_DATA not set and /data does not exist";
1364 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001365 }
1366 }
1367 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001368 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1369 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001370 }
1371 return android_data;
1372}
1373
Alex Lighta59dd802014-07-02 16:28:08 -07001374void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001375 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001376 CHECK(subdir != nullptr);
1377 std::string error_msg;
1378 const char* android_data = GetAndroidDataSafe(&error_msg);
1379 if (android_data == nullptr) {
1380 *have_android_data = false;
1381 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001382 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001383 return;
1384 } else {
1385 *have_android_data = true;
1386 }
1387 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1388 *dalvik_cache = dalvik_cache_root + subdir;
1389 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001390 *is_global_cache = strcmp(android_data, "/data") == 0;
1391 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001392 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1393 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1394 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1395 }
1396}
1397
Narayan Kamath11d9f062014-04-23 20:24:57 +01001398std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1399 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001400 const char* android_data = GetAndroidData();
1401 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001402 const std::string dalvik_cache = dalvik_cache_root + subdir;
1403 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001404 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1405 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001406 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001407 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001408 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1409 return "";
1410 }
1411 result = mkdir(dalvik_cache.c_str(), 0700);
1412 if (result != 0) {
1413 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001414 return "";
1415 }
1416 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001417 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001418 return "";
1419 }
1420 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001421 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001422}
1423
Alex Lighta59dd802014-07-02 16:28:08 -07001424bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1425 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001426 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001427 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1428 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001429 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001430 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001431 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001432 cache_file += "/";
1433 cache_file += DexFile::kClassesDex;
1434 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001435 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001436 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1437 return true;
1438}
1439
1440std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1441 std::string ret;
1442 std::string error_msg;
1443 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1444 LOG(FATAL) << error_msg;
1445 }
1446 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001447}
1448
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001449static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001450 // in = /foo/bar/baz
1451 // out = /foo/bar/<isa>/baz
1452 size_t pos = filename->rfind('/');
1453 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1454 filename->insert(pos, "/", 1);
1455 filename->insert(pos + 1, GetInstructionSetString(isa));
1456}
1457
1458std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1459 // location = /system/framework/boot.art
1460 // filename = /system/framework/<isa>/boot.art
1461 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001462 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001463 return filename;
1464}
1465
1466std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1467 // location = /foo/bar/baz.jar
1468 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001469
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001470 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1471 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001472 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001473 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1474 CHECK_EQ('.', odex_location[dot_index]) << location;
1475 odex_location.resize(dot_index + 1);
1476 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1477 odex_location += "odex";
1478 return odex_location;
1479}
1480
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001481bool IsZipMagic(uint32_t magic) {
1482 return (('P' == ((magic >> 0) & 0xff)) &&
1483 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001484}
1485
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001486bool IsDexMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001487 return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001488}
1489
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001490bool IsOatMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001491 return (memcmp(reinterpret_cast<const uint8_t*>(magic),
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001492 OatHeader::kOatMagic,
1493 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001494}
1495
Brian Carlstrom6449c622014-02-10 23:48:36 -08001496bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1497 const std::string command_line(Join(arg_vector, ' '));
1498
1499 CHECK_GE(arg_vector.size(), 1U) << command_line;
1500
1501 // Convert the args to char pointers.
1502 const char* program = arg_vector[0].c_str();
1503 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001504 for (size_t i = 0; i < arg_vector.size(); ++i) {
1505 const std::string& arg = arg_vector[i];
1506 char* arg_str = const_cast<char*>(arg.c_str());
1507 CHECK(arg_str != nullptr) << i;
1508 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001509 }
1510 args.push_back(NULL);
1511
1512 // fork and exec
1513 pid_t pid = fork();
1514 if (pid == 0) {
1515 // no allocation allowed between fork and exec
1516
1517 // change process groups, so we don't get reaped by ProcessManager
1518 setpgid(0, 0);
1519
1520 execv(program, &args[0]);
1521
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001522 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1523 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001524 } else {
1525 if (pid == -1) {
1526 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1527 command_line.c_str(), strerror(errno));
1528 return false;
1529 }
1530
1531 // wait for subprocess to finish
1532 int status;
1533 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1534 if (got_pid != pid) {
1535 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1536 "wanted %d, got %d: %s",
1537 command_line.c_str(), pid, got_pid, strerror(errno));
1538 return false;
1539 }
1540 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1541 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1542 command_line.c_str());
1543 return false;
1544 }
1545 }
1546 return true;
1547}
1548
Tong Shen547cdfd2014-08-05 01:54:19 -07001549void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001550 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001551}
1552
1553void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001554 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001555}
1556
1557void PushWord(std::vector<uint8_t>* buf, int data) {
1558 buf->push_back(data & 0xff);
1559 buf->push_back((data >> 8) & 0xff);
1560 buf->push_back((data >> 16) & 0xff);
1561 buf->push_back((data >> 24) & 0xff);
1562}
1563
Mathieu Chartier76433272014-09-26 14:32:37 -07001564std::string PrettyDescriptor(Primitive::Type type) {
1565 return PrettyDescriptor(Primitive::Descriptor(type));
1566}
1567
Elliott Hughes42ee1422011-09-06 12:33:32 -07001568} // namespace art