blob: be735882c3a768b612725fdade5305b6eb15913d [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
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080056pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070057#if defined(__APPLE__)
58 uint64_t owner;
59 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
60 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070061#elif defined(__BIONIC__)
62 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080063#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080064 return syscall(__NR_gettid);
65#endif
66}
67
Elliott Hughes289be852012-06-12 13:57:20 -070068std::string GetThreadName(pid_t tid) {
69 std::string result;
70 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070071 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070072 } else {
73 result = "<unknown>";
74 }
75 return result;
76}
77
Elliott Hughes6d3fc562014-08-27 11:47:01 -070078void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070079#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070080 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070081 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070082
83 // Check whether stack_addr is the base or end of the stack.
84 // (On Mac OS 10.7, it's the end.)
85 int stack_variable;
86 if (stack_addr > &stack_variable) {
Ian Rogers13735952014-10-08 12:43:28 -070087 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070088 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070089 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070090 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070091
92 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
93 pthread_attr_t attributes;
94 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
95 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
96 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070097#else
98 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070099 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700100 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700101 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700102 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700103
104#if defined(__GLIBC__)
105 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
106 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
107 // will be broken because we'll die long before we get close to 2GB.
108 bool is_main_thread = (::art::GetTid() == getpid());
109 if (is_main_thread) {
110 rlimit stack_limit;
111 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
112 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
113 }
114 if (stack_limit.rlim_cur == RLIM_INFINITY) {
115 size_t old_stack_size = *stack_size;
116
117 // Use the kernel default limit as our size, and adjust the base to match.
118 *stack_size = 8 * MB;
119 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
120
121 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
122 << " to " << PrettySize(*stack_size)
123 << " with base " << *stack_base;
124 }
125 }
126#endif
127
Elliott Hughese1884192012-04-23 12:38:15 -0700128#endif
129}
130
Elliott Hughesd92bec42011-09-02 17:04:36 -0700131bool ReadFileToString(const std::string& file_name, std::string* result) {
Ian Rogers700a4022014-05-19 16:49:03 -0700132 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800133 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700134 return false;
135 }
buzbeec143c552011-08-20 17:38:58 -0700136
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700137 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700138 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800139 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700140 if (n == -1) {
141 return false;
buzbeec143c552011-08-20 17:38:58 -0700142 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700143 if (n == 0) {
144 return true;
145 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700146 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700147 }
buzbeec143c552011-08-20 17:38:58 -0700148}
149
Elliott Hughese27955c2011-08-26 15:21:24 -0700150std::string GetIsoDate() {
151 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700152 tm tmbuf;
153 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700154 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
155 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
156 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
157}
158
Elliott Hughes7162ad92011-10-27 14:08:42 -0700159uint64_t MilliTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800160#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700161 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700162 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700163 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800164#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700165 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800166 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700167 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800168#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700169}
170
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800171uint64_t MicroTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800172#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700173 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800174 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700175 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -0800176#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700177 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800178 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700179 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800180#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800181}
182
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700183uint64_t NanoTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800184#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700185 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700186 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700187 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0a18df82015-01-09 15:16:16 -0800188#else // __APPLE__
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700189 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800190 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700191 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800192#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700193}
194
Elliott Hughes0512f022012-03-15 22:10:52 -0700195uint64_t ThreadCpuNanoTime() {
Elliott Hughes0a18df82015-01-09 15:16:16 -0800196#if defined(__linux__)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700197 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700198 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700199 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0a18df82015-01-09 15:16:16 -0800200#else // __APPLE__
Elliott Hughes0512f022012-03-15 22:10:52 -0700201 UNIMPLEMENTED(WARNING);
202 return -1;
203#endif
204}
205
Ian Rogers56edc432013-01-18 16:51:51 -0800206void NanoSleep(uint64_t ns) {
207 timespec tm;
208 tm.tv_sec = 0;
209 tm.tv_nsec = ns;
210 nanosleep(&tm, NULL);
211}
212
Brian Carlstrombcc29262012-11-02 11:36:03 -0700213void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
214 int64_t endSec;
215
216 if (absolute) {
217#if !defined(__APPLE__)
218 clock_gettime(clock, ts);
219#else
220 UNUSED(clock);
221 timeval tv;
222 gettimeofday(&tv, NULL);
223 ts->tv_sec = tv.tv_sec;
224 ts->tv_nsec = tv.tv_usec * 1000;
225#endif
226 } else {
227 ts->tv_sec = 0;
228 ts->tv_nsec = 0;
229 }
230 endSec = ts->tv_sec + ms / 1000;
231 if (UNLIKELY(endSec >= 0x7fffffff)) {
232 std::ostringstream ss;
233 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
234 endSec = 0x7ffffffe;
235 }
236 ts->tv_sec = endSec;
237 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
238
239 // Catch rollover.
240 if (ts->tv_nsec >= 1000000000L) {
241 ts->tv_sec++;
242 ts->tv_nsec -= 1000000000L;
243 }
244}
245
Ian Rogersef7d42f2014-01-06 12:55:46 -0800246std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700247 if (java_descriptor == NULL) {
248 return "null";
249 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700250 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700251}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700252
Ian Rogersef7d42f2014-01-06 12:55:46 -0800253std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800254 if (klass == NULL) {
255 return "null";
256 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700257 std::string temp;
258 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800259}
260
Ian Rogers1ff3c982014-08-12 02:30:58 -0700261std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700262 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700263 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700264 size_t dim = 0;
265 while (*c == '[') {
266 dim++;
267 c++;
268 }
269
270 // Reference or primitive?
271 if (*c == 'L') {
272 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700273 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700274 } else {
275 // "[[B" -> "byte[][]".
276 // To make life easier, we make primitives look like unqualified
277 // reference types.
278 switch (*c) {
279 case 'B': c = "byte;"; break;
280 case 'C': c = "char;"; break;
281 case 'D': c = "double;"; break;
282 case 'F': c = "float;"; break;
283 case 'I': c = "int;"; break;
284 case 'J': c = "long;"; break;
285 case 'S': c = "short;"; break;
286 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700287 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700288 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700289 }
290 }
291
292 // At this point, 'c' is a string of the form "fully/qualified/Type;"
293 // or "primitive;". Rewrite the type with '.' instead of '/':
294 std::string result;
295 const char* p = c;
296 while (*p != ';') {
297 char ch = *p++;
298 if (ch == '/') {
299 ch = '.';
300 }
301 result.push_back(ch);
302 }
303 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700304 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700305 result += "[]";
306 }
307 return result;
308}
309
Ian Rogersef7d42f2014-01-06 12:55:46 -0800310std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700311 if (f == NULL) {
312 return "null";
313 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700314 std::string result;
315 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700316 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700317 result += ' ';
318 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800319 std::string temp;
320 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700321 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700322 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700323 return result;
324}
325
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700326std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800327 if (field_idx >= dex_file.NumFieldIds()) {
328 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
329 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700330 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
331 std::string result;
332 if (with_type) {
333 result += dex_file.GetFieldTypeDescriptor(field_id);
334 result += ' ';
335 }
336 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
337 result += '.';
338 result += dex_file.GetFieldName(field_id);
339 return result;
340}
341
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700342std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800343 if (type_idx >= dex_file.NumTypeIds()) {
344 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
345 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700346 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700347 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700348}
349
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700350std::string PrettyArguments(const char* signature) {
351 std::string result;
352 result += '(';
353 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700354 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700355 while (*signature != ')') {
356 size_t argument_length = 0;
357 while (signature[argument_length] == '[') {
358 ++argument_length;
359 }
360 if (signature[argument_length] == 'L') {
361 argument_length = (strchr(signature, ';') - signature + 1);
362 } else {
363 ++argument_length;
364 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700365 {
366 std::string argument_descriptor(signature, argument_length);
367 result += PrettyDescriptor(argument_descriptor.c_str());
368 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700369 if (signature[argument_length] != ')') {
370 result += ", ";
371 }
372 signature += argument_length;
373 }
374 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700375 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700376 result += ')';
377 return result;
378}
379
380std::string PrettyReturnType(const char* signature) {
381 const char* return_type = strchr(signature, ')');
382 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700383 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700384 return PrettyDescriptor(return_type);
385}
386
Ian Rogersef7d42f2014-01-06 12:55:46 -0800387std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800388 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700389 return "null";
390 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700391 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700392 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700393 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800394 if (UNLIKELY(m->IsFastNative())) {
395 result += "!";
396 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700397 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700398 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700399 std::string sig_as_string(signature.ToString());
400 if (signature == Signature::NoSignature()) {
401 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700402 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700403 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
404 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700405 }
406 return result;
407}
408
Ian Rogers0571d352011-11-03 19:51:38 -0700409std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800410 if (method_idx >= dex_file.NumMethodIds()) {
411 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
412 }
Ian Rogers0571d352011-11-03 19:51:38 -0700413 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
414 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
415 result += '.';
416 result += dex_file.GetMethodName(method_id);
417 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700418 const Signature signature = dex_file.GetMethodSignature(method_id);
419 std::string sig_as_string(signature.ToString());
420 if (signature == Signature::NoSignature()) {
421 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700422 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700423 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
424 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700425 }
426 return result;
427}
428
Ian Rogersef7d42f2014-01-06 12:55:46 -0800429std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700430 if (obj == NULL) {
431 return "null";
432 }
433 if (obj->GetClass() == NULL) {
434 return "(raw)";
435 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700436 std::string temp;
437 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700438 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700439 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700440 }
441 return result;
442}
443
Ian Rogersef7d42f2014-01-06 12:55:46 -0800444std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700445 if (c == NULL) {
446 return "null";
447 }
448 std::string result;
449 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800450 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700451 result += ">";
452 return result;
453}
454
Ian Rogersef7d42f2014-01-06 12:55:46 -0800455std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700456 if (c == NULL) {
457 return "null";
458 }
459 std::string result;
460 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800461 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700462 result += ",";
463 result += PrettyTypeOf(c->GetClassLoader());
464 // TODO: add an identifying hash value for the loader
465 result += ">";
466 return result;
467}
468
Andreas Gampec0d82292014-09-23 10:38:30 -0700469std::string PrettyJavaAccessFlags(uint32_t access_flags) {
470 std::string result;
471 if ((access_flags & kAccPublic) != 0) {
472 result += "public ";
473 }
474 if ((access_flags & kAccProtected) != 0) {
475 result += "protected ";
476 }
477 if ((access_flags & kAccPrivate) != 0) {
478 result += "private ";
479 }
480 if ((access_flags & kAccFinal) != 0) {
481 result += "final ";
482 }
483 if ((access_flags & kAccStatic) != 0) {
484 result += "static ";
485 }
486 if ((access_flags & kAccTransient) != 0) {
487 result += "transient ";
488 }
489 if ((access_flags & kAccVolatile) != 0) {
490 result += "volatile ";
491 }
492 if ((access_flags & kAccSynchronized) != 0) {
493 result += "synchronized ";
494 }
495 return result;
496}
497
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800498std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700499 // The byte thresholds at which we display amounts. A byte count is displayed
500 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800501 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700502 0, // B up to...
503 3*1024, // KB up to...
504 2*1024*1024, // MB up to...
505 1024*1024*1024 // GB from here.
506 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800507 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700508 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800509 const char* negative_str = "";
510 if (byte_count < 0) {
511 negative_str = "-";
512 byte_count = -byte_count;
513 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700514 int i = arraysize(kUnitThresholds);
515 while (--i > 0) {
516 if (byte_count >= kUnitThresholds[i]) {
517 break;
518 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800519 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800520 return StringPrintf("%s%" PRId64 "%s",
521 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800522}
523
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700524std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800525 if (nano_duration == 0) {
526 return "0";
527 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700528 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
529 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700530 }
531}
532
533TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
534 const uint64_t one_sec = 1000 * 1000 * 1000;
535 const uint64_t one_ms = 1000 * 1000;
536 const uint64_t one_us = 1000;
537 if (nano_duration >= one_sec) {
538 return kTimeUnitSecond;
539 } else if (nano_duration >= one_ms) {
540 return kTimeUnitMillisecond;
541 } else if (nano_duration >= one_us) {
542 return kTimeUnitMicrosecond;
543 } else {
544 return kTimeUnitNanosecond;
545 }
546}
547
548uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
549 const uint64_t one_sec = 1000 * 1000 * 1000;
550 const uint64_t one_ms = 1000 * 1000;
551 const uint64_t one_us = 1000;
552
553 switch (time_unit) {
554 case kTimeUnitSecond:
555 return one_sec;
556 case kTimeUnitMillisecond:
557 return one_ms;
558 case kTimeUnitMicrosecond:
559 return one_us;
560 case kTimeUnitNanosecond:
561 return 1;
562 }
563 return 0;
564}
565
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700566std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
567 size_t max_fraction_digits) {
568 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700569 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700570 switch (time_unit) {
571 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800572 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700573 break;
574 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800575 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700576 break;
577 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800578 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700579 break;
580 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800581 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700582 break;
583 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700584 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700585 uint64_t fractional_part = nano_duration % divisor;
586 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800587 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700588 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700589 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700590 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700591 char fraction_buffer[kMaxDigits];
592 char* ptr = fraction_buffer;
593 uint64_t multiplier = 10;
594 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700595 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700596 multiplier *= 10;
597 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700598 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800599 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700600 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700601 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
602 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800603 }
604}
605
Ian Rogers576ca0c2014-06-06 15:58:22 -0700606std::string PrintableChar(uint16_t ch) {
607 std::string result;
608 result += '\'';
609 if (NeedsEscaping(ch)) {
610 StringAppendF(&result, "\\u%04x", ch);
611 } else {
612 result += ch;
613 }
614 result += '\'';
615 return result;
616}
617
Ian Rogers68b56852014-08-29 20:19:11 -0700618std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700619 std::string result;
620 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700621 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700622 size_t char_count = CountModifiedUtf8Chars(p);
623 for (size_t i = 0; i < char_count; ++i) {
624 uint16_t ch = GetUtf16FromUtf8(&p);
625 if (ch == '\\') {
626 result += "\\\\";
627 } else if (ch == '\n') {
628 result += "\\n";
629 } else if (ch == '\r') {
630 result += "\\r";
631 } else if (ch == '\t') {
632 result += "\\t";
633 } else if (NeedsEscaping(ch)) {
634 StringAppendF(&result, "\\u%04x", ch);
635 } else {
636 result += ch;
637 }
638 }
639 result += '"';
640 return result;
641}
642
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800643// 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 -0700644std::string MangleForJni(const std::string& s) {
645 std::string result;
646 size_t char_count = CountModifiedUtf8Chars(s.c_str());
647 const char* cp = &s[0];
648 for (size_t i = 0; i < char_count; ++i) {
649 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800650 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
651 result.push_back(ch);
652 } else if (ch == '.' || ch == '/') {
653 result += "_";
654 } else if (ch == '_') {
655 result += "_1";
656 } else if (ch == ';') {
657 result += "_2";
658 } else if (ch == '[') {
659 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700660 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800661 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700662 }
663 }
664 return result;
665}
666
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700667std::string DotToDescriptor(const char* class_name) {
668 std::string descriptor(class_name);
669 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
670 if (descriptor.length() > 0 && descriptor[0] != '[') {
671 descriptor = "L" + descriptor + ";";
672 }
673 return descriptor;
674}
675
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800676std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800677 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700678 if (length > 1) {
679 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
680 // Descriptors have the leading 'L' and trailing ';' stripped.
681 std::string result(descriptor + 1, length - 2);
682 std::replace(result.begin(), result.end(), '/', '.');
683 return result;
684 } else {
685 // For arrays the 'L' and ';' remain intact.
686 std::string result(descriptor);
687 std::replace(result.begin(), result.end(), '/', '.');
688 return result;
689 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800690 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700691 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800692 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800693}
694
695std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800696 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800697 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
698 std::string result(descriptor + 1, length - 2);
699 return result;
700 }
701 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700702}
703
Ian Rogersef7d42f2014-01-06 12:55:46 -0800704std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700705 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700706 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700707 CHECK_EQ(class_name[0], 'L') << class_name;
708 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700709 class_name.erase(0, 1);
710 class_name.erase(class_name.size() - 1, 1);
711
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700712 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700713
714 std::string short_name;
715 short_name += "Java_";
716 short_name += MangleForJni(class_name);
717 short_name += "_";
718 short_name += MangleForJni(method_name);
719 return short_name;
720}
721
Ian Rogersef7d42f2014-01-06 12:55:46 -0800722std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700723 std::string long_name;
724 long_name += JniShortName(m);
725 long_name += "__";
726
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700727 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700728 signature.erase(0, 1);
729 signature.erase(signature.begin() + signature.find(')'), signature.end());
730
731 long_name += MangleForJni(signature);
732
733 return long_name;
734}
735
jeffhao10037c82012-01-23 15:06:23 -0800736// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700737uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700738 0x00000000, // 00..1f low control characters; nothing valid
739 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
740 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
741 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700742};
743
jeffhao10037c82012-01-23 15:06:23 -0800744// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
745bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700746 /*
747 * It's a multibyte encoded character. Decode it and analyze. We
748 * accept anything that isn't (a) an improperly encoded low value,
749 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
750 * control character, or (e) a high space, layout, or special
751 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
752 * U+fff0..U+ffff). This is all specified in the dex format
753 * document.
754 */
755
756 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
757
758 // Perform follow-up tests based on the high 8 bits.
759 switch (utf16 >> 8) {
760 case 0x00:
761 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
762 return (utf16 > 0x00a0);
763 case 0xd8:
764 case 0xd9:
765 case 0xda:
766 case 0xdb:
767 // It's a leading surrogate. Check to see that a trailing
768 // surrogate follows.
769 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
770 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
771 case 0xdc:
772 case 0xdd:
773 case 0xde:
774 case 0xdf:
775 // It's a trailing surrogate, which is not valid at this point.
776 return false;
777 case 0x20:
778 case 0xff:
779 // It's in the range that has spaces, controls, and specials.
780 switch (utf16 & 0xfff8) {
781 case 0x2000:
782 case 0x2008:
783 case 0x2028:
784 case 0xfff0:
785 case 0xfff8:
786 return false;
787 }
788 break;
789 }
790 return true;
791}
792
793/* Return whether the pointed-at modified-UTF-8 encoded character is
794 * valid as part of a member name, updating the pointer to point past
795 * the consumed character. This will consume two encoded UTF-16 code
796 * points if the character is encoded as a surrogate pair. Also, if
797 * this function returns false, then the given pointer may only have
798 * been partially advanced.
799 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700800static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700801 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700802 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700803 // It's low-ascii, so check the table.
804 uint32_t wordIdx = c >> 5;
805 uint32_t bitIdx = c & 0x1f;
806 (*pUtf8Ptr)++;
807 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
808 }
809
810 // It's a multibyte encoded character. Call a non-inline function
811 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800812 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
813}
814
815bool IsValidMemberName(const char* s) {
816 bool angle_name = false;
817
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700818 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800819 case '\0':
820 // The empty string is not a valid name.
821 return false;
822 case '<':
823 angle_name = true;
824 s++;
825 break;
826 }
827
828 while (true) {
829 switch (*s) {
830 case '\0':
831 return !angle_name;
832 case '>':
833 return angle_name && s[1] == '\0';
834 }
835
836 if (!IsValidPartOfMemberNameUtf8(&s)) {
837 return false;
838 }
839 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700840}
841
Elliott Hughes906e6852011-10-28 14:52:10 -0700842enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700843template<ClassNameType kType, char kSeparator>
844static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700845 int arrayCount = 0;
846 while (*s == '[') {
847 arrayCount++;
848 s++;
849 }
850
851 if (arrayCount > 255) {
852 // Arrays may have no more than 255 dimensions.
853 return false;
854 }
855
Ian Rogers7b078e82014-09-10 14:44:24 -0700856 ClassNameType type = kType;
857 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700858 /*
859 * If we're looking at an array of some sort, then it doesn't
860 * matter if what is being asked for is a class name; the
861 * format looks the same as a type descriptor in that case, so
862 * treat it as such.
863 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700864 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700865 }
866
Elliott Hughes906e6852011-10-28 14:52:10 -0700867 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700868 /*
869 * We are looking for a descriptor. Either validate it as a
870 * single-character primitive type, or continue on to check the
871 * embedded class name (bracketed by "L" and ";").
872 */
873 switch (*(s++)) {
874 case 'B':
875 case 'C':
876 case 'D':
877 case 'F':
878 case 'I':
879 case 'J':
880 case 'S':
881 case 'Z':
882 // These are all single-character descriptors for primitive types.
883 return (*s == '\0');
884 case 'V':
885 // Non-array void is valid, but you can't have an array of void.
886 return (arrayCount == 0) && (*s == '\0');
887 case 'L':
888 // Class name: Break out and continue below.
889 break;
890 default:
891 // Oddball descriptor character.
892 return false;
893 }
894 }
895
896 /*
897 * We just consumed the 'L' that introduces a class name as part
898 * of a type descriptor, or we are looking for an unadorned class
899 * name.
900 */
901
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700902 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700903 for (;;) {
904 uint8_t c = (uint8_t) *s;
905 switch (c) {
906 case '\0':
907 /*
908 * Premature end for a type descriptor, but valid for
909 * a class name as long as we haven't encountered an
910 * empty component (including the degenerate case of
911 * the empty string "").
912 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700913 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700914 case ';':
915 /*
916 * Invalid character for a class name, but the
917 * legitimate end of a type descriptor. In the latter
918 * case, make sure that this is the end of the string
919 * and that it doesn't end with an empty component
920 * (including the degenerate case of "L;").
921 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700922 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700923 case '/':
924 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700925 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700926 // The wrong separator character.
927 return false;
928 }
929 if (sepOrFirst) {
930 // Separator at start or two separators in a row.
931 return false;
932 }
933 sepOrFirst = true;
934 s++;
935 break;
936 default:
jeffhao10037c82012-01-23 15:06:23 -0800937 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700938 return false;
939 }
940 sepOrFirst = false;
941 break;
942 }
943 }
944}
945
Elliott Hughes906e6852011-10-28 14:52:10 -0700946bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700947 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700948}
949
950bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700951 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700952}
953
954bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700955 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700956}
957
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700958void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700959 const char* p = s.data();
960 const char* end = p + s.size();
961 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800962 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700963 ++p;
964 } else {
965 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800966 while (++p != end && *p != separator) {
967 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700968 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700969 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700970 }
971 }
972}
973
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700974std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -0700975 std::string result;
976 unsigned int start_index = 0;
977 unsigned int end_index = s.size() - 1;
978
979 // Skip initial whitespace.
980 while (start_index < s.size()) {
981 if (!isspace(s[start_index])) {
982 break;
983 }
984 start_index++;
985 }
986
987 // Skip terminating whitespace.
988 while (end_index >= start_index) {
989 if (!isspace(s[end_index])) {
990 break;
991 }
992 end_index--;
993 }
994
995 // All spaces, no beef.
996 if (end_index < start_index) {
997 return "";
998 }
999 // Start_index is the first non-space, end_index is the last one.
1000 return s.substr(start_index, end_index - start_index + 1);
1001}
1002
Elliott Hughes48436bb2012-02-07 15:23:28 -08001003template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001004std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -08001005 if (strings.empty()) {
1006 return "";
1007 }
1008
1009 std::string result(strings[0]);
1010 for (size_t i = 1; i < strings.size(); ++i) {
1011 result += separator;
1012 result += strings[i];
1013 }
1014 return result;
1015}
1016
1017// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001018template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
1019template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -08001020
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001021bool StartsWith(const std::string& s, const char* prefix) {
1022 return s.compare(0, strlen(prefix), prefix) == 0;
1023}
1024
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001025bool EndsWith(const std::string& s, const char* suffix) {
1026 size_t suffix_length = strlen(suffix);
1027 size_t string_length = s.size();
1028 if (suffix_length > string_length) {
1029 return false;
1030 }
1031 size_t offset = string_length - suffix_length;
1032 return s.compare(offset, suffix_length, suffix) == 0;
1033}
1034
Elliott Hughes22869a92012-03-27 14:08:24 -07001035void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -07001036 int hasAt = 0;
1037 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -07001038 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001039 while (*s) {
1040 if (*s == '.') {
1041 hasDot = 1;
1042 } else if (*s == '@') {
1043 hasAt = 1;
1044 }
1045 s++;
1046 }
Elliott Hughes22869a92012-03-27 14:08:24 -07001047 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001048 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -07001049 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001050 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001051 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001052 }
Elliott Hughes0a18df82015-01-09 15:16:16 -08001053#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001054 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -08001055 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001056 strncpy(buf, s, sizeof(buf)-1);
1057 buf[sizeof(buf)-1] = '\0';
1058 errno = pthread_setname_np(pthread_self(), buf);
1059 if (errno != 0) {
1060 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1061 }
Elliott Hughes0a18df82015-01-09 15:16:16 -08001062#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -07001063 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001064#endif
1065}
1066
Brian Carlstrom29212012013-09-12 22:18:30 -07001067void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1068 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001069 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001070 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001071 return;
1072 }
1073 // Skip the command, which may contain spaces.
1074 stats = stats.substr(stats.find(')') + 2);
1075 // Extract the three fields we care about.
1076 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001077 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001078 *state = fields[0][0];
1079 *utime = strtoull(fields[11].c_str(), NULL, 10);
1080 *stime = strtoull(fields[12].c_str(), NULL, 10);
1081 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001082}
1083
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001084std::string GetSchedulerGroupName(pid_t tid) {
1085 // /proc/<pid>/cgroup looks like this:
1086 // 2:devices:/
1087 // 1:cpuacct,cpu:/
1088 // We want the third field from the line whose second field contains the "cpu" token.
1089 std::string cgroup_file;
1090 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1091 return "";
1092 }
1093 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001094 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001095 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1096 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001097 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001098 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001099 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001100 for (size_t j = 0; j < cgroups.size(); ++j) {
1101 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001102 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001103 }
1104 }
1105 }
1106 return "";
1107}
1108
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001109void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Andreas Gampe628a61a2015-01-07 22:08:35 -08001110 mirror::ArtMethod* current_method, void* ucontext_ptr) {
Ian Rogers83597d02014-11-20 10:29:00 -08001111#if __linux__
Andreas Gamped7576322014-10-24 22:13:45 -07001112 // b/18119146
1113 if (RUNNING_ON_VALGRIND != 0) {
1114 return;
1115 }
1116
Ian Rogersedfdaf32014-12-05 16:12:21 +00001117#if !defined(HAVE_ANDROID_OS)
1118 if (GetTid() != tid) {
1119 // TODO: dumping of other threads is disabled to avoid crashes during stress testing.
1120 // b/15446488.
1121 return;
1122 }
1123#endif
1124
Ian Rogers700a4022014-05-19 16:49:03 -07001125 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Andreas Gampe628a61a2015-01-07 22:08:35 -08001126 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001127 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001128 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001129 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001130 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001131 return;
1132 }
1133
Christopher Ferris943af7d2014-01-16 12:41:46 -08001134 for (Backtrace::const_iterator it = backtrace->begin();
1135 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001136 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001137 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1138 // In order for parsing tools to continue to function, the stack dump
1139 // format must at least adhere to this format:
1140 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1141 // The parsers require a single space before and after pc, and two spaces
1142 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1143 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1144 os << prefix << StringPrintf("#%02zu pc ", it->num);
1145 if (!it->map) {
1146 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001147 } else {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001148 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1149 << it->map->name << " (";
1150 if (!it->func_name.empty()) {
1151 os << it->func_name;
1152 if (it->func_offset != 0) {
1153 os << "+" << it->func_offset;
1154 }
Hiroshi Yamauchi7895d552014-08-28 14:55:56 -07001155 } else if (current_method != nullptr &&
1156 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001157 current_method->PcIsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001158 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1159 os << JniLongName(current_method) << "+"
1160 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001161 } else {
1162 os << "???";
1163 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001164 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001165 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001166 os << "\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001167 }
Nicolas Geoffraye6ac4fd2014-11-04 13:03:29 +00001168#else
1169 UNUSED(os, tid, prefix, current_method);
Ian Rogersc5f17732014-06-05 20:48:42 -07001170#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001171}
1172
Elliott Hughes058a6de2012-05-24 19:13:02 -07001173#if defined(__APPLE__)
1174
1175// TODO: is there any way to get the kernel stack on Mac OS?
1176void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1177
1178#else
1179
Elliott Hughes46e251b2012-05-22 15:10:45 -07001180void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001181 if (tid == GetTid()) {
1182 // There's no point showing that we're reading our stack out of /proc!
1183 return;
1184 }
1185
Elliott Hughes46e251b2012-05-22 15:10:45 -07001186 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1187 std::string kernel_stack;
1188 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001189 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001190 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001191 }
1192
1193 std::vector<std::string> kernel_stack_frames;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001194 Split(kernel_stack, '\n', &kernel_stack_frames);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001195 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1196 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1197 kernel_stack_frames.pop_back();
1198 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001199 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1200 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001201 const char* text = kernel_stack_frames[i].c_str();
1202 const char* close_bracket = strchr(text, ']');
1203 if (close_bracket != NULL) {
1204 text = close_bracket + 2;
1205 }
1206 os << prefix;
1207 if (include_count) {
1208 os << StringPrintf("#%02zd ", i);
1209 }
1210 os << text << "\n";
1211 }
1212}
1213
1214#endif
1215
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001216const char* GetAndroidRoot() {
1217 const char* android_root = getenv("ANDROID_ROOT");
1218 if (android_root == NULL) {
1219 if (OS::DirectoryExists("/system")) {
1220 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001221 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001222 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1223 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001224 }
1225 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001226 if (!OS::DirectoryExists(android_root)) {
1227 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001228 return "";
1229 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001230 return android_root;
1231}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001232
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001233const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001234 std::string error_msg;
1235 const char* dir = GetAndroidDataSafe(&error_msg);
1236 if (dir != nullptr) {
1237 return dir;
1238 } else {
1239 LOG(FATAL) << error_msg;
1240 return "";
1241 }
1242}
1243
1244const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001245 const char* android_data = getenv("ANDROID_DATA");
1246 if (android_data == NULL) {
1247 if (OS::DirectoryExists("/data")) {
1248 android_data = "/data";
1249 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001250 *error_msg = "ANDROID_DATA not set and /data does not exist";
1251 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001252 }
1253 }
1254 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001255 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1256 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001257 }
1258 return android_data;
1259}
1260
Alex Lighta59dd802014-07-02 16:28:08 -07001261void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001262 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001263 CHECK(subdir != nullptr);
1264 std::string error_msg;
1265 const char* android_data = GetAndroidDataSafe(&error_msg);
1266 if (android_data == nullptr) {
1267 *have_android_data = false;
1268 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001269 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001270 return;
1271 } else {
1272 *have_android_data = true;
1273 }
1274 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1275 *dalvik_cache = dalvik_cache_root + subdir;
1276 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001277 *is_global_cache = strcmp(android_data, "/data") == 0;
1278 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001279 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1280 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1281 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1282 }
1283}
1284
Narayan Kamath11d9f062014-04-23 20:24:57 +01001285std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1286 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001287 const char* android_data = GetAndroidData();
1288 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001289 const std::string dalvik_cache = dalvik_cache_root + subdir;
1290 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001291 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1292 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001293 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001294 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001295 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1296 return "";
1297 }
1298 result = mkdir(dalvik_cache.c_str(), 0700);
1299 if (result != 0) {
1300 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001301 return "";
1302 }
1303 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001304 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001305 return "";
1306 }
1307 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001308 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001309}
1310
Alex Lighta59dd802014-07-02 16:28:08 -07001311bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1312 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001313 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001314 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1315 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001316 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001317 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001318 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001319 cache_file += "/";
1320 cache_file += DexFile::kClassesDex;
1321 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001322 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001323 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1324 return true;
1325}
1326
1327std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1328 std::string ret;
1329 std::string error_msg;
1330 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1331 LOG(FATAL) << error_msg;
1332 }
1333 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001334}
1335
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001336static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001337 // in = /foo/bar/baz
1338 // out = /foo/bar/<isa>/baz
1339 size_t pos = filename->rfind('/');
1340 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1341 filename->insert(pos, "/", 1);
1342 filename->insert(pos + 1, GetInstructionSetString(isa));
1343}
1344
1345std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1346 // location = /system/framework/boot.art
1347 // filename = /system/framework/<isa>/boot.art
1348 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001349 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001350 return filename;
1351}
1352
1353std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1354 // location = /foo/bar/baz.jar
1355 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001356
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001357 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1358 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001359 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001360 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1361 CHECK_EQ('.', odex_location[dot_index]) << location;
1362 odex_location.resize(dot_index + 1);
1363 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1364 odex_location += "odex";
1365 return odex_location;
1366}
1367
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001368bool IsZipMagic(uint32_t magic) {
1369 return (('P' == ((magic >> 0) & 0xff)) &&
1370 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001371}
1372
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001373bool IsDexMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001374 return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001375}
1376
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001377bool IsOatMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001378 return (memcmp(reinterpret_cast<const uint8_t*>(magic),
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001379 OatHeader::kOatMagic,
1380 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001381}
1382
Brian Carlstrom6449c622014-02-10 23:48:36 -08001383bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1384 const std::string command_line(Join(arg_vector, ' '));
1385
1386 CHECK_GE(arg_vector.size(), 1U) << command_line;
1387
1388 // Convert the args to char pointers.
1389 const char* program = arg_vector[0].c_str();
1390 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001391 for (size_t i = 0; i < arg_vector.size(); ++i) {
1392 const std::string& arg = arg_vector[i];
1393 char* arg_str = const_cast<char*>(arg.c_str());
1394 CHECK(arg_str != nullptr) << i;
1395 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001396 }
1397 args.push_back(NULL);
1398
1399 // fork and exec
1400 pid_t pid = fork();
1401 if (pid == 0) {
1402 // no allocation allowed between fork and exec
1403
1404 // change process groups, so we don't get reaped by ProcessManager
1405 setpgid(0, 0);
1406
1407 execv(program, &args[0]);
1408
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001409 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1410 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001411 } else {
1412 if (pid == -1) {
1413 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1414 command_line.c_str(), strerror(errno));
1415 return false;
1416 }
1417
1418 // wait for subprocess to finish
1419 int status;
1420 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1421 if (got_pid != pid) {
1422 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1423 "wanted %d, got %d: %s",
1424 command_line.c_str(), pid, got_pid, strerror(errno));
1425 return false;
1426 }
1427 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1428 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1429 command_line.c_str());
1430 return false;
1431 }
1432 }
1433 return true;
1434}
1435
Tong Shen547cdfd2014-08-05 01:54:19 -07001436void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001437 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001438}
1439
1440void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001441 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001442}
1443
1444void PushWord(std::vector<uint8_t>* buf, int data) {
1445 buf->push_back(data & 0xff);
1446 buf->push_back((data >> 8) & 0xff);
1447 buf->push_back((data >> 16) & 0xff);
1448 buf->push_back((data >> 24) & 0xff);
1449}
1450
Mathieu Chartier76433272014-09-26 14:32:37 -07001451std::string PrettyDescriptor(Primitive::Type type) {
1452 return PrettyDescriptor(Primitive::Descriptor(type));
1453}
1454
Elliott Hughes42ee1422011-09-06 12:33:32 -07001455} // namespace art