blob: 55ecc1e40c357be9db0906599ea7b0a987d188a5 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Elliott Hughes11e45072011-08-16 17:40:46 -070016
Elliott Hughes42ee1422011-09-06 12:33:32 -070017#include "utils.h"
18
Christopher Ferris943af7d2014-01-16 12:41:46 -080019#include <inttypes.h>
Elliott Hughes92b3b562011-09-08 16:32:26 -070020#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070021#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070022#include <sys/syscall.h>
23#include <sys/types.h>
Brian Carlstrom4cf5e572014-02-25 11:47:48 -080024#include <sys/wait.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070025#include <unistd.h>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Elliott Hughes42ee1422011-09-06 12:33:32 -070027
Brian Carlstrom6449c622014-02-10 23:48:36 -080028#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080029#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "dex_file-inl.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070031#include "field_helper.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070032#include "mirror/art_field-inl.h"
33#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "mirror/object-inl.h"
37#include "mirror/object_array-inl.h"
38#include "mirror/string.h"
buzbeec143c552011-08-20 17:38:58 -070039#include "os.h"
Kenny Root067d20f2014-03-05 14:57:21 -080040#include "scoped_thread_state_change.h"
Ian Rogersa6724902013-09-23 09:23:37 -070041#include "utf-inl.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070042
Elliott Hughesad6c9c32012-01-19 17:39:12 -080043#if !defined(HAVE_POSIX_CLOCKS)
44#include <sys/time.h>
45#endif
46
Elliott Hughesdcc24742011-09-07 14:02:44 -070047#if defined(HAVE_PRCTL)
48#include <sys/prctl.h>
49#endif
50
Elliott Hughes4ae722a2012-03-13 11:08:51 -070051#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070052#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070053#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070054#endif
55
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070056#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070057
Elliott Hughes058a6de2012-05-24 19:13:02 -070058#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080059#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080060#endif
61
Elliott Hughes11e45072011-08-16 17:40:46 -070062namespace art {
63
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080064pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070065#if defined(__APPLE__)
66 uint64_t owner;
67 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
68 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070069#elif defined(__BIONIC__)
70 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080071#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080072 return syscall(__NR_gettid);
73#endif
74}
75
Elliott Hughes289be852012-06-12 13:57:20 -070076std::string GetThreadName(pid_t tid) {
77 std::string result;
78 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070079 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070080 } else {
81 result = "<unknown>";
82 }
83 return result;
84}
85
Elliott Hughes6d3fc562014-08-27 11:47:01 -070086void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070087#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070088 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070089 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070090
91 // Check whether stack_addr is the base or end of the stack.
92 // (On Mac OS 10.7, it's the end.)
93 int stack_variable;
94 if (stack_addr > &stack_variable) {
Brian Carlstrom29212012013-09-12 22:18:30 -070095 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070096 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070097 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070098 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070099
100 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
101 pthread_attr_t attributes;
102 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
103 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
104 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700105#else
106 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700107 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700108 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700109 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700110 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
111#endif
112}
113
Elliott Hughesd92bec42011-09-02 17:04:36 -0700114bool ReadFileToString(const std::string& file_name, std::string* result) {
Ian Rogers700a4022014-05-19 16:49:03 -0700115 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800116 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700117 return false;
118 }
buzbeec143c552011-08-20 17:38:58 -0700119
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700120 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700121 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800122 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700123 if (n == -1) {
124 return false;
buzbeec143c552011-08-20 17:38:58 -0700125 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700126 if (n == 0) {
127 return true;
128 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700129 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700130 }
buzbeec143c552011-08-20 17:38:58 -0700131}
132
Elliott Hughese27955c2011-08-26 15:21:24 -0700133std::string GetIsoDate() {
134 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700135 tm tmbuf;
136 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700137 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
138 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
139 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
140}
141
Elliott Hughes7162ad92011-10-27 14:08:42 -0700142uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800143#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700144 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700145 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700146 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800147#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700148 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800149 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700150 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800151#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700152}
153
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800154uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800155#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700156 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800157 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700158 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800159#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700160 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800161 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700162 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800163#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800164}
165
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700166uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800167#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700168 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700169 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700170 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800171#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700172 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800173 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700174 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800175#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700176}
177
Elliott Hughes0512f022012-03-15 22:10:52 -0700178uint64_t ThreadCpuNanoTime() {
179#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700180 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700181 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700182 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0512f022012-03-15 22:10:52 -0700183#else
184 UNIMPLEMENTED(WARNING);
185 return -1;
186#endif
187}
188
Ian Rogers56edc432013-01-18 16:51:51 -0800189void NanoSleep(uint64_t ns) {
190 timespec tm;
191 tm.tv_sec = 0;
192 tm.tv_nsec = ns;
193 nanosleep(&tm, NULL);
194}
195
Brian Carlstrombcc29262012-11-02 11:36:03 -0700196void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
197 int64_t endSec;
198
199 if (absolute) {
200#if !defined(__APPLE__)
201 clock_gettime(clock, ts);
202#else
203 UNUSED(clock);
204 timeval tv;
205 gettimeofday(&tv, NULL);
206 ts->tv_sec = tv.tv_sec;
207 ts->tv_nsec = tv.tv_usec * 1000;
208#endif
209 } else {
210 ts->tv_sec = 0;
211 ts->tv_nsec = 0;
212 }
213 endSec = ts->tv_sec + ms / 1000;
214 if (UNLIKELY(endSec >= 0x7fffffff)) {
215 std::ostringstream ss;
216 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
217 endSec = 0x7ffffffe;
218 }
219 ts->tv_sec = endSec;
220 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
221
222 // Catch rollover.
223 if (ts->tv_nsec >= 1000000000L) {
224 ts->tv_sec++;
225 ts->tv_nsec -= 1000000000L;
226 }
227}
228
Ian Rogersef7d42f2014-01-06 12:55:46 -0800229std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700230 if (java_descriptor == NULL) {
231 return "null";
232 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700233 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700234}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700235
Ian Rogersef7d42f2014-01-06 12:55:46 -0800236std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800237 if (klass == NULL) {
238 return "null";
239 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700240 std::string temp;
241 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800242}
243
Ian Rogers1ff3c982014-08-12 02:30:58 -0700244std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700245 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700246 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700247 size_t dim = 0;
248 while (*c == '[') {
249 dim++;
250 c++;
251 }
252
253 // Reference or primitive?
254 if (*c == 'L') {
255 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700256 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700257 } else {
258 // "[[B" -> "byte[][]".
259 // To make life easier, we make primitives look like unqualified
260 // reference types.
261 switch (*c) {
262 case 'B': c = "byte;"; break;
263 case 'C': c = "char;"; break;
264 case 'D': c = "double;"; break;
265 case 'F': c = "float;"; break;
266 case 'I': c = "int;"; break;
267 case 'J': c = "long;"; break;
268 case 'S': c = "short;"; break;
269 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700270 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700271 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700272 }
273 }
274
275 // At this point, 'c' is a string of the form "fully/qualified/Type;"
276 // or "primitive;". Rewrite the type with '.' instead of '/':
277 std::string result;
278 const char* p = c;
279 while (*p != ';') {
280 char ch = *p++;
281 if (ch == '/') {
282 ch = '.';
283 }
284 result.push_back(ch);
285 }
286 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700287 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700288 result += "[]";
289 }
290 return result;
291}
292
Ian Rogers68d8b422014-07-17 11:09:10 -0700293std::string PrettyDescriptor(Primitive::Type type) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700294 return PrettyDescriptor(Primitive::Descriptor(type));
Ian Rogers68d8b422014-07-17 11:09:10 -0700295}
296
Ian Rogersef7d42f2014-01-06 12:55:46 -0800297std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700298 if (f == NULL) {
299 return "null";
300 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700301 std::string result;
302 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700303 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700304 result += ' ';
305 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700306 StackHandleScope<1> hs(Thread::Current());
307 result += PrettyDescriptor(FieldHelper(hs.NewHandle(f)).GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700308 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700309 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700310 return result;
311}
312
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700313std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800314 if (field_idx >= dex_file.NumFieldIds()) {
315 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
316 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700317 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
318 std::string result;
319 if (with_type) {
320 result += dex_file.GetFieldTypeDescriptor(field_id);
321 result += ' ';
322 }
323 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
324 result += '.';
325 result += dex_file.GetFieldName(field_id);
326 return result;
327}
328
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700329std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800330 if (type_idx >= dex_file.NumTypeIds()) {
331 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
332 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700333 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700334 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700335}
336
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700337std::string PrettyArguments(const char* signature) {
338 std::string result;
339 result += '(';
340 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700341 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700342 while (*signature != ')') {
343 size_t argument_length = 0;
344 while (signature[argument_length] == '[') {
345 ++argument_length;
346 }
347 if (signature[argument_length] == 'L') {
348 argument_length = (strchr(signature, ';') - signature + 1);
349 } else {
350 ++argument_length;
351 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700352 {
353 std::string argument_descriptor(signature, argument_length);
354 result += PrettyDescriptor(argument_descriptor.c_str());
355 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700356 if (signature[argument_length] != ')') {
357 result += ", ";
358 }
359 signature += argument_length;
360 }
361 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700362 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700363 result += ')';
364 return result;
365}
366
367std::string PrettyReturnType(const char* signature) {
368 const char* return_type = strchr(signature, ')');
369 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700370 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700371 return PrettyDescriptor(return_type);
372}
373
Ian Rogersef7d42f2014-01-06 12:55:46 -0800374std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800375 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700376 return "null";
377 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700378 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700379 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700380 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800381 if (UNLIKELY(m->IsFastNative())) {
382 result += "!";
383 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700384 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700385 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700386 std::string sig_as_string(signature.ToString());
387 if (signature == Signature::NoSignature()) {
388 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700389 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700390 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
391 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700392 }
393 return result;
394}
395
Ian Rogers0571d352011-11-03 19:51:38 -0700396std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800397 if (method_idx >= dex_file.NumMethodIds()) {
398 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
399 }
Ian Rogers0571d352011-11-03 19:51:38 -0700400 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
401 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
402 result += '.';
403 result += dex_file.GetMethodName(method_id);
404 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700405 const Signature signature = dex_file.GetMethodSignature(method_id);
406 std::string sig_as_string(signature.ToString());
407 if (signature == Signature::NoSignature()) {
408 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700409 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700410 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
411 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700412 }
413 return result;
414}
415
Ian Rogersef7d42f2014-01-06 12:55:46 -0800416std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700417 if (obj == NULL) {
418 return "null";
419 }
420 if (obj->GetClass() == NULL) {
421 return "(raw)";
422 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700423 std::string temp;
424 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700425 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700426 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700427 }
428 return result;
429}
430
Ian Rogersef7d42f2014-01-06 12:55:46 -0800431std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700432 if (c == NULL) {
433 return "null";
434 }
435 std::string result;
436 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800437 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700438 result += ">";
439 return result;
440}
441
Ian Rogersef7d42f2014-01-06 12:55:46 -0800442std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700443 if (c == NULL) {
444 return "null";
445 }
446 std::string result;
447 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800448 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700449 result += ",";
450 result += PrettyTypeOf(c->GetClassLoader());
451 // TODO: add an identifying hash value for the loader
452 result += ">";
453 return result;
454}
455
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800456std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700457 // The byte thresholds at which we display amounts. A byte count is displayed
458 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800459 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700460 0, // B up to...
461 3*1024, // KB up to...
462 2*1024*1024, // MB up to...
463 1024*1024*1024 // GB from here.
464 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800465 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700466 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800467 const char* negative_str = "";
468 if (byte_count < 0) {
469 negative_str = "-";
470 byte_count = -byte_count;
471 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700472 int i = arraysize(kUnitThresholds);
473 while (--i > 0) {
474 if (byte_count >= kUnitThresholds[i]) {
475 break;
476 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800477 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800478 return StringPrintf("%s%" PRId64 "%s",
479 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800480}
481
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700482std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800483 if (nano_duration == 0) {
484 return "0";
485 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700486 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
487 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700488 }
489}
490
491TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
492 const uint64_t one_sec = 1000 * 1000 * 1000;
493 const uint64_t one_ms = 1000 * 1000;
494 const uint64_t one_us = 1000;
495 if (nano_duration >= one_sec) {
496 return kTimeUnitSecond;
497 } else if (nano_duration >= one_ms) {
498 return kTimeUnitMillisecond;
499 } else if (nano_duration >= one_us) {
500 return kTimeUnitMicrosecond;
501 } else {
502 return kTimeUnitNanosecond;
503 }
504}
505
506uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
507 const uint64_t one_sec = 1000 * 1000 * 1000;
508 const uint64_t one_ms = 1000 * 1000;
509 const uint64_t one_us = 1000;
510
511 switch (time_unit) {
512 case kTimeUnitSecond:
513 return one_sec;
514 case kTimeUnitMillisecond:
515 return one_ms;
516 case kTimeUnitMicrosecond:
517 return one_us;
518 case kTimeUnitNanosecond:
519 return 1;
520 }
521 return 0;
522}
523
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700524std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
525 size_t max_fraction_digits) {
526 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700527 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700528 switch (time_unit) {
529 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800530 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700531 break;
532 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800533 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700534 break;
535 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800536 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700537 break;
538 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800539 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700540 break;
541 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700542 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700543 uint64_t fractional_part = nano_duration % divisor;
544 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800545 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700546 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700547 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700548 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700549 char fraction_buffer[kMaxDigits];
550 char* ptr = fraction_buffer;
551 uint64_t multiplier = 10;
552 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700553 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700554 multiplier *= 10;
555 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700556 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800557 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700558 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700559 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
560 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800561 }
562}
563
Ian Rogers576ca0c2014-06-06 15:58:22 -0700564std::string PrintableChar(uint16_t ch) {
565 std::string result;
566 result += '\'';
567 if (NeedsEscaping(ch)) {
568 StringAppendF(&result, "\\u%04x", ch);
569 } else {
570 result += ch;
571 }
572 result += '\'';
573 return result;
574}
575
Elliott Hughes82914b62012-04-09 15:56:29 -0700576std::string PrintableString(const std::string& utf) {
577 std::string result;
578 result += '"';
579 const char* p = utf.c_str();
580 size_t char_count = CountModifiedUtf8Chars(p);
581 for (size_t i = 0; i < char_count; ++i) {
582 uint16_t ch = GetUtf16FromUtf8(&p);
583 if (ch == '\\') {
584 result += "\\\\";
585 } else if (ch == '\n') {
586 result += "\\n";
587 } else if (ch == '\r') {
588 result += "\\r";
589 } else if (ch == '\t') {
590 result += "\\t";
591 } else if (NeedsEscaping(ch)) {
592 StringAppendF(&result, "\\u%04x", ch);
593 } else {
594 result += ch;
595 }
596 }
597 result += '"';
598 return result;
599}
600
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800601// 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 -0700602std::string MangleForJni(const std::string& s) {
603 std::string result;
604 size_t char_count = CountModifiedUtf8Chars(s.c_str());
605 const char* cp = &s[0];
606 for (size_t i = 0; i < char_count; ++i) {
607 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800608 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
609 result.push_back(ch);
610 } else if (ch == '.' || ch == '/') {
611 result += "_";
612 } else if (ch == '_') {
613 result += "_1";
614 } else if (ch == ';') {
615 result += "_2";
616 } else if (ch == '[') {
617 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700618 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800619 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700620 }
621 }
622 return result;
623}
624
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700625std::string DotToDescriptor(const char* class_name) {
626 std::string descriptor(class_name);
627 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
628 if (descriptor.length() > 0 && descriptor[0] != '[') {
629 descriptor = "L" + descriptor + ";";
630 }
631 return descriptor;
632}
633
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800634std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800635 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700636 if (length > 1) {
637 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
638 // Descriptors have the leading 'L' and trailing ';' stripped.
639 std::string result(descriptor + 1, length - 2);
640 std::replace(result.begin(), result.end(), '/', '.');
641 return result;
642 } else {
643 // For arrays the 'L' and ';' remain intact.
644 std::string result(descriptor);
645 std::replace(result.begin(), result.end(), '/', '.');
646 return result;
647 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800648 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700649 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800650 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800651}
652
653std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800654 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800655 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
656 std::string result(descriptor + 1, length - 2);
657 return result;
658 }
659 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700660}
661
Ian Rogersef7d42f2014-01-06 12:55:46 -0800662std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700663 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700664 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700665 CHECK_EQ(class_name[0], 'L') << class_name;
666 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700667 class_name.erase(0, 1);
668 class_name.erase(class_name.size() - 1, 1);
669
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700670 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700671
672 std::string short_name;
673 short_name += "Java_";
674 short_name += MangleForJni(class_name);
675 short_name += "_";
676 short_name += MangleForJni(method_name);
677 return short_name;
678}
679
Ian Rogersef7d42f2014-01-06 12:55:46 -0800680std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700681 std::string long_name;
682 long_name += JniShortName(m);
683 long_name += "__";
684
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700685 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700686 signature.erase(0, 1);
687 signature.erase(signature.begin() + signature.find(')'), signature.end());
688
689 long_name += MangleForJni(signature);
690
691 return long_name;
692}
693
jeffhao10037c82012-01-23 15:06:23 -0800694// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700695uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700696 0x00000000, // 00..1f low control characters; nothing valid
697 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
698 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
699 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700700};
701
jeffhao10037c82012-01-23 15:06:23 -0800702// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
703bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700704 /*
705 * It's a multibyte encoded character. Decode it and analyze. We
706 * accept anything that isn't (a) an improperly encoded low value,
707 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
708 * control character, or (e) a high space, layout, or special
709 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
710 * U+fff0..U+ffff). This is all specified in the dex format
711 * document.
712 */
713
714 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
715
716 // Perform follow-up tests based on the high 8 bits.
717 switch (utf16 >> 8) {
718 case 0x00:
719 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
720 return (utf16 > 0x00a0);
721 case 0xd8:
722 case 0xd9:
723 case 0xda:
724 case 0xdb:
725 // It's a leading surrogate. Check to see that a trailing
726 // surrogate follows.
727 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
728 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
729 case 0xdc:
730 case 0xdd:
731 case 0xde:
732 case 0xdf:
733 // It's a trailing surrogate, which is not valid at this point.
734 return false;
735 case 0x20:
736 case 0xff:
737 // It's in the range that has spaces, controls, and specials.
738 switch (utf16 & 0xfff8) {
739 case 0x2000:
740 case 0x2008:
741 case 0x2028:
742 case 0xfff0:
743 case 0xfff8:
744 return false;
745 }
746 break;
747 }
748 return true;
749}
750
751/* Return whether the pointed-at modified-UTF-8 encoded character is
752 * valid as part of a member name, updating the pointer to point past
753 * the consumed character. This will consume two encoded UTF-16 code
754 * points if the character is encoded as a surrogate pair. Also, if
755 * this function returns false, then the given pointer may only have
756 * been partially advanced.
757 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700758static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700759 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700760 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700761 // It's low-ascii, so check the table.
762 uint32_t wordIdx = c >> 5;
763 uint32_t bitIdx = c & 0x1f;
764 (*pUtf8Ptr)++;
765 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
766 }
767
768 // It's a multibyte encoded character. Call a non-inline function
769 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800770 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
771}
772
773bool IsValidMemberName(const char* s) {
774 bool angle_name = false;
775
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700776 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800777 case '\0':
778 // The empty string is not a valid name.
779 return false;
780 case '<':
781 angle_name = true;
782 s++;
783 break;
784 }
785
786 while (true) {
787 switch (*s) {
788 case '\0':
789 return !angle_name;
790 case '>':
791 return angle_name && s[1] == '\0';
792 }
793
794 if (!IsValidPartOfMemberNameUtf8(&s)) {
795 return false;
796 }
797 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700798}
799
Elliott Hughes906e6852011-10-28 14:52:10 -0700800enum ClassNameType { kName, kDescriptor };
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700801static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700802 int arrayCount = 0;
803 while (*s == '[') {
804 arrayCount++;
805 s++;
806 }
807
808 if (arrayCount > 255) {
809 // Arrays may have no more than 255 dimensions.
810 return false;
811 }
812
813 if (arrayCount != 0) {
814 /*
815 * If we're looking at an array of some sort, then it doesn't
816 * matter if what is being asked for is a class name; the
817 * format looks the same as a type descriptor in that case, so
818 * treat it as such.
819 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700820 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700821 }
822
Elliott Hughes906e6852011-10-28 14:52:10 -0700823 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700824 /*
825 * We are looking for a descriptor. Either validate it as a
826 * single-character primitive type, or continue on to check the
827 * embedded class name (bracketed by "L" and ";").
828 */
829 switch (*(s++)) {
830 case 'B':
831 case 'C':
832 case 'D':
833 case 'F':
834 case 'I':
835 case 'J':
836 case 'S':
837 case 'Z':
838 // These are all single-character descriptors for primitive types.
839 return (*s == '\0');
840 case 'V':
841 // Non-array void is valid, but you can't have an array of void.
842 return (arrayCount == 0) && (*s == '\0');
843 case 'L':
844 // Class name: Break out and continue below.
845 break;
846 default:
847 // Oddball descriptor character.
848 return false;
849 }
850 }
851
852 /*
853 * We just consumed the 'L' that introduces a class name as part
854 * of a type descriptor, or we are looking for an unadorned class
855 * name.
856 */
857
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700858 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700859 for (;;) {
860 uint8_t c = (uint8_t) *s;
861 switch (c) {
862 case '\0':
863 /*
864 * Premature end for a type descriptor, but valid for
865 * a class name as long as we haven't encountered an
866 * empty component (including the degenerate case of
867 * the empty string "").
868 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700869 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700870 case ';':
871 /*
872 * Invalid character for a class name, but the
873 * legitimate end of a type descriptor. In the latter
874 * case, make sure that this is the end of the string
875 * and that it doesn't end with an empty component
876 * (including the degenerate case of "L;").
877 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700878 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700879 case '/':
880 case '.':
881 if (c != separator) {
882 // The wrong separator character.
883 return false;
884 }
885 if (sepOrFirst) {
886 // Separator at start or two separators in a row.
887 return false;
888 }
889 sepOrFirst = true;
890 s++;
891 break;
892 default:
jeffhao10037c82012-01-23 15:06:23 -0800893 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700894 return false;
895 }
896 sepOrFirst = false;
897 break;
898 }
899 }
900}
901
Elliott Hughes906e6852011-10-28 14:52:10 -0700902bool IsValidBinaryClassName(const char* s) {
903 return IsValidClassName(s, kName, '.');
904}
905
906bool IsValidJniClassName(const char* s) {
907 return IsValidClassName(s, kName, '/');
908}
909
910bool IsValidDescriptor(const char* s) {
911 return IsValidClassName(s, kDescriptor, '/');
912}
913
Elliott Hughes48436bb2012-02-07 15:23:28 -0800914void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700915 const char* p = s.data();
916 const char* end = p + s.size();
917 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800918 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700919 ++p;
920 } else {
921 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800922 while (++p != end && *p != separator) {
923 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700924 }
925 result.push_back(std::string(start, p - start));
926 }
927 }
928}
929
Dave Allison70202782013-10-22 17:52:19 -0700930std::string Trim(std::string s) {
931 std::string result;
932 unsigned int start_index = 0;
933 unsigned int end_index = s.size() - 1;
934
935 // Skip initial whitespace.
936 while (start_index < s.size()) {
937 if (!isspace(s[start_index])) {
938 break;
939 }
940 start_index++;
941 }
942
943 // Skip terminating whitespace.
944 while (end_index >= start_index) {
945 if (!isspace(s[end_index])) {
946 break;
947 }
948 end_index--;
949 }
950
951 // All spaces, no beef.
952 if (end_index < start_index) {
953 return "";
954 }
955 // Start_index is the first non-space, end_index is the last one.
956 return s.substr(start_index, end_index - start_index + 1);
957}
958
Elliott Hughes48436bb2012-02-07 15:23:28 -0800959template <typename StringT>
960std::string Join(std::vector<StringT>& strings, char separator) {
961 if (strings.empty()) {
962 return "";
963 }
964
965 std::string result(strings[0]);
966 for (size_t i = 1; i < strings.size(); ++i) {
967 result += separator;
968 result += strings[i];
969 }
970 return result;
971}
972
973// Explicit instantiations.
974template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
975template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
976template std::string Join<char*>(std::vector<char*>& strings, char separator);
977
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800978bool StartsWith(const std::string& s, const char* prefix) {
979 return s.compare(0, strlen(prefix), prefix) == 0;
980}
981
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700982bool EndsWith(const std::string& s, const char* suffix) {
983 size_t suffix_length = strlen(suffix);
984 size_t string_length = s.size();
985 if (suffix_length > string_length) {
986 return false;
987 }
988 size_t offset = string_length - suffix_length;
989 return s.compare(offset, suffix_length, suffix) == 0;
990}
991
Elliott Hughes22869a92012-03-27 14:08:24 -0700992void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700993 int hasAt = 0;
994 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700995 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700996 while (*s) {
997 if (*s == '.') {
998 hasDot = 1;
999 } else if (*s == '@') {
1000 hasAt = 1;
1001 }
1002 s++;
1003 }
Elliott Hughes22869a92012-03-27 14:08:24 -07001004 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001005 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -07001006 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001007 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001008 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001009 }
Elliott Hughes49e36ec2014-08-20 20:18:18 -07001010#if defined(__BIONIC__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001011 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001012 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1013 strncpy(buf, s, sizeof(buf)-1);
1014 buf[sizeof(buf)-1] = '\0';
1015 errno = pthread_setname_np(pthread_self(), buf);
1016 if (errno != 0) {
1017 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1018 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -07001019#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -07001020 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001021#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -07001022 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -07001023#else
Elliott Hughes22869a92012-03-27 14:08:24 -07001024 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001025#endif
1026}
1027
Brian Carlstrom29212012013-09-12 22:18:30 -07001028void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1029 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001030 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001031 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001032 return;
1033 }
1034 // Skip the command, which may contain spaces.
1035 stats = stats.substr(stats.find(')') + 2);
1036 // Extract the three fields we care about.
1037 std::vector<std::string> fields;
1038 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001039 *state = fields[0][0];
1040 *utime = strtoull(fields[11].c_str(), NULL, 10);
1041 *stime = strtoull(fields[12].c_str(), NULL, 10);
1042 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001043}
1044
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001045std::string GetSchedulerGroupName(pid_t tid) {
1046 // /proc/<pid>/cgroup looks like this:
1047 // 2:devices:/
1048 // 1:cpuacct,cpu:/
1049 // We want the third field from the line whose second field contains the "cpu" token.
1050 std::string cgroup_file;
1051 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1052 return "";
1053 }
1054 std::vector<std::string> cgroup_lines;
1055 Split(cgroup_file, '\n', cgroup_lines);
1056 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1057 std::vector<std::string> cgroup_fields;
1058 Split(cgroup_lines[i], ':', cgroup_fields);
1059 std::vector<std::string> cgroups;
1060 Split(cgroup_fields[1], ',', cgroups);
1061 for (size_t i = 0; i < cgroups.size(); ++i) {
1062 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001063 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001064 }
1065 }
1066 }
1067 return "";
1068}
1069
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001070void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Kenny Root067d20f2014-03-05 14:57:21 -08001071 mirror::ArtMethod* current_method) {
1072 // We may be called from contexts where current_method is not null, so we must assert this.
1073 if (current_method != nullptr) {
1074 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1075 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001076#ifdef __linux__
Ian Rogers700a4022014-05-19 16:49:03 -07001077 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001078 if (!backtrace->Unwind(0)) {
1079 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001080 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001081 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001082 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001083 return;
1084 }
1085
Christopher Ferris943af7d2014-01-16 12:41:46 -08001086 for (Backtrace::const_iterator it = backtrace->begin();
1087 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001088 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001089 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1090 // In order for parsing tools to continue to function, the stack dump
1091 // format must at least adhere to this format:
1092 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1093 // The parsers require a single space before and after pc, and two spaces
1094 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1095 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1096 os << prefix << StringPrintf("#%02zu pc ", it->num);
1097 if (!it->map) {
1098 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001099 } else {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001100 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1101 << it->map->name << " (";
1102 if (!it->func_name.empty()) {
1103 os << it->func_name;
1104 if (it->func_offset != 0) {
1105 os << "+" << it->func_offset;
1106 }
1107 } else if (current_method != nullptr && current_method->IsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001108 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1109 os << JniLongName(current_method) << "+"
1110 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001111 } else {
1112 os << "???";
1113 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001114 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001115 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001116 os << "\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001117 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001118#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001119}
1120
Elliott Hughes058a6de2012-05-24 19:13:02 -07001121#if defined(__APPLE__)
1122
1123// TODO: is there any way to get the kernel stack on Mac OS?
1124void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1125
1126#else
1127
Elliott Hughes46e251b2012-05-22 15:10:45 -07001128void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001129 if (tid == GetTid()) {
1130 // There's no point showing that we're reading our stack out of /proc!
1131 return;
1132 }
1133
Elliott Hughes46e251b2012-05-22 15:10:45 -07001134 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1135 std::string kernel_stack;
1136 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001137 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001138 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001139 }
1140
1141 std::vector<std::string> kernel_stack_frames;
1142 Split(kernel_stack, '\n', kernel_stack_frames);
1143 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1144 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1145 kernel_stack_frames.pop_back();
1146 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001147 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1148 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001149 const char* text = kernel_stack_frames[i].c_str();
1150 const char* close_bracket = strchr(text, ']');
1151 if (close_bracket != NULL) {
1152 text = close_bracket + 2;
1153 }
1154 os << prefix;
1155 if (include_count) {
1156 os << StringPrintf("#%02zd ", i);
1157 }
1158 os << text << "\n";
1159 }
1160}
1161
1162#endif
1163
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001164const char* GetAndroidRoot() {
1165 const char* android_root = getenv("ANDROID_ROOT");
1166 if (android_root == NULL) {
1167 if (OS::DirectoryExists("/system")) {
1168 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001169 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001170 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1171 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001172 }
1173 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001174 if (!OS::DirectoryExists(android_root)) {
1175 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001176 return "";
1177 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001178 return android_root;
1179}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001180
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001181const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001182 std::string error_msg;
1183 const char* dir = GetAndroidDataSafe(&error_msg);
1184 if (dir != nullptr) {
1185 return dir;
1186 } else {
1187 LOG(FATAL) << error_msg;
1188 return "";
1189 }
1190}
1191
1192const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001193 const char* android_data = getenv("ANDROID_DATA");
1194 if (android_data == NULL) {
1195 if (OS::DirectoryExists("/data")) {
1196 android_data = "/data";
1197 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001198 *error_msg = "ANDROID_DATA not set and /data does not exist";
1199 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001200 }
1201 }
1202 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001203 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1204 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001205 }
1206 return android_data;
1207}
1208
Alex Lighta59dd802014-07-02 16:28:08 -07001209void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
1210 bool* have_android_data, bool* dalvik_cache_exists) {
1211 CHECK(subdir != nullptr);
1212 std::string error_msg;
1213 const char* android_data = GetAndroidDataSafe(&error_msg);
1214 if (android_data == nullptr) {
1215 *have_android_data = false;
1216 *dalvik_cache_exists = false;
1217 return;
1218 } else {
1219 *have_android_data = true;
1220 }
1221 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1222 *dalvik_cache = dalvik_cache_root + subdir;
1223 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
1224 if (create_if_absent && !*dalvik_cache_exists && strcmp(android_data, "/data") != 0) {
1225 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1226 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1227 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1228 }
1229}
1230
Narayan Kamath11d9f062014-04-23 20:24:57 +01001231std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1232 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001233 const char* android_data = GetAndroidData();
1234 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001235 const std::string dalvik_cache = dalvik_cache_root + subdir;
1236 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001237 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1238 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001239 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001240 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001241 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1242 return "";
1243 }
1244 result = mkdir(dalvik_cache.c_str(), 0700);
1245 if (result != 0) {
1246 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001247 return "";
1248 }
1249 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001250 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001251 return "";
1252 }
1253 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001254 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001255}
1256
Alex Lighta59dd802014-07-02 16:28:08 -07001257bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1258 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001259 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001260 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1261 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001262 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001263 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001264 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001265 cache_file += "/";
1266 cache_file += DexFile::kClassesDex;
1267 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001268 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001269 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1270 return true;
1271}
1272
1273std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1274 std::string ret;
1275 std::string error_msg;
1276 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1277 LOG(FATAL) << error_msg;
1278 }
1279 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001280}
1281
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001282static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001283 // in = /foo/bar/baz
1284 // out = /foo/bar/<isa>/baz
1285 size_t pos = filename->rfind('/');
1286 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1287 filename->insert(pos, "/", 1);
1288 filename->insert(pos + 1, GetInstructionSetString(isa));
1289}
1290
1291std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1292 // location = /system/framework/boot.art
1293 // filename = /system/framework/<isa>/boot.art
1294 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001295 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001296 return filename;
1297}
1298
1299std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1300 // location = /foo/bar/baz.jar
1301 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001302
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001303 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1304 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001305 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001306 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1307 CHECK_EQ('.', odex_location[dot_index]) << location;
1308 odex_location.resize(dot_index + 1);
1309 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1310 odex_location += "odex";
1311 return odex_location;
1312}
1313
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001314bool IsZipMagic(uint32_t magic) {
1315 return (('P' == ((magic >> 0) & 0xff)) &&
1316 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001317}
1318
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001319bool IsDexMagic(uint32_t magic) {
1320 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001321}
1322
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001323bool IsOatMagic(uint32_t magic) {
1324 return (memcmp(reinterpret_cast<const byte*>(magic),
1325 OatHeader::kOatMagic,
1326 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001327}
1328
Brian Carlstrom6449c622014-02-10 23:48:36 -08001329bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1330 const std::string command_line(Join(arg_vector, ' '));
1331
1332 CHECK_GE(arg_vector.size(), 1U) << command_line;
1333
1334 // Convert the args to char pointers.
1335 const char* program = arg_vector[0].c_str();
1336 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001337 for (size_t i = 0; i < arg_vector.size(); ++i) {
1338 const std::string& arg = arg_vector[i];
1339 char* arg_str = const_cast<char*>(arg.c_str());
1340 CHECK(arg_str != nullptr) << i;
1341 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001342 }
1343 args.push_back(NULL);
1344
1345 // fork and exec
1346 pid_t pid = fork();
1347 if (pid == 0) {
1348 // no allocation allowed between fork and exec
1349
1350 // change process groups, so we don't get reaped by ProcessManager
1351 setpgid(0, 0);
1352
1353 execv(program, &args[0]);
1354
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001355 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1356 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001357 } else {
1358 if (pid == -1) {
1359 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1360 command_line.c_str(), strerror(errno));
1361 return false;
1362 }
1363
1364 // wait for subprocess to finish
1365 int status;
1366 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1367 if (got_pid != pid) {
1368 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1369 "wanted %d, got %d: %s",
1370 command_line.c_str(), pid, got_pid, strerror(errno));
1371 return false;
1372 }
1373 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1374 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1375 command_line.c_str());
1376 return false;
1377 }
1378 }
1379 return true;
1380}
1381
Tong Shen547cdfd2014-08-05 01:54:19 -07001382void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001383 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001384}
1385
1386void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001387 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001388}
1389
1390void PushWord(std::vector<uint8_t>* buf, int data) {
1391 buf->push_back(data & 0xff);
1392 buf->push_back((data >> 8) & 0xff);
1393 buf->push_back((data >> 16) & 0xff);
1394 buf->push_back((data >> 24) & 0xff);
1395}
1396
Elliott Hughes42ee1422011-09-06 12:33:32 -07001397} // namespace art