blob: 4c52229120c6ef174fb697c89206bb8138ac2a09 [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
Brian Carlstrom29212012013-09-12 22:18:30 -070086void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_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 }
99#else
100 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700101 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700102 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700103 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
104#endif
105}
106
Elliott Hughesd92bec42011-09-02 17:04:36 -0700107bool ReadFileToString(const std::string& file_name, std::string* result) {
Ian Rogers700a4022014-05-19 16:49:03 -0700108 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800109 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700110 return false;
111 }
buzbeec143c552011-08-20 17:38:58 -0700112
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700113 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700114 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800115 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700116 if (n == -1) {
117 return false;
buzbeec143c552011-08-20 17:38:58 -0700118 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700119 if (n == 0) {
120 return true;
121 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700122 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700123 }
buzbeec143c552011-08-20 17:38:58 -0700124}
125
Elliott Hughese27955c2011-08-26 15:21:24 -0700126std::string GetIsoDate() {
127 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700128 tm tmbuf;
129 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700130 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
131 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
132 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
133}
134
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800136#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700137 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700138 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700139 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800140#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700141 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700143 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800144#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700145}
146
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800148#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700149 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800150 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700151 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800152#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700153 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700155 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800157}
158
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800160#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700161 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700162 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700163 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800164#else
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(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800168#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700169}
170
Elliott Hughes0512f022012-03-15 22:10:52 -0700171uint64_t ThreadCpuNanoTime() {
172#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700173 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700174 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700175 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0512f022012-03-15 22:10:52 -0700176#else
177 UNIMPLEMENTED(WARNING);
178 return -1;
179#endif
180}
181
Ian Rogers56edc432013-01-18 16:51:51 -0800182void NanoSleep(uint64_t ns) {
183 timespec tm;
184 tm.tv_sec = 0;
185 tm.tv_nsec = ns;
186 nanosleep(&tm, NULL);
187}
188
Brian Carlstrombcc29262012-11-02 11:36:03 -0700189void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
190 int64_t endSec;
191
192 if (absolute) {
193#if !defined(__APPLE__)
194 clock_gettime(clock, ts);
195#else
196 UNUSED(clock);
197 timeval tv;
198 gettimeofday(&tv, NULL);
199 ts->tv_sec = tv.tv_sec;
200 ts->tv_nsec = tv.tv_usec * 1000;
201#endif
202 } else {
203 ts->tv_sec = 0;
204 ts->tv_nsec = 0;
205 }
206 endSec = ts->tv_sec + ms / 1000;
207 if (UNLIKELY(endSec >= 0x7fffffff)) {
208 std::ostringstream ss;
209 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
210 endSec = 0x7ffffffe;
211 }
212 ts->tv_sec = endSec;
213 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
214
215 // Catch rollover.
216 if (ts->tv_nsec >= 1000000000L) {
217 ts->tv_sec++;
218 ts->tv_nsec -= 1000000000L;
219 }
220}
221
Ian Rogersef7d42f2014-01-06 12:55:46 -0800222std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700223 if (java_descriptor == NULL) {
224 return "null";
225 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700226 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700227}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700228
Ian Rogersef7d42f2014-01-06 12:55:46 -0800229std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800230 if (klass == NULL) {
231 return "null";
232 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700233 std::string temp;
234 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800235}
236
Ian Rogers1ff3c982014-08-12 02:30:58 -0700237std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700238 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700239 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700240 size_t dim = 0;
241 while (*c == '[') {
242 dim++;
243 c++;
244 }
245
246 // Reference or primitive?
247 if (*c == 'L') {
248 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700249 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700250 } else {
251 // "[[B" -> "byte[][]".
252 // To make life easier, we make primitives look like unqualified
253 // reference types.
254 switch (*c) {
255 case 'B': c = "byte;"; break;
256 case 'C': c = "char;"; break;
257 case 'D': c = "double;"; break;
258 case 'F': c = "float;"; break;
259 case 'I': c = "int;"; break;
260 case 'J': c = "long;"; break;
261 case 'S': c = "short;"; break;
262 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700263 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700264 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700265 }
266 }
267
268 // At this point, 'c' is a string of the form "fully/qualified/Type;"
269 // or "primitive;". Rewrite the type with '.' instead of '/':
270 std::string result;
271 const char* p = c;
272 while (*p != ';') {
273 char ch = *p++;
274 if (ch == '/') {
275 ch = '.';
276 }
277 result.push_back(ch);
278 }
279 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700280 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700281 result += "[]";
282 }
283 return result;
284}
285
Ian Rogers68d8b422014-07-17 11:09:10 -0700286std::string PrettyDescriptor(Primitive::Type type) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700287 return PrettyDescriptor(Primitive::Descriptor(type));
Ian Rogers68d8b422014-07-17 11:09:10 -0700288}
289
Ian Rogersef7d42f2014-01-06 12:55:46 -0800290std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700291 if (f == NULL) {
292 return "null";
293 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700294 std::string result;
295 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700296 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700297 result += ' ';
298 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700299 StackHandleScope<1> hs(Thread::Current());
300 result += PrettyDescriptor(FieldHelper(hs.NewHandle(f)).GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700301 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700302 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700303 return result;
304}
305
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700306std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800307 if (field_idx >= dex_file.NumFieldIds()) {
308 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
309 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700310 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
311 std::string result;
312 if (with_type) {
313 result += dex_file.GetFieldTypeDescriptor(field_id);
314 result += ' ';
315 }
316 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
317 result += '.';
318 result += dex_file.GetFieldName(field_id);
319 return result;
320}
321
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700322std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800323 if (type_idx >= dex_file.NumTypeIds()) {
324 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
325 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700326 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700327 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700328}
329
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700330std::string PrettyArguments(const char* signature) {
331 std::string result;
332 result += '(';
333 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700334 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700335 while (*signature != ')') {
336 size_t argument_length = 0;
337 while (signature[argument_length] == '[') {
338 ++argument_length;
339 }
340 if (signature[argument_length] == 'L') {
341 argument_length = (strchr(signature, ';') - signature + 1);
342 } else {
343 ++argument_length;
344 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700345 {
346 std::string argument_descriptor(signature, argument_length);
347 result += PrettyDescriptor(argument_descriptor.c_str());
348 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700349 if (signature[argument_length] != ')') {
350 result += ", ";
351 }
352 signature += argument_length;
353 }
354 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700355 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700356 result += ')';
357 return result;
358}
359
360std::string PrettyReturnType(const char* signature) {
361 const char* return_type = strchr(signature, ')');
362 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700363 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700364 return PrettyDescriptor(return_type);
365}
366
Ian Rogersef7d42f2014-01-06 12:55:46 -0800367std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800368 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700369 return "null";
370 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700371 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700372 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700373 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800374 if (UNLIKELY(m->IsFastNative())) {
375 result += "!";
376 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700377 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700378 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700379 std::string sig_as_string(signature.ToString());
380 if (signature == Signature::NoSignature()) {
381 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700382 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700383 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
384 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700385 }
386 return result;
387}
388
Ian Rogers0571d352011-11-03 19:51:38 -0700389std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800390 if (method_idx >= dex_file.NumMethodIds()) {
391 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
392 }
Ian Rogers0571d352011-11-03 19:51:38 -0700393 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
394 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
395 result += '.';
396 result += dex_file.GetMethodName(method_id);
397 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700398 const Signature signature = dex_file.GetMethodSignature(method_id);
399 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());
Ian Rogers0571d352011-11-03 19:51:38 -0700405 }
406 return result;
407}
408
Ian Rogersef7d42f2014-01-06 12:55:46 -0800409std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700410 if (obj == NULL) {
411 return "null";
412 }
413 if (obj->GetClass() == NULL) {
414 return "(raw)";
415 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700416 std::string temp;
417 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700418 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700419 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700420 }
421 return result;
422}
423
Ian Rogersef7d42f2014-01-06 12:55:46 -0800424std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700425 if (c == NULL) {
426 return "null";
427 }
428 std::string result;
429 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800430 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700431 result += ">";
432 return result;
433}
434
Ian Rogersef7d42f2014-01-06 12:55:46 -0800435std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700436 if (c == NULL) {
437 return "null";
438 }
439 std::string result;
440 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800441 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700442 result += ",";
443 result += PrettyTypeOf(c->GetClassLoader());
444 // TODO: add an identifying hash value for the loader
445 result += ">";
446 return result;
447}
448
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800449std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700450 // The byte thresholds at which we display amounts. A byte count is displayed
451 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800452 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700453 0, // B up to...
454 3*1024, // KB up to...
455 2*1024*1024, // MB up to...
456 1024*1024*1024 // GB from here.
457 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800458 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700459 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800460 const char* negative_str = "";
461 if (byte_count < 0) {
462 negative_str = "-";
463 byte_count = -byte_count;
464 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700465 int i = arraysize(kUnitThresholds);
466 while (--i > 0) {
467 if (byte_count >= kUnitThresholds[i]) {
468 break;
469 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800470 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800471 return StringPrintf("%s%" PRId64 "%s",
472 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800473}
474
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700475std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800476 if (nano_duration == 0) {
477 return "0";
478 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700479 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
480 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700481 }
482}
483
484TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
485 const uint64_t one_sec = 1000 * 1000 * 1000;
486 const uint64_t one_ms = 1000 * 1000;
487 const uint64_t one_us = 1000;
488 if (nano_duration >= one_sec) {
489 return kTimeUnitSecond;
490 } else if (nano_duration >= one_ms) {
491 return kTimeUnitMillisecond;
492 } else if (nano_duration >= one_us) {
493 return kTimeUnitMicrosecond;
494 } else {
495 return kTimeUnitNanosecond;
496 }
497}
498
499uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
500 const uint64_t one_sec = 1000 * 1000 * 1000;
501 const uint64_t one_ms = 1000 * 1000;
502 const uint64_t one_us = 1000;
503
504 switch (time_unit) {
505 case kTimeUnitSecond:
506 return one_sec;
507 case kTimeUnitMillisecond:
508 return one_ms;
509 case kTimeUnitMicrosecond:
510 return one_us;
511 case kTimeUnitNanosecond:
512 return 1;
513 }
514 return 0;
515}
516
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700517std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
518 size_t max_fraction_digits) {
519 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700520 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700521 switch (time_unit) {
522 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800523 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700524 break;
525 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800526 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700527 break;
528 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800529 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700530 break;
531 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800532 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700533 break;
534 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700535 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700536 uint64_t fractional_part = nano_duration % divisor;
537 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800538 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700539 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700540 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700541 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700542 char fraction_buffer[kMaxDigits];
543 char* ptr = fraction_buffer;
544 uint64_t multiplier = 10;
545 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700546 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700547 multiplier *= 10;
548 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700549 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800550 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700551 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700552 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
553 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800554 }
555}
556
Ian Rogers576ca0c2014-06-06 15:58:22 -0700557std::string PrintableChar(uint16_t ch) {
558 std::string result;
559 result += '\'';
560 if (NeedsEscaping(ch)) {
561 StringAppendF(&result, "\\u%04x", ch);
562 } else {
563 result += ch;
564 }
565 result += '\'';
566 return result;
567}
568
Elliott Hughes82914b62012-04-09 15:56:29 -0700569std::string PrintableString(const std::string& utf) {
570 std::string result;
571 result += '"';
572 const char* p = utf.c_str();
573 size_t char_count = CountModifiedUtf8Chars(p);
574 for (size_t i = 0; i < char_count; ++i) {
575 uint16_t ch = GetUtf16FromUtf8(&p);
576 if (ch == '\\') {
577 result += "\\\\";
578 } else if (ch == '\n') {
579 result += "\\n";
580 } else if (ch == '\r') {
581 result += "\\r";
582 } else if (ch == '\t') {
583 result += "\\t";
584 } else if (NeedsEscaping(ch)) {
585 StringAppendF(&result, "\\u%04x", ch);
586 } else {
587 result += ch;
588 }
589 }
590 result += '"';
591 return result;
592}
593
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800594// 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 -0700595std::string MangleForJni(const std::string& s) {
596 std::string result;
597 size_t char_count = CountModifiedUtf8Chars(s.c_str());
598 const char* cp = &s[0];
599 for (size_t i = 0; i < char_count; ++i) {
600 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800601 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
602 result.push_back(ch);
603 } else if (ch == '.' || ch == '/') {
604 result += "_";
605 } else if (ch == '_') {
606 result += "_1";
607 } else if (ch == ';') {
608 result += "_2";
609 } else if (ch == '[') {
610 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700611 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800612 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700613 }
614 }
615 return result;
616}
617
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700618std::string DotToDescriptor(const char* class_name) {
619 std::string descriptor(class_name);
620 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
621 if (descriptor.length() > 0 && descriptor[0] != '[') {
622 descriptor = "L" + descriptor + ";";
623 }
624 return descriptor;
625}
626
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800627std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800628 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700629 if (length > 1) {
630 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
631 // Descriptors have the leading 'L' and trailing ';' stripped.
632 std::string result(descriptor + 1, length - 2);
633 std::replace(result.begin(), result.end(), '/', '.');
634 return result;
635 } else {
636 // For arrays the 'L' and ';' remain intact.
637 std::string result(descriptor);
638 std::replace(result.begin(), result.end(), '/', '.');
639 return result;
640 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800641 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700642 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800643 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800644}
645
646std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800647 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800648 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
649 std::string result(descriptor + 1, length - 2);
650 return result;
651 }
652 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700653}
654
Ian Rogersef7d42f2014-01-06 12:55:46 -0800655std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700656 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700657 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700658 CHECK_EQ(class_name[0], 'L') << class_name;
659 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700660 class_name.erase(0, 1);
661 class_name.erase(class_name.size() - 1, 1);
662
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700663 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700664
665 std::string short_name;
666 short_name += "Java_";
667 short_name += MangleForJni(class_name);
668 short_name += "_";
669 short_name += MangleForJni(method_name);
670 return short_name;
671}
672
Ian Rogersef7d42f2014-01-06 12:55:46 -0800673std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700674 std::string long_name;
675 long_name += JniShortName(m);
676 long_name += "__";
677
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700678 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700679 signature.erase(0, 1);
680 signature.erase(signature.begin() + signature.find(')'), signature.end());
681
682 long_name += MangleForJni(signature);
683
684 return long_name;
685}
686
jeffhao10037c82012-01-23 15:06:23 -0800687// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700688uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700689 0x00000000, // 00..1f low control characters; nothing valid
690 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
691 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
692 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700693};
694
jeffhao10037c82012-01-23 15:06:23 -0800695// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
696bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700697 /*
698 * It's a multibyte encoded character. Decode it and analyze. We
699 * accept anything that isn't (a) an improperly encoded low value,
700 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
701 * control character, or (e) a high space, layout, or special
702 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
703 * U+fff0..U+ffff). This is all specified in the dex format
704 * document.
705 */
706
707 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
708
709 // Perform follow-up tests based on the high 8 bits.
710 switch (utf16 >> 8) {
711 case 0x00:
712 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
713 return (utf16 > 0x00a0);
714 case 0xd8:
715 case 0xd9:
716 case 0xda:
717 case 0xdb:
718 // It's a leading surrogate. Check to see that a trailing
719 // surrogate follows.
720 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
721 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
722 case 0xdc:
723 case 0xdd:
724 case 0xde:
725 case 0xdf:
726 // It's a trailing surrogate, which is not valid at this point.
727 return false;
728 case 0x20:
729 case 0xff:
730 // It's in the range that has spaces, controls, and specials.
731 switch (utf16 & 0xfff8) {
732 case 0x2000:
733 case 0x2008:
734 case 0x2028:
735 case 0xfff0:
736 case 0xfff8:
737 return false;
738 }
739 break;
740 }
741 return true;
742}
743
744/* Return whether the pointed-at modified-UTF-8 encoded character is
745 * valid as part of a member name, updating the pointer to point past
746 * the consumed character. This will consume two encoded UTF-16 code
747 * points if the character is encoded as a surrogate pair. Also, if
748 * this function returns false, then the given pointer may only have
749 * been partially advanced.
750 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700751static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700752 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700753 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700754 // It's low-ascii, so check the table.
755 uint32_t wordIdx = c >> 5;
756 uint32_t bitIdx = c & 0x1f;
757 (*pUtf8Ptr)++;
758 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
759 }
760
761 // It's a multibyte encoded character. Call a non-inline function
762 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800763 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
764}
765
766bool IsValidMemberName(const char* s) {
767 bool angle_name = false;
768
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700769 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800770 case '\0':
771 // The empty string is not a valid name.
772 return false;
773 case '<':
774 angle_name = true;
775 s++;
776 break;
777 }
778
779 while (true) {
780 switch (*s) {
781 case '\0':
782 return !angle_name;
783 case '>':
784 return angle_name && s[1] == '\0';
785 }
786
787 if (!IsValidPartOfMemberNameUtf8(&s)) {
788 return false;
789 }
790 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700791}
792
Elliott Hughes906e6852011-10-28 14:52:10 -0700793enum ClassNameType { kName, kDescriptor };
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700794static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700795 int arrayCount = 0;
796 while (*s == '[') {
797 arrayCount++;
798 s++;
799 }
800
801 if (arrayCount > 255) {
802 // Arrays may have no more than 255 dimensions.
803 return false;
804 }
805
806 if (arrayCount != 0) {
807 /*
808 * If we're looking at an array of some sort, then it doesn't
809 * matter if what is being asked for is a class name; the
810 * format looks the same as a type descriptor in that case, so
811 * treat it as such.
812 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700813 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700814 }
815
Elliott Hughes906e6852011-10-28 14:52:10 -0700816 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700817 /*
818 * We are looking for a descriptor. Either validate it as a
819 * single-character primitive type, or continue on to check the
820 * embedded class name (bracketed by "L" and ";").
821 */
822 switch (*(s++)) {
823 case 'B':
824 case 'C':
825 case 'D':
826 case 'F':
827 case 'I':
828 case 'J':
829 case 'S':
830 case 'Z':
831 // These are all single-character descriptors for primitive types.
832 return (*s == '\0');
833 case 'V':
834 // Non-array void is valid, but you can't have an array of void.
835 return (arrayCount == 0) && (*s == '\0');
836 case 'L':
837 // Class name: Break out and continue below.
838 break;
839 default:
840 // Oddball descriptor character.
841 return false;
842 }
843 }
844
845 /*
846 * We just consumed the 'L' that introduces a class name as part
847 * of a type descriptor, or we are looking for an unadorned class
848 * name.
849 */
850
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700851 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700852 for (;;) {
853 uint8_t c = (uint8_t) *s;
854 switch (c) {
855 case '\0':
856 /*
857 * Premature end for a type descriptor, but valid for
858 * a class name as long as we haven't encountered an
859 * empty component (including the degenerate case of
860 * the empty string "").
861 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700862 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700863 case ';':
864 /*
865 * Invalid character for a class name, but the
866 * legitimate end of a type descriptor. In the latter
867 * case, make sure that this is the end of the string
868 * and that it doesn't end with an empty component
869 * (including the degenerate case of "L;").
870 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700871 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700872 case '/':
873 case '.':
874 if (c != separator) {
875 // The wrong separator character.
876 return false;
877 }
878 if (sepOrFirst) {
879 // Separator at start or two separators in a row.
880 return false;
881 }
882 sepOrFirst = true;
883 s++;
884 break;
885 default:
jeffhao10037c82012-01-23 15:06:23 -0800886 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700887 return false;
888 }
889 sepOrFirst = false;
890 break;
891 }
892 }
893}
894
Elliott Hughes906e6852011-10-28 14:52:10 -0700895bool IsValidBinaryClassName(const char* s) {
896 return IsValidClassName(s, kName, '.');
897}
898
899bool IsValidJniClassName(const char* s) {
900 return IsValidClassName(s, kName, '/');
901}
902
903bool IsValidDescriptor(const char* s) {
904 return IsValidClassName(s, kDescriptor, '/');
905}
906
Elliott Hughes48436bb2012-02-07 15:23:28 -0800907void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700908 const char* p = s.data();
909 const char* end = p + s.size();
910 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800911 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700912 ++p;
913 } else {
914 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800915 while (++p != end && *p != separator) {
916 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700917 }
918 result.push_back(std::string(start, p - start));
919 }
920 }
921}
922
Dave Allison70202782013-10-22 17:52:19 -0700923std::string Trim(std::string s) {
924 std::string result;
925 unsigned int start_index = 0;
926 unsigned int end_index = s.size() - 1;
927
928 // Skip initial whitespace.
929 while (start_index < s.size()) {
930 if (!isspace(s[start_index])) {
931 break;
932 }
933 start_index++;
934 }
935
936 // Skip terminating whitespace.
937 while (end_index >= start_index) {
938 if (!isspace(s[end_index])) {
939 break;
940 }
941 end_index--;
942 }
943
944 // All spaces, no beef.
945 if (end_index < start_index) {
946 return "";
947 }
948 // Start_index is the first non-space, end_index is the last one.
949 return s.substr(start_index, end_index - start_index + 1);
950}
951
Elliott Hughes48436bb2012-02-07 15:23:28 -0800952template <typename StringT>
953std::string Join(std::vector<StringT>& strings, char separator) {
954 if (strings.empty()) {
955 return "";
956 }
957
958 std::string result(strings[0]);
959 for (size_t i = 1; i < strings.size(); ++i) {
960 result += separator;
961 result += strings[i];
962 }
963 return result;
964}
965
966// Explicit instantiations.
967template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
968template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
969template std::string Join<char*>(std::vector<char*>& strings, char separator);
970
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800971bool StartsWith(const std::string& s, const char* prefix) {
972 return s.compare(0, strlen(prefix), prefix) == 0;
973}
974
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700975bool EndsWith(const std::string& s, const char* suffix) {
976 size_t suffix_length = strlen(suffix);
977 size_t string_length = s.size();
978 if (suffix_length > string_length) {
979 return false;
980 }
981 size_t offset = string_length - suffix_length;
982 return s.compare(offset, suffix_length, suffix) == 0;
983}
984
Elliott Hughes22869a92012-03-27 14:08:24 -0700985void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700986 int hasAt = 0;
987 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700988 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700989 while (*s) {
990 if (*s == '.') {
991 hasDot = 1;
992 } else if (*s == '@') {
993 hasAt = 1;
994 }
995 s++;
996 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700997 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700998 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700999 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001000 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001001 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001002 }
1003#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001004 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001005 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1006 strncpy(buf, s, sizeof(buf)-1);
1007 buf[sizeof(buf)-1] = '\0';
1008 errno = pthread_setname_np(pthread_self(), buf);
1009 if (errno != 0) {
1010 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1011 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -07001012#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -07001013 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001014#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -07001015 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -07001016#else
Elliott Hughes22869a92012-03-27 14:08:24 -07001017 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001018#endif
1019}
1020
Brian Carlstrom29212012013-09-12 22:18:30 -07001021void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1022 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001023 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001024 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001025 return;
1026 }
1027 // Skip the command, which may contain spaces.
1028 stats = stats.substr(stats.find(')') + 2);
1029 // Extract the three fields we care about.
1030 std::vector<std::string> fields;
1031 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001032 *state = fields[0][0];
1033 *utime = strtoull(fields[11].c_str(), NULL, 10);
1034 *stime = strtoull(fields[12].c_str(), NULL, 10);
1035 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001036}
1037
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001038std::string GetSchedulerGroupName(pid_t tid) {
1039 // /proc/<pid>/cgroup looks like this:
1040 // 2:devices:/
1041 // 1:cpuacct,cpu:/
1042 // We want the third field from the line whose second field contains the "cpu" token.
1043 std::string cgroup_file;
1044 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1045 return "";
1046 }
1047 std::vector<std::string> cgroup_lines;
1048 Split(cgroup_file, '\n', cgroup_lines);
1049 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1050 std::vector<std::string> cgroup_fields;
1051 Split(cgroup_lines[i], ':', cgroup_fields);
1052 std::vector<std::string> cgroups;
1053 Split(cgroup_fields[1], ',', cgroups);
1054 for (size_t i = 0; i < cgroups.size(); ++i) {
1055 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001056 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001057 }
1058 }
1059 }
1060 return "";
1061}
1062
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001063void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Kenny Root067d20f2014-03-05 14:57:21 -08001064 mirror::ArtMethod* current_method) {
1065 // We may be called from contexts where current_method is not null, so we must assert this.
1066 if (current_method != nullptr) {
1067 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1068 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001069#ifdef __linux__
Ian Rogers700a4022014-05-19 16:49:03 -07001070 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001071 if (!backtrace->Unwind(0)) {
1072 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001073 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001074 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001075 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001076 return;
1077 }
1078
Christopher Ferris943af7d2014-01-16 12:41:46 -08001079 for (Backtrace::const_iterator it = backtrace->begin();
1080 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001081 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001082 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1083 // In order for parsing tools to continue to function, the stack dump
1084 // format must at least adhere to this format:
1085 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1086 // The parsers require a single space before and after pc, and two spaces
1087 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1088 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1089 os << prefix << StringPrintf("#%02zu pc ", it->num);
1090 if (!it->map) {
1091 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001092 } else {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001093 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1094 << it->map->name << " (";
1095 if (!it->func_name.empty()) {
1096 os << it->func_name;
1097 if (it->func_offset != 0) {
1098 os << "+" << it->func_offset;
1099 }
1100 } else if (current_method != nullptr && current_method->IsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001101 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1102 os << JniLongName(current_method) << "+"
1103 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001104 } else {
1105 os << "???";
1106 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001107 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001108 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001109 os << "\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001110 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001111#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001112}
1113
Elliott Hughes058a6de2012-05-24 19:13:02 -07001114#if defined(__APPLE__)
1115
1116// TODO: is there any way to get the kernel stack on Mac OS?
1117void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1118
1119#else
1120
Elliott Hughes46e251b2012-05-22 15:10:45 -07001121void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001122 if (tid == GetTid()) {
1123 // There's no point showing that we're reading our stack out of /proc!
1124 return;
1125 }
1126
Elliott Hughes46e251b2012-05-22 15:10:45 -07001127 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1128 std::string kernel_stack;
1129 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001130 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001131 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001132 }
1133
1134 std::vector<std::string> kernel_stack_frames;
1135 Split(kernel_stack, '\n', kernel_stack_frames);
1136 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1137 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1138 kernel_stack_frames.pop_back();
1139 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001140 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1141 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001142 const char* text = kernel_stack_frames[i].c_str();
1143 const char* close_bracket = strchr(text, ']');
1144 if (close_bracket != NULL) {
1145 text = close_bracket + 2;
1146 }
1147 os << prefix;
1148 if (include_count) {
1149 os << StringPrintf("#%02zd ", i);
1150 }
1151 os << text << "\n";
1152 }
1153}
1154
1155#endif
1156
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001157const char* GetAndroidRoot() {
1158 const char* android_root = getenv("ANDROID_ROOT");
1159 if (android_root == NULL) {
1160 if (OS::DirectoryExists("/system")) {
1161 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001162 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001163 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1164 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001165 }
1166 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001167 if (!OS::DirectoryExists(android_root)) {
1168 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001169 return "";
1170 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001171 return android_root;
1172}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001173
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001174const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001175 std::string error_msg;
1176 const char* dir = GetAndroidDataSafe(&error_msg);
1177 if (dir != nullptr) {
1178 return dir;
1179 } else {
1180 LOG(FATAL) << error_msg;
1181 return "";
1182 }
1183}
1184
1185const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001186 const char* android_data = getenv("ANDROID_DATA");
1187 if (android_data == NULL) {
1188 if (OS::DirectoryExists("/data")) {
1189 android_data = "/data";
1190 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001191 *error_msg = "ANDROID_DATA not set and /data does not exist";
1192 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001193 }
1194 }
1195 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001196 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1197 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001198 }
1199 return android_data;
1200}
1201
Alex Lighta59dd802014-07-02 16:28:08 -07001202void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
1203 bool* have_android_data, bool* dalvik_cache_exists) {
1204 CHECK(subdir != nullptr);
1205 std::string error_msg;
1206 const char* android_data = GetAndroidDataSafe(&error_msg);
1207 if (android_data == nullptr) {
1208 *have_android_data = false;
1209 *dalvik_cache_exists = false;
1210 return;
1211 } else {
1212 *have_android_data = true;
1213 }
1214 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1215 *dalvik_cache = dalvik_cache_root + subdir;
1216 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
1217 if (create_if_absent && !*dalvik_cache_exists && strcmp(android_data, "/data") != 0) {
1218 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1219 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1220 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1221 }
1222}
1223
Narayan Kamath11d9f062014-04-23 20:24:57 +01001224std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1225 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001226 const char* android_data = GetAndroidData();
1227 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001228 const std::string dalvik_cache = dalvik_cache_root + subdir;
1229 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001230 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1231 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001232 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001233 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001234 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1235 return "";
1236 }
1237 result = mkdir(dalvik_cache.c_str(), 0700);
1238 if (result != 0) {
1239 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001240 return "";
1241 }
1242 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001243 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001244 return "";
1245 }
1246 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001247 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001248}
1249
Alex Lighta59dd802014-07-02 16:28:08 -07001250bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1251 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001252 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001253 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1254 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001255 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001256 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001257 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001258 cache_file += "/";
1259 cache_file += DexFile::kClassesDex;
1260 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001261 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001262 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1263 return true;
1264}
1265
1266std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1267 std::string ret;
1268 std::string error_msg;
1269 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1270 LOG(FATAL) << error_msg;
1271 }
1272 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001273}
1274
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001275static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001276 // in = /foo/bar/baz
1277 // out = /foo/bar/<isa>/baz
1278 size_t pos = filename->rfind('/');
1279 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1280 filename->insert(pos, "/", 1);
1281 filename->insert(pos + 1, GetInstructionSetString(isa));
1282}
1283
1284std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1285 // location = /system/framework/boot.art
1286 // filename = /system/framework/<isa>/boot.art
1287 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001288 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001289 return filename;
1290}
1291
1292std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1293 // location = /foo/bar/baz.jar
1294 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001295
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001296 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1297 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001298 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001299 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1300 CHECK_EQ('.', odex_location[dot_index]) << location;
1301 odex_location.resize(dot_index + 1);
1302 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1303 odex_location += "odex";
1304 return odex_location;
1305}
1306
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001307bool IsZipMagic(uint32_t magic) {
1308 return (('P' == ((magic >> 0) & 0xff)) &&
1309 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001310}
1311
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001312bool IsDexMagic(uint32_t magic) {
1313 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001314}
1315
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001316bool IsOatMagic(uint32_t magic) {
1317 return (memcmp(reinterpret_cast<const byte*>(magic),
1318 OatHeader::kOatMagic,
1319 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001320}
1321
Brian Carlstrom6449c622014-02-10 23:48:36 -08001322bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1323 const std::string command_line(Join(arg_vector, ' '));
1324
1325 CHECK_GE(arg_vector.size(), 1U) << command_line;
1326
1327 // Convert the args to char pointers.
1328 const char* program = arg_vector[0].c_str();
1329 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001330 for (size_t i = 0; i < arg_vector.size(); ++i) {
1331 const std::string& arg = arg_vector[i];
1332 char* arg_str = const_cast<char*>(arg.c_str());
1333 CHECK(arg_str != nullptr) << i;
1334 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001335 }
1336 args.push_back(NULL);
1337
1338 // fork and exec
1339 pid_t pid = fork();
1340 if (pid == 0) {
1341 // no allocation allowed between fork and exec
1342
1343 // change process groups, so we don't get reaped by ProcessManager
1344 setpgid(0, 0);
1345
1346 execv(program, &args[0]);
1347
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001348 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1349 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001350 } else {
1351 if (pid == -1) {
1352 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1353 command_line.c_str(), strerror(errno));
1354 return false;
1355 }
1356
1357 // wait for subprocess to finish
1358 int status;
1359 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1360 if (got_pid != pid) {
1361 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1362 "wanted %d, got %d: %s",
1363 command_line.c_str(), pid, got_pid, strerror(errno));
1364 return false;
1365 }
1366 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1367 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1368 command_line.c_str());
1369 return false;
1370 }
1371 }
1372 return true;
1373}
1374
Tong Shen547cdfd2014-08-05 01:54:19 -07001375void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001376 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001377}
1378
1379void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001380 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001381}
1382
1383void PushWord(std::vector<uint8_t>* buf, int data) {
1384 buf->push_back(data & 0xff);
1385 buf->push_back((data >> 8) & 0xff);
1386 buf->push_back((data >> 16) & 0xff);
1387 buf->push_back((data >> 24) & 0xff);
1388}
1389
Elliott Hughes42ee1422011-09-06 12:33:32 -07001390} // namespace art