blob: c4e84f3473a212d6605e58d46287a1d07c566070 [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 Hughes11d1b0c2012-01-23 16:57:47 -080069#else
70 // Neither bionic nor glibc exposes gettid(2).
71 return syscall(__NR_gettid);
72#endif
73}
74
Elliott Hughes289be852012-06-12 13:57:20 -070075std::string GetThreadName(pid_t tid) {
76 std::string result;
77 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070078 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070079 } else {
80 result = "<unknown>";
81 }
82 return result;
83}
84
Elliott Hughes307091d2014-08-27 11:47:01 -070085void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070086#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070087 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070088 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070089
90 // Check whether stack_addr is the base or end of the stack.
91 // (On Mac OS 10.7, it's the end.)
92 int stack_variable;
93 if (stack_addr > &stack_variable) {
Brian Carlstrom29212012013-09-12 22:18:30 -070094 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070095 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070096 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070097 }
Elliott Hughes307091d2014-08-27 11:47:01 -070098
99 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
100 pthread_attr_t attributes;
101 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
102 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
103 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700104#else
105 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700106 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700107 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes307091d2014-08-27 11:47:01 -0700108 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700109 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
110#endif
111}
112
Elliott Hughesd92bec42011-09-02 17:04:36 -0700113bool ReadFileToString(const std::string& file_name, std::string* result) {
Ian Rogers700a4022014-05-19 16:49:03 -0700114 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800115 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700116 return false;
117 }
buzbeec143c552011-08-20 17:38:58 -0700118
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700119 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700120 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800121 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700122 if (n == -1) {
123 return false;
buzbeec143c552011-08-20 17:38:58 -0700124 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700125 if (n == 0) {
126 return true;
127 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700128 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700129 }
buzbeec143c552011-08-20 17:38:58 -0700130}
131
Elliott Hughese27955c2011-08-26 15:21:24 -0700132std::string GetIsoDate() {
133 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700134 tm tmbuf;
135 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700136 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
137 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
138 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
139}
140
Elliott Hughes7162ad92011-10-27 14:08:42 -0700141uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700143 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700144 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700145 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800146#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700147 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800148 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700149 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700151}
152
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800153uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700155 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800156 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700157 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800158#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700159 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800160 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700161 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800163}
164
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700165uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800166#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700167 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700168 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700169 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800170#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700171 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800172 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700173 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800174#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700175}
176
Elliott Hughes0512f022012-03-15 22:10:52 -0700177uint64_t ThreadCpuNanoTime() {
178#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700179 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700180 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700181 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0512f022012-03-15 22:10:52 -0700182#else
183 UNIMPLEMENTED(WARNING);
184 return -1;
185#endif
186}
187
Ian Rogers56edc432013-01-18 16:51:51 -0800188void NanoSleep(uint64_t ns) {
189 timespec tm;
190 tm.tv_sec = 0;
191 tm.tv_nsec = ns;
192 nanosleep(&tm, NULL);
193}
194
Brian Carlstrombcc29262012-11-02 11:36:03 -0700195void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
196 int64_t endSec;
197
198 if (absolute) {
199#if !defined(__APPLE__)
200 clock_gettime(clock, ts);
201#else
202 UNUSED(clock);
203 timeval tv;
204 gettimeofday(&tv, NULL);
205 ts->tv_sec = tv.tv_sec;
206 ts->tv_nsec = tv.tv_usec * 1000;
207#endif
208 } else {
209 ts->tv_sec = 0;
210 ts->tv_nsec = 0;
211 }
212 endSec = ts->tv_sec + ms / 1000;
213 if (UNLIKELY(endSec >= 0x7fffffff)) {
214 std::ostringstream ss;
215 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
216 endSec = 0x7ffffffe;
217 }
218 ts->tv_sec = endSec;
219 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
220
221 // Catch rollover.
222 if (ts->tv_nsec >= 1000000000L) {
223 ts->tv_sec++;
224 ts->tv_nsec -= 1000000000L;
225 }
226}
227
Ian Rogersef7d42f2014-01-06 12:55:46 -0800228std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700229 if (java_descriptor == NULL) {
230 return "null";
231 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700232 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700233}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700234
Ian Rogersef7d42f2014-01-06 12:55:46 -0800235std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800236 if (klass == NULL) {
237 return "null";
238 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700239 std::string temp;
240 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800241}
242
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700243std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700244 // Count the number of '['s to get the dimensionality.
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700245 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700246 size_t dim = 0;
247 while (*c == '[') {
248 dim++;
249 c++;
250 }
251
252 // Reference or primitive?
253 if (*c == 'L') {
254 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700255 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700256 } else {
257 // "[[B" -> "byte[][]".
258 // To make life easier, we make primitives look like unqualified
259 // reference types.
260 switch (*c) {
261 case 'B': c = "byte;"; break;
262 case 'C': c = "char;"; break;
263 case 'D': c = "double;"; break;
264 case 'F': c = "float;"; break;
265 case 'I': c = "int;"; break;
266 case 'J': c = "long;"; break;
267 case 'S': c = "short;"; break;
268 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700269 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700270 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700271 }
272 }
273
274 // At this point, 'c' is a string of the form "fully/qualified/Type;"
275 // or "primitive;". Rewrite the type with '.' instead of '/':
276 std::string result;
277 const char* p = c;
278 while (*p != ';') {
279 char ch = *p++;
280 if (ch == '/') {
281 ch = '.';
282 }
283 result.push_back(ch);
284 }
285 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700286 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700287 result += "[]";
288 }
289 return result;
290}
291
Ian Rogersef7d42f2014-01-06 12:55:46 -0800292std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700293 if (f == NULL) {
294 return "null";
295 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700296 std::string result;
297 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700298 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700299 result += ' ';
300 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700301 StackHandleScope<1> hs(Thread::Current());
302 result += PrettyDescriptor(FieldHelper(hs.NewHandle(f)).GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700303 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700304 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700305 return result;
306}
307
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700308std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800309 if (field_idx >= dex_file.NumFieldIds()) {
310 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
311 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700312 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
313 std::string result;
314 if (with_type) {
315 result += dex_file.GetFieldTypeDescriptor(field_id);
316 result += ' ';
317 }
318 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
319 result += '.';
320 result += dex_file.GetFieldName(field_id);
321 return result;
322}
323
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700324std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800325 if (type_idx >= dex_file.NumTypeIds()) {
326 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
327 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700328 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700329 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700330}
331
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700332std::string PrettyArguments(const char* signature) {
333 std::string result;
334 result += '(';
335 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700336 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700337 while (*signature != ')') {
338 size_t argument_length = 0;
339 while (signature[argument_length] == '[') {
340 ++argument_length;
341 }
342 if (signature[argument_length] == 'L') {
343 argument_length = (strchr(signature, ';') - signature + 1);
344 } else {
345 ++argument_length;
346 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700347 {
348 std::string argument_descriptor(signature, argument_length);
349 result += PrettyDescriptor(argument_descriptor.c_str());
350 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700351 if (signature[argument_length] != ')') {
352 result += ", ";
353 }
354 signature += argument_length;
355 }
356 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700357 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700358 result += ')';
359 return result;
360}
361
362std::string PrettyReturnType(const char* signature) {
363 const char* return_type = strchr(signature, ')');
364 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700365 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700366 return PrettyDescriptor(return_type);
367}
368
Ian Rogersef7d42f2014-01-06 12:55:46 -0800369std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800370 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700371 return "null";
372 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700373 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700374 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700375 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800376 if (UNLIKELY(m->IsFastNative())) {
377 result += "!";
378 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700379 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700380 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700381 std::string sig_as_string(signature.ToString());
382 if (signature == Signature::NoSignature()) {
383 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700384 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700385 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
386 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700387 }
388 return result;
389}
390
Ian Rogers0571d352011-11-03 19:51:38 -0700391std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800392 if (method_idx >= dex_file.NumMethodIds()) {
393 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
394 }
Ian Rogers0571d352011-11-03 19:51:38 -0700395 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
396 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
397 result += '.';
398 result += dex_file.GetMethodName(method_id);
399 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700400 const Signature signature = dex_file.GetMethodSignature(method_id);
401 std::string sig_as_string(signature.ToString());
402 if (signature == Signature::NoSignature()) {
403 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700404 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700405 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
406 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700407 }
408 return result;
409}
410
Ian Rogersef7d42f2014-01-06 12:55:46 -0800411std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700412 if (obj == NULL) {
413 return "null";
414 }
415 if (obj->GetClass() == NULL) {
416 return "(raw)";
417 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700418 std::string temp;
419 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700420 if (obj->IsClass()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700421 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700422 }
423 return result;
424}
425
Ian Rogersef7d42f2014-01-06 12:55:46 -0800426std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700427 if (c == NULL) {
428 return "null";
429 }
430 std::string result;
431 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800432 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700433 result += ">";
434 return result;
435}
436
Ian Rogersef7d42f2014-01-06 12:55:46 -0800437std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700438 if (c == NULL) {
439 return "null";
440 }
441 std::string result;
442 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800443 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700444 result += ",";
445 result += PrettyTypeOf(c->GetClassLoader());
446 // TODO: add an identifying hash value for the loader
447 result += ">";
448 return result;
449}
450
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800451std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700452 // The byte thresholds at which we display amounts. A byte count is displayed
453 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800454 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700455 0, // B up to...
456 3*1024, // KB up to...
457 2*1024*1024, // MB up to...
458 1024*1024*1024 // GB from here.
459 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800460 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700461 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800462 const char* negative_str = "";
463 if (byte_count < 0) {
464 negative_str = "-";
465 byte_count = -byte_count;
466 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700467 int i = arraysize(kUnitThresholds);
468 while (--i > 0) {
469 if (byte_count >= kUnitThresholds[i]) {
470 break;
471 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800472 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800473 return StringPrintf("%s%" PRId64 "%s",
474 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800475}
476
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700477std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800478 if (nano_duration == 0) {
479 return "0";
480 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700481 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
482 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700483 }
484}
485
486TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
487 const uint64_t one_sec = 1000 * 1000 * 1000;
488 const uint64_t one_ms = 1000 * 1000;
489 const uint64_t one_us = 1000;
490 if (nano_duration >= one_sec) {
491 return kTimeUnitSecond;
492 } else if (nano_duration >= one_ms) {
493 return kTimeUnitMillisecond;
494 } else if (nano_duration >= one_us) {
495 return kTimeUnitMicrosecond;
496 } else {
497 return kTimeUnitNanosecond;
498 }
499}
500
501uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
502 const uint64_t one_sec = 1000 * 1000 * 1000;
503 const uint64_t one_ms = 1000 * 1000;
504 const uint64_t one_us = 1000;
505
506 switch (time_unit) {
507 case kTimeUnitSecond:
508 return one_sec;
509 case kTimeUnitMillisecond:
510 return one_ms;
511 case kTimeUnitMicrosecond:
512 return one_us;
513 case kTimeUnitNanosecond:
514 return 1;
515 }
516 return 0;
517}
518
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700519std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
520 size_t max_fraction_digits) {
521 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700522 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700523 switch (time_unit) {
524 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800525 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700526 break;
527 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800528 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700529 break;
530 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800531 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700532 break;
533 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800534 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700535 break;
536 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700537 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700538 uint64_t fractional_part = nano_duration % divisor;
539 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800540 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700541 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700542 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700543 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700544 char fraction_buffer[kMaxDigits];
545 char* ptr = fraction_buffer;
546 uint64_t multiplier = 10;
547 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700548 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700549 multiplier *= 10;
550 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700551 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800552 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700553 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700554 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
555 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800556 }
557}
558
Ian Rogers576ca0c2014-06-06 15:58:22 -0700559std::string PrintableChar(uint16_t ch) {
560 std::string result;
561 result += '\'';
562 if (NeedsEscaping(ch)) {
563 StringAppendF(&result, "\\u%04x", ch);
564 } else {
565 result += ch;
566 }
567 result += '\'';
568 return result;
569}
570
Ian Rogerscc2f2392014-08-29 20:19:11 -0700571std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700572 std::string result;
573 result += '"';
Ian Rogerscc2f2392014-08-29 20:19:11 -0700574 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700575 size_t char_count = CountModifiedUtf8Chars(p);
576 for (size_t i = 0; i < char_count; ++i) {
577 uint16_t ch = GetUtf16FromUtf8(&p);
578 if (ch == '\\') {
579 result += "\\\\";
580 } else if (ch == '\n') {
581 result += "\\n";
582 } else if (ch == '\r') {
583 result += "\\r";
584 } else if (ch == '\t') {
585 result += "\\t";
586 } else if (NeedsEscaping(ch)) {
587 StringAppendF(&result, "\\u%04x", ch);
588 } else {
589 result += ch;
590 }
591 }
592 result += '"';
593 return result;
594}
595
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800596// 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 -0700597std::string MangleForJni(const std::string& s) {
598 std::string result;
599 size_t char_count = CountModifiedUtf8Chars(s.c_str());
600 const char* cp = &s[0];
601 for (size_t i = 0; i < char_count; ++i) {
602 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800603 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
604 result.push_back(ch);
605 } else if (ch == '.' || ch == '/') {
606 result += "_";
607 } else if (ch == '_') {
608 result += "_1";
609 } else if (ch == ';') {
610 result += "_2";
611 } else if (ch == '[') {
612 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700613 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800614 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700615 }
616 }
617 return result;
618}
619
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700620std::string DotToDescriptor(const char* class_name) {
621 std::string descriptor(class_name);
622 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
623 if (descriptor.length() > 0 && descriptor[0] != '[') {
624 descriptor = "L" + descriptor + ";";
625 }
626 return descriptor;
627}
628
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800629std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800630 size_t length = strlen(descriptor);
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700631 if (length > 1) {
632 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
633 // Descriptors have the leading 'L' and trailing ';' stripped.
634 std::string result(descriptor + 1, length - 2);
635 std::replace(result.begin(), result.end(), '/', '.');
636 return result;
637 } else {
638 // For arrays the 'L' and ';' remain intact.
639 std::string result(descriptor);
640 std::replace(result.begin(), result.end(), '/', '.');
641 return result;
642 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800643 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700644 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800645 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800646}
647
648std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800649 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800650 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
651 std::string result(descriptor + 1, length - 2);
652 return result;
653 }
654 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700655}
656
Ian Rogersef7d42f2014-01-06 12:55:46 -0800657std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700658 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700659 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700660 CHECK_EQ(class_name[0], 'L') << class_name;
661 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700662 class_name.erase(0, 1);
663 class_name.erase(class_name.size() - 1, 1);
664
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700665 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700666
667 std::string short_name;
668 short_name += "Java_";
669 short_name += MangleForJni(class_name);
670 short_name += "_";
671 short_name += MangleForJni(method_name);
672 return short_name;
673}
674
Ian Rogersef7d42f2014-01-06 12:55:46 -0800675std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700676 std::string long_name;
677 long_name += JniShortName(m);
678 long_name += "__";
679
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700680 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700681 signature.erase(0, 1);
682 signature.erase(signature.begin() + signature.find(')'), signature.end());
683
684 long_name += MangleForJni(signature);
685
686 return long_name;
687}
688
jeffhao10037c82012-01-23 15:06:23 -0800689// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700690uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700691 0x00000000, // 00..1f low control characters; nothing valid
692 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
693 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
694 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700695};
696
jeffhao10037c82012-01-23 15:06:23 -0800697// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
698bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700699 /*
700 * It's a multibyte encoded character. Decode it and analyze. We
701 * accept anything that isn't (a) an improperly encoded low value,
702 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
703 * control character, or (e) a high space, layout, or special
704 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
705 * U+fff0..U+ffff). This is all specified in the dex format
706 * document.
707 */
708
709 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
710
711 // Perform follow-up tests based on the high 8 bits.
712 switch (utf16 >> 8) {
713 case 0x00:
714 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
715 return (utf16 > 0x00a0);
716 case 0xd8:
717 case 0xd9:
718 case 0xda:
719 case 0xdb:
720 // It's a leading surrogate. Check to see that a trailing
721 // surrogate follows.
722 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
723 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
724 case 0xdc:
725 case 0xdd:
726 case 0xde:
727 case 0xdf:
728 // It's a trailing surrogate, which is not valid at this point.
729 return false;
730 case 0x20:
731 case 0xff:
732 // It's in the range that has spaces, controls, and specials.
733 switch (utf16 & 0xfff8) {
734 case 0x2000:
735 case 0x2008:
736 case 0x2028:
737 case 0xfff0:
738 case 0xfff8:
739 return false;
740 }
741 break;
742 }
743 return true;
744}
745
746/* Return whether the pointed-at modified-UTF-8 encoded character is
747 * valid as part of a member name, updating the pointer to point past
748 * the consumed character. This will consume two encoded UTF-16 code
749 * points if the character is encoded as a surrogate pair. Also, if
750 * this function returns false, then the given pointer may only have
751 * been partially advanced.
752 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700753static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700754 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700755 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700756 // It's low-ascii, so check the table.
757 uint32_t wordIdx = c >> 5;
758 uint32_t bitIdx = c & 0x1f;
759 (*pUtf8Ptr)++;
760 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
761 }
762
763 // It's a multibyte encoded character. Call a non-inline function
764 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800765 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
766}
767
768bool IsValidMemberName(const char* s) {
769 bool angle_name = false;
770
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700771 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800772 case '\0':
773 // The empty string is not a valid name.
774 return false;
775 case '<':
776 angle_name = true;
777 s++;
778 break;
779 }
780
781 while (true) {
782 switch (*s) {
783 case '\0':
784 return !angle_name;
785 case '>':
786 return angle_name && s[1] == '\0';
787 }
788
789 if (!IsValidPartOfMemberNameUtf8(&s)) {
790 return false;
791 }
792 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700793}
794
Elliott Hughes906e6852011-10-28 14:52:10 -0700795enum ClassNameType { kName, kDescriptor };
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700796static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700797 int arrayCount = 0;
798 while (*s == '[') {
799 arrayCount++;
800 s++;
801 }
802
803 if (arrayCount > 255) {
804 // Arrays may have no more than 255 dimensions.
805 return false;
806 }
807
808 if (arrayCount != 0) {
809 /*
810 * If we're looking at an array of some sort, then it doesn't
811 * matter if what is being asked for is a class name; the
812 * format looks the same as a type descriptor in that case, so
813 * treat it as such.
814 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700815 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700816 }
817
Elliott Hughes906e6852011-10-28 14:52:10 -0700818 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700819 /*
820 * We are looking for a descriptor. Either validate it as a
821 * single-character primitive type, or continue on to check the
822 * embedded class name (bracketed by "L" and ";").
823 */
824 switch (*(s++)) {
825 case 'B':
826 case 'C':
827 case 'D':
828 case 'F':
829 case 'I':
830 case 'J':
831 case 'S':
832 case 'Z':
833 // These are all single-character descriptors for primitive types.
834 return (*s == '\0');
835 case 'V':
836 // Non-array void is valid, but you can't have an array of void.
837 return (arrayCount == 0) && (*s == '\0');
838 case 'L':
839 // Class name: Break out and continue below.
840 break;
841 default:
842 // Oddball descriptor character.
843 return false;
844 }
845 }
846
847 /*
848 * We just consumed the 'L' that introduces a class name as part
849 * of a type descriptor, or we are looking for an unadorned class
850 * name.
851 */
852
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700853 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700854 for (;;) {
855 uint8_t c = (uint8_t) *s;
856 switch (c) {
857 case '\0':
858 /*
859 * Premature end for a type descriptor, but valid for
860 * a class name as long as we haven't encountered an
861 * empty component (including the degenerate case of
862 * the empty string "").
863 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700864 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700865 case ';':
866 /*
867 * Invalid character for a class name, but the
868 * legitimate end of a type descriptor. In the latter
869 * case, make sure that this is the end of the string
870 * and that it doesn't end with an empty component
871 * (including the degenerate case of "L;").
872 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700873 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700874 case '/':
875 case '.':
876 if (c != separator) {
877 // The wrong separator character.
878 return false;
879 }
880 if (sepOrFirst) {
881 // Separator at start or two separators in a row.
882 return false;
883 }
884 sepOrFirst = true;
885 s++;
886 break;
887 default:
jeffhao10037c82012-01-23 15:06:23 -0800888 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700889 return false;
890 }
891 sepOrFirst = false;
892 break;
893 }
894 }
895}
896
Elliott Hughes906e6852011-10-28 14:52:10 -0700897bool IsValidBinaryClassName(const char* s) {
898 return IsValidClassName(s, kName, '.');
899}
900
901bool IsValidJniClassName(const char* s) {
902 return IsValidClassName(s, kName, '/');
903}
904
905bool IsValidDescriptor(const char* s) {
906 return IsValidClassName(s, kDescriptor, '/');
907}
908
Elliott Hughes48436bb2012-02-07 15:23:28 -0800909void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700910 const char* p = s.data();
911 const char* end = p + s.size();
912 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800913 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700914 ++p;
915 } else {
916 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800917 while (++p != end && *p != separator) {
918 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700919 }
920 result.push_back(std::string(start, p - start));
921 }
922 }
923}
924
Dave Allison70202782013-10-22 17:52:19 -0700925std::string Trim(std::string s) {
926 std::string result;
927 unsigned int start_index = 0;
928 unsigned int end_index = s.size() - 1;
929
930 // Skip initial whitespace.
931 while (start_index < s.size()) {
932 if (!isspace(s[start_index])) {
933 break;
934 }
935 start_index++;
936 }
937
938 // Skip terminating whitespace.
939 while (end_index >= start_index) {
940 if (!isspace(s[end_index])) {
941 break;
942 }
943 end_index--;
944 }
945
946 // All spaces, no beef.
947 if (end_index < start_index) {
948 return "";
949 }
950 // Start_index is the first non-space, end_index is the last one.
951 return s.substr(start_index, end_index - start_index + 1);
952}
953
Elliott Hughes48436bb2012-02-07 15:23:28 -0800954template <typename StringT>
955std::string Join(std::vector<StringT>& strings, char separator) {
956 if (strings.empty()) {
957 return "";
958 }
959
960 std::string result(strings[0]);
961 for (size_t i = 1; i < strings.size(); ++i) {
962 result += separator;
963 result += strings[i];
964 }
965 return result;
966}
967
968// Explicit instantiations.
969template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
970template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
971template std::string Join<char*>(std::vector<char*>& strings, char separator);
972
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800973bool StartsWith(const std::string& s, const char* prefix) {
974 return s.compare(0, strlen(prefix), prefix) == 0;
975}
976
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700977bool EndsWith(const std::string& s, const char* suffix) {
978 size_t suffix_length = strlen(suffix);
979 size_t string_length = s.size();
980 if (suffix_length > string_length) {
981 return false;
982 }
983 size_t offset = string_length - suffix_length;
984 return s.compare(offset, suffix_length, suffix) == 0;
985}
986
Elliott Hughes22869a92012-03-27 14:08:24 -0700987void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700988 int hasAt = 0;
989 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700990 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700991 while (*s) {
992 if (*s == '.') {
993 hasDot = 1;
994 } else if (*s == '@') {
995 hasAt = 1;
996 }
997 s++;
998 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700999 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001000 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -07001001 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001002 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -07001003 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001004 }
1005#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -07001006 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001007 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1008 strncpy(buf, s, sizeof(buf)-1);
1009 buf[sizeof(buf)-1] = '\0';
1010 errno = pthread_setname_np(pthread_self(), buf);
1011 if (errno != 0) {
1012 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1013 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -07001014#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -07001015 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001016#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -07001017 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -07001018#else
Elliott Hughes22869a92012-03-27 14:08:24 -07001019 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001020#endif
1021}
1022
Brian Carlstrom29212012013-09-12 22:18:30 -07001023void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1024 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001025 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001026 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001027 return;
1028 }
1029 // Skip the command, which may contain spaces.
1030 stats = stats.substr(stats.find(')') + 2);
1031 // Extract the three fields we care about.
1032 std::vector<std::string> fields;
1033 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001034 *state = fields[0][0];
1035 *utime = strtoull(fields[11].c_str(), NULL, 10);
1036 *stime = strtoull(fields[12].c_str(), NULL, 10);
1037 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001038}
1039
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001040std::string GetSchedulerGroupName(pid_t tid) {
1041 // /proc/<pid>/cgroup looks like this:
1042 // 2:devices:/
1043 // 1:cpuacct,cpu:/
1044 // We want the third field from the line whose second field contains the "cpu" token.
1045 std::string cgroup_file;
1046 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1047 return "";
1048 }
1049 std::vector<std::string> cgroup_lines;
1050 Split(cgroup_file, '\n', cgroup_lines);
1051 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1052 std::vector<std::string> cgroup_fields;
1053 Split(cgroup_lines[i], ':', cgroup_fields);
1054 std::vector<std::string> cgroups;
1055 Split(cgroup_fields[1], ',', cgroups);
1056 for (size_t i = 0; i < cgroups.size(); ++i) {
1057 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001058 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001059 }
1060 }
1061 }
1062 return "";
1063}
1064
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001065void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Kenny Root067d20f2014-03-05 14:57:21 -08001066 mirror::ArtMethod* current_method) {
1067 // We may be called from contexts where current_method is not null, so we must assert this.
1068 if (current_method != nullptr) {
1069 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1070 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001071#ifdef __linux__
Ian Rogers700a4022014-05-19 16:49:03 -07001072 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001073 if (!backtrace->Unwind(0)) {
1074 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001075 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001076 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001077 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001078 return;
1079 }
1080
Christopher Ferris943af7d2014-01-16 12:41:46 -08001081 for (Backtrace::const_iterator it = backtrace->begin();
1082 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001083 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001084 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1085 // In order for parsing tools to continue to function, the stack dump
1086 // format must at least adhere to this format:
1087 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1088 // The parsers require a single space before and after pc, and two spaces
1089 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1090 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1091 os << prefix << StringPrintf("#%02zu pc ", it->num);
1092 if (!it->map) {
1093 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001094 } else {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001095 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1096 << it->map->name << " (";
1097 if (!it->func_name.empty()) {
1098 os << it->func_name;
1099 if (it->func_offset != 0) {
1100 os << "+" << it->func_offset;
1101 }
1102 } else if (current_method != nullptr && current_method->IsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001103 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1104 os << JniLongName(current_method) << "+"
1105 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001106 } else {
1107 os << "???";
1108 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001109 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001110 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001111 os << "\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001112 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001113#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001114}
1115
Elliott Hughes058a6de2012-05-24 19:13:02 -07001116#if defined(__APPLE__)
1117
1118// TODO: is there any way to get the kernel stack on Mac OS?
1119void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1120
1121#else
1122
Elliott Hughes46e251b2012-05-22 15:10:45 -07001123void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001124 if (tid == GetTid()) {
1125 // There's no point showing that we're reading our stack out of /proc!
1126 return;
1127 }
1128
Elliott Hughes46e251b2012-05-22 15:10:45 -07001129 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1130 std::string kernel_stack;
1131 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001132 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001133 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001134 }
1135
1136 std::vector<std::string> kernel_stack_frames;
1137 Split(kernel_stack, '\n', kernel_stack_frames);
1138 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1139 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1140 kernel_stack_frames.pop_back();
1141 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001142 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1143 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001144 const char* text = kernel_stack_frames[i].c_str();
1145 const char* close_bracket = strchr(text, ']');
1146 if (close_bracket != NULL) {
1147 text = close_bracket + 2;
1148 }
1149 os << prefix;
1150 if (include_count) {
1151 os << StringPrintf("#%02zd ", i);
1152 }
1153 os << text << "\n";
1154 }
1155}
1156
1157#endif
1158
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001159const char* GetAndroidRoot() {
1160 const char* android_root = getenv("ANDROID_ROOT");
1161 if (android_root == NULL) {
1162 if (OS::DirectoryExists("/system")) {
1163 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001164 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001165 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1166 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001167 }
1168 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001169 if (!OS::DirectoryExists(android_root)) {
1170 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001171 return "";
1172 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001173 return android_root;
1174}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001175
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001176const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001177 std::string error_msg;
1178 const char* dir = GetAndroidDataSafe(&error_msg);
1179 if (dir != nullptr) {
1180 return dir;
1181 } else {
1182 LOG(FATAL) << error_msg;
1183 return "";
1184 }
1185}
1186
1187const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001188 const char* android_data = getenv("ANDROID_DATA");
1189 if (android_data == NULL) {
1190 if (OS::DirectoryExists("/data")) {
1191 android_data = "/data";
1192 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001193 *error_msg = "ANDROID_DATA not set and /data does not exist";
1194 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001195 }
1196 }
1197 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001198 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1199 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001200 }
1201 return android_data;
1202}
1203
Alex Lighta59dd802014-07-02 16:28:08 -07001204void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
1205 bool* have_android_data, bool* dalvik_cache_exists) {
1206 CHECK(subdir != nullptr);
1207 std::string error_msg;
1208 const char* android_data = GetAndroidDataSafe(&error_msg);
1209 if (android_data == nullptr) {
1210 *have_android_data = false;
1211 *dalvik_cache_exists = false;
1212 return;
1213 } else {
1214 *have_android_data = true;
1215 }
1216 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1217 *dalvik_cache = dalvik_cache_root + subdir;
1218 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
1219 if (create_if_absent && !*dalvik_cache_exists && strcmp(android_data, "/data") != 0) {
1220 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1221 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1222 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1223 }
1224}
1225
Narayan Kamath11d9f062014-04-23 20:24:57 +01001226std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1227 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001228 const char* android_data = GetAndroidData();
1229 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001230 const std::string dalvik_cache = dalvik_cache_root + subdir;
1231 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001232 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1233 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001234 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001235 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001236 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1237 return "";
1238 }
1239 result = mkdir(dalvik_cache.c_str(), 0700);
1240 if (result != 0) {
1241 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001242 return "";
1243 }
1244 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001245 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001246 return "";
1247 }
1248 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001249 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001250}
1251
Alex Lighta59dd802014-07-02 16:28:08 -07001252bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1253 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001254 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001255 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1256 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001257 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001258 std::string cache_file(&location[1]); // skip leading slash
Alex Light345c4b12014-07-18 14:57:04 -07001259 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001260 cache_file += "/";
1261 cache_file += DexFile::kClassesDex;
1262 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001263 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001264 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1265 return true;
1266}
1267
1268std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1269 std::string ret;
1270 std::string error_msg;
1271 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1272 LOG(FATAL) << error_msg;
1273 }
1274 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001275}
1276
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001277static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001278 // in = /foo/bar/baz
1279 // out = /foo/bar/<isa>/baz
1280 size_t pos = filename->rfind('/');
1281 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1282 filename->insert(pos, "/", 1);
1283 filename->insert(pos + 1, GetInstructionSetString(isa));
1284}
1285
1286std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1287 // location = /system/framework/boot.art
1288 // filename = /system/framework/<isa>/boot.art
1289 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001290 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001291 return filename;
1292}
1293
1294std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1295 // location = /foo/bar/baz.jar
1296 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001297
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001298 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1299 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001300 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001301 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1302 CHECK_EQ('.', odex_location[dot_index]) << location;
1303 odex_location.resize(dot_index + 1);
1304 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1305 odex_location += "odex";
1306 return odex_location;
1307}
1308
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001309bool IsZipMagic(uint32_t magic) {
1310 return (('P' == ((magic >> 0) & 0xff)) &&
1311 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001312}
1313
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001314bool IsDexMagic(uint32_t magic) {
1315 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001316}
1317
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001318bool IsOatMagic(uint32_t magic) {
1319 return (memcmp(reinterpret_cast<const byte*>(magic),
1320 OatHeader::kOatMagic,
1321 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001322}
1323
Brian Carlstrom6449c622014-02-10 23:48:36 -08001324bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1325 const std::string command_line(Join(arg_vector, ' '));
1326
1327 CHECK_GE(arg_vector.size(), 1U) << command_line;
1328
1329 // Convert the args to char pointers.
1330 const char* program = arg_vector[0].c_str();
1331 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001332 for (size_t i = 0; i < arg_vector.size(); ++i) {
1333 const std::string& arg = arg_vector[i];
1334 char* arg_str = const_cast<char*>(arg.c_str());
1335 CHECK(arg_str != nullptr) << i;
1336 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001337 }
1338 args.push_back(NULL);
1339
1340 // fork and exec
1341 pid_t pid = fork();
1342 if (pid == 0) {
1343 // no allocation allowed between fork and exec
1344
1345 // change process groups, so we don't get reaped by ProcessManager
1346 setpgid(0, 0);
1347
1348 execv(program, &args[0]);
1349
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001350 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1351 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001352 } else {
1353 if (pid == -1) {
1354 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1355 command_line.c_str(), strerror(errno));
1356 return false;
1357 }
1358
1359 // wait for subprocess to finish
1360 int status;
1361 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1362 if (got_pid != pid) {
1363 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1364 "wanted %d, got %d: %s",
1365 command_line.c_str(), pid, got_pid, strerror(errno));
1366 return false;
1367 }
1368 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1369 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1370 command_line.c_str());
1371 return false;
1372 }
1373 }
1374 return true;
1375}
1376
Elliott Hughes42ee1422011-09-06 12:33:32 -07001377} // namespace art