blob: 4f73e69756310a4b89ffb5de647de11034557a29 [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
Brian Carlstrom29212012013-09-12 22:18:30 -070085void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_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 }
98#else
99 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700100 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700101 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700102 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
103#endif
104}
105
Elliott Hughesd92bec42011-09-02 17:04:36 -0700106bool ReadFileToString(const std::string& file_name, std::string* result) {
Ian Rogers700a4022014-05-19 16:49:03 -0700107 std::unique_ptr<File> file(new File);
Elliott Hughes76160052012-12-12 16:31:20 -0800108 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700109 return false;
110 }
buzbeec143c552011-08-20 17:38:58 -0700111
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700112 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700113 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800114 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700115 if (n == -1) {
116 return false;
buzbeec143c552011-08-20 17:38:58 -0700117 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700118 if (n == 0) {
119 return true;
120 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700121 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700122 }
buzbeec143c552011-08-20 17:38:58 -0700123}
124
Elliott Hughese27955c2011-08-26 15:21:24 -0700125std::string GetIsoDate() {
126 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700127 tm tmbuf;
128 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700129 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
130 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
131 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
132}
133
Elliott Hughes7162ad92011-10-27 14:08:42 -0700134uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800135#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700136 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700137 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700138 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800139#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700140 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800141 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700142 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800143#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700144}
145
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800146uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800147#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700148 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800149 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700150 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800151#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700152 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800153 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700154 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800155#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800156}
157
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700158uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800159#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700160 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700161 clock_gettime(CLOCK_MONOTONIC, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700162 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800163#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700164 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800165 gettimeofday(&now, NULL);
Ian Rogers0f678472014-03-10 16:18:37 -0700166 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800167#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700168}
169
Elliott Hughes0512f022012-03-15 22:10:52 -0700170uint64_t ThreadCpuNanoTime() {
171#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700172 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700173 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
Ian Rogers0f678472014-03-10 16:18:37 -0700174 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
Elliott Hughes0512f022012-03-15 22:10:52 -0700175#else
176 UNIMPLEMENTED(WARNING);
177 return -1;
178#endif
179}
180
Ian Rogers56edc432013-01-18 16:51:51 -0800181void NanoSleep(uint64_t ns) {
182 timespec tm;
183 tm.tv_sec = 0;
184 tm.tv_nsec = ns;
185 nanosleep(&tm, NULL);
186}
187
Brian Carlstrombcc29262012-11-02 11:36:03 -0700188void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
189 int64_t endSec;
190
191 if (absolute) {
192#if !defined(__APPLE__)
193 clock_gettime(clock, ts);
194#else
195 UNUSED(clock);
196 timeval tv;
197 gettimeofday(&tv, NULL);
198 ts->tv_sec = tv.tv_sec;
199 ts->tv_nsec = tv.tv_usec * 1000;
200#endif
201 } else {
202 ts->tv_sec = 0;
203 ts->tv_nsec = 0;
204 }
205 endSec = ts->tv_sec + ms / 1000;
206 if (UNLIKELY(endSec >= 0x7fffffff)) {
207 std::ostringstream ss;
208 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
209 endSec = 0x7ffffffe;
210 }
211 ts->tv_sec = endSec;
212 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
213
214 // Catch rollover.
215 if (ts->tv_nsec >= 1000000000L) {
216 ts->tv_sec++;
217 ts->tv_nsec -= 1000000000L;
218 }
219}
220
Ian Rogersef7d42f2014-01-06 12:55:46 -0800221std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700222 if (java_descriptor == NULL) {
223 return "null";
224 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700225 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700226}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700227
Ian Rogersef7d42f2014-01-06 12:55:46 -0800228std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800229 if (klass == NULL) {
230 return "null";
231 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700232 std::string temp;
233 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800234}
235
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700236std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700237 // Count the number of '['s to get the dimensionality.
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700238 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700239 size_t dim = 0;
240 while (*c == '[') {
241 dim++;
242 c++;
243 }
244
245 // Reference or primitive?
246 if (*c == 'L') {
247 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700248 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700249 } else {
250 // "[[B" -> "byte[][]".
251 // To make life easier, we make primitives look like unqualified
252 // reference types.
253 switch (*c) {
254 case 'B': c = "byte;"; break;
255 case 'C': c = "char;"; break;
256 case 'D': c = "double;"; break;
257 case 'F': c = "float;"; break;
258 case 'I': c = "int;"; break;
259 case 'J': c = "long;"; break;
260 case 'S': c = "short;"; break;
261 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700262 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700263 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700264 }
265 }
266
267 // At this point, 'c' is a string of the form "fully/qualified/Type;"
268 // or "primitive;". Rewrite the type with '.' instead of '/':
269 std::string result;
270 const char* p = c;
271 while (*p != ';') {
272 char ch = *p++;
273 if (ch == '/') {
274 ch = '.';
275 }
276 result.push_back(ch);
277 }
278 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700279 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700280 result += "[]";
281 }
282 return result;
283}
284
Ian Rogersef7d42f2014-01-06 12:55:46 -0800285std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700286 if (f == NULL) {
287 return "null";
288 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700289 std::string result;
290 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700291 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700292 result += ' ';
293 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700294 StackHandleScope<1> hs(Thread::Current());
295 result += PrettyDescriptor(FieldHelper(hs.NewHandle(f)).GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700296 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700297 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700298 return result;
299}
300
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700301std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800302 if (field_idx >= dex_file.NumFieldIds()) {
303 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
304 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700305 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
306 std::string result;
307 if (with_type) {
308 result += dex_file.GetFieldTypeDescriptor(field_id);
309 result += ' ';
310 }
311 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
312 result += '.';
313 result += dex_file.GetFieldName(field_id);
314 return result;
315}
316
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700317std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800318 if (type_idx >= dex_file.NumTypeIds()) {
319 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
320 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700321 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700322 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700323}
324
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700325std::string PrettyArguments(const char* signature) {
326 std::string result;
327 result += '(';
328 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700329 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700330 while (*signature != ')') {
331 size_t argument_length = 0;
332 while (signature[argument_length] == '[') {
333 ++argument_length;
334 }
335 if (signature[argument_length] == 'L') {
336 argument_length = (strchr(signature, ';') - signature + 1);
337 } else {
338 ++argument_length;
339 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700340 {
341 std::string argument_descriptor(signature, argument_length);
342 result += PrettyDescriptor(argument_descriptor.c_str());
343 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700344 if (signature[argument_length] != ')') {
345 result += ", ";
346 }
347 signature += argument_length;
348 }
349 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700350 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700351 result += ')';
352 return result;
353}
354
355std::string PrettyReturnType(const char* signature) {
356 const char* return_type = strchr(signature, ')');
357 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700358 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700359 return PrettyDescriptor(return_type);
360}
361
Ian Rogersef7d42f2014-01-06 12:55:46 -0800362std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800363 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700364 return "null";
365 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700366 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700367 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700368 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800369 if (UNLIKELY(m->IsFastNative())) {
370 result += "!";
371 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700372 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700373 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700374 std::string sig_as_string(signature.ToString());
375 if (signature == Signature::NoSignature()) {
376 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700377 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700378 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
379 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700380 }
381 return result;
382}
383
Ian Rogers0571d352011-11-03 19:51:38 -0700384std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800385 if (method_idx >= dex_file.NumMethodIds()) {
386 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
387 }
Ian Rogers0571d352011-11-03 19:51:38 -0700388 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
389 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
390 result += '.';
391 result += dex_file.GetMethodName(method_id);
392 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700393 const Signature signature = dex_file.GetMethodSignature(method_id);
394 std::string sig_as_string(signature.ToString());
395 if (signature == Signature::NoSignature()) {
396 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700397 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700398 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
399 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700400 }
401 return result;
402}
403
Ian Rogersef7d42f2014-01-06 12:55:46 -0800404std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700405 if (obj == NULL) {
406 return "null";
407 }
408 if (obj->GetClass() == NULL) {
409 return "(raw)";
410 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700411 std::string temp;
412 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700413 if (obj->IsClass()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700414 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700415 }
416 return result;
417}
418
Ian Rogersef7d42f2014-01-06 12:55:46 -0800419std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700420 if (c == NULL) {
421 return "null";
422 }
423 std::string result;
424 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800425 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700426 result += ">";
427 return result;
428}
429
Ian Rogersef7d42f2014-01-06 12:55:46 -0800430std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700431 if (c == NULL) {
432 return "null";
433 }
434 std::string result;
435 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800436 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700437 result += ",";
438 result += PrettyTypeOf(c->GetClassLoader());
439 // TODO: add an identifying hash value for the loader
440 result += ">";
441 return result;
442}
443
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800444std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700445 // The byte thresholds at which we display amounts. A byte count is displayed
446 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800447 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700448 0, // B up to...
449 3*1024, // KB up to...
450 2*1024*1024, // MB up to...
451 1024*1024*1024 // GB from here.
452 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800453 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700454 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800455 const char* negative_str = "";
456 if (byte_count < 0) {
457 negative_str = "-";
458 byte_count = -byte_count;
459 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700460 int i = arraysize(kUnitThresholds);
461 while (--i > 0) {
462 if (byte_count >= kUnitThresholds[i]) {
463 break;
464 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800465 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800466 return StringPrintf("%s%" PRId64 "%s",
467 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800468}
469
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700470std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800471 if (nano_duration == 0) {
472 return "0";
473 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700474 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
475 max_fraction_digits);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700476 }
477}
478
479TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
480 const uint64_t one_sec = 1000 * 1000 * 1000;
481 const uint64_t one_ms = 1000 * 1000;
482 const uint64_t one_us = 1000;
483 if (nano_duration >= one_sec) {
484 return kTimeUnitSecond;
485 } else if (nano_duration >= one_ms) {
486 return kTimeUnitMillisecond;
487 } else if (nano_duration >= one_us) {
488 return kTimeUnitMicrosecond;
489 } else {
490 return kTimeUnitNanosecond;
491 }
492}
493
494uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
495 const uint64_t one_sec = 1000 * 1000 * 1000;
496 const uint64_t one_ms = 1000 * 1000;
497 const uint64_t one_us = 1000;
498
499 switch (time_unit) {
500 case kTimeUnitSecond:
501 return one_sec;
502 case kTimeUnitMillisecond:
503 return one_ms;
504 case kTimeUnitMicrosecond:
505 return one_us;
506 case kTimeUnitNanosecond:
507 return 1;
508 }
509 return 0;
510}
511
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700512std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
513 size_t max_fraction_digits) {
514 const char* unit = nullptr;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700515 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700516 switch (time_unit) {
517 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800518 unit = "s";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700519 break;
520 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800521 unit = "ms";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700522 break;
523 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800524 unit = "us";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700525 break;
526 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800527 unit = "ns";
Mathieu Chartier0325e622012-09-05 14:22:51 -0700528 break;
529 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700530 const uint64_t whole_part = nano_duration / divisor;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700531 uint64_t fractional_part = nano_duration % divisor;
532 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800533 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700534 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700535 static constexpr size_t kMaxDigits = 30;
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700536 size_t avail_digits = kMaxDigits;
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700537 char fraction_buffer[kMaxDigits];
538 char* ptr = fraction_buffer;
539 uint64_t multiplier = 10;
540 // This infinite loops if fractional part is 0.
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700541 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700542 multiplier *= 10;
543 *ptr++ = '0';
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700544 avail_digits--;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800545 }
Andreas Gampe829b4ba2014-06-26 13:49:36 -0700546 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700547 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
548 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800549 }
550}
551
Ian Rogers576ca0c2014-06-06 15:58:22 -0700552std::string PrintableChar(uint16_t ch) {
553 std::string result;
554 result += '\'';
555 if (NeedsEscaping(ch)) {
556 StringAppendF(&result, "\\u%04x", ch);
557 } else {
558 result += ch;
559 }
560 result += '\'';
561 return result;
562}
563
Elliott Hughes82914b62012-04-09 15:56:29 -0700564std::string PrintableString(const std::string& utf) {
565 std::string result;
566 result += '"';
567 const char* p = utf.c_str();
568 size_t char_count = CountModifiedUtf8Chars(p);
569 for (size_t i = 0; i < char_count; ++i) {
570 uint16_t ch = GetUtf16FromUtf8(&p);
571 if (ch == '\\') {
572 result += "\\\\";
573 } else if (ch == '\n') {
574 result += "\\n";
575 } else if (ch == '\r') {
576 result += "\\r";
577 } else if (ch == '\t') {
578 result += "\\t";
579 } else if (NeedsEscaping(ch)) {
580 StringAppendF(&result, "\\u%04x", ch);
581 } else {
582 result += ch;
583 }
584 }
585 result += '"';
586 return result;
587}
588
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800589// 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 -0700590std::string MangleForJni(const std::string& s) {
591 std::string result;
592 size_t char_count = CountModifiedUtf8Chars(s.c_str());
593 const char* cp = &s[0];
594 for (size_t i = 0; i < char_count; ++i) {
595 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800596 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
597 result.push_back(ch);
598 } else if (ch == '.' || ch == '/') {
599 result += "_";
600 } else if (ch == '_') {
601 result += "_1";
602 } else if (ch == ';') {
603 result += "_2";
604 } else if (ch == '[') {
605 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700606 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800607 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700608 }
609 }
610 return result;
611}
612
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700613std::string DotToDescriptor(const char* class_name) {
614 std::string descriptor(class_name);
615 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
616 if (descriptor.length() > 0 && descriptor[0] != '[') {
617 descriptor = "L" + descriptor + ";";
618 }
619 return descriptor;
620}
621
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800622std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800623 size_t length = strlen(descriptor);
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700624 if (length > 1) {
625 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
626 // Descriptors have the leading 'L' and trailing ';' stripped.
627 std::string result(descriptor + 1, length - 2);
628 std::replace(result.begin(), result.end(), '/', '.');
629 return result;
630 } else {
631 // For arrays the 'L' and ';' remain intact.
632 std::string result(descriptor);
633 std::replace(result.begin(), result.end(), '/', '.');
634 return result;
635 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800636 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700637 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800638 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800639}
640
641std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800642 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800643 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
644 std::string result(descriptor + 1, length - 2);
645 return result;
646 }
647 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700648}
649
Ian Rogersef7d42f2014-01-06 12:55:46 -0800650std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700651 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700652 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700653 CHECK_EQ(class_name[0], 'L') << class_name;
654 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700655 class_name.erase(0, 1);
656 class_name.erase(class_name.size() - 1, 1);
657
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700658 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700659
660 std::string short_name;
661 short_name += "Java_";
662 short_name += MangleForJni(class_name);
663 short_name += "_";
664 short_name += MangleForJni(method_name);
665 return short_name;
666}
667
Ian Rogersef7d42f2014-01-06 12:55:46 -0800668std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700669 std::string long_name;
670 long_name += JniShortName(m);
671 long_name += "__";
672
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700673 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700674 signature.erase(0, 1);
675 signature.erase(signature.begin() + signature.find(')'), signature.end());
676
677 long_name += MangleForJni(signature);
678
679 return long_name;
680}
681
jeffhao10037c82012-01-23 15:06:23 -0800682// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700683uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700684 0x00000000, // 00..1f low control characters; nothing valid
685 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
686 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
687 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700688};
689
jeffhao10037c82012-01-23 15:06:23 -0800690// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
691bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700692 /*
693 * It's a multibyte encoded character. Decode it and analyze. We
694 * accept anything that isn't (a) an improperly encoded low value,
695 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
696 * control character, or (e) a high space, layout, or special
697 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
698 * U+fff0..U+ffff). This is all specified in the dex format
699 * document.
700 */
701
702 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
703
704 // Perform follow-up tests based on the high 8 bits.
705 switch (utf16 >> 8) {
706 case 0x00:
707 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
708 return (utf16 > 0x00a0);
709 case 0xd8:
710 case 0xd9:
711 case 0xda:
712 case 0xdb:
713 // It's a leading surrogate. Check to see that a trailing
714 // surrogate follows.
715 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
716 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
717 case 0xdc:
718 case 0xdd:
719 case 0xde:
720 case 0xdf:
721 // It's a trailing surrogate, which is not valid at this point.
722 return false;
723 case 0x20:
724 case 0xff:
725 // It's in the range that has spaces, controls, and specials.
726 switch (utf16 & 0xfff8) {
727 case 0x2000:
728 case 0x2008:
729 case 0x2028:
730 case 0xfff0:
731 case 0xfff8:
732 return false;
733 }
734 break;
735 }
736 return true;
737}
738
739/* Return whether the pointed-at modified-UTF-8 encoded character is
740 * valid as part of a member name, updating the pointer to point past
741 * the consumed character. This will consume two encoded UTF-16 code
742 * points if the character is encoded as a surrogate pair. Also, if
743 * this function returns false, then the given pointer may only have
744 * been partially advanced.
745 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700746static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700747 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700748 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700749 // It's low-ascii, so check the table.
750 uint32_t wordIdx = c >> 5;
751 uint32_t bitIdx = c & 0x1f;
752 (*pUtf8Ptr)++;
753 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
754 }
755
756 // It's a multibyte encoded character. Call a non-inline function
757 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800758 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
759}
760
761bool IsValidMemberName(const char* s) {
762 bool angle_name = false;
763
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700764 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800765 case '\0':
766 // The empty string is not a valid name.
767 return false;
768 case '<':
769 angle_name = true;
770 s++;
771 break;
772 }
773
774 while (true) {
775 switch (*s) {
776 case '\0':
777 return !angle_name;
778 case '>':
779 return angle_name && s[1] == '\0';
780 }
781
782 if (!IsValidPartOfMemberNameUtf8(&s)) {
783 return false;
784 }
785 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700786}
787
Elliott Hughes906e6852011-10-28 14:52:10 -0700788enum ClassNameType { kName, kDescriptor };
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700789static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700790 int arrayCount = 0;
791 while (*s == '[') {
792 arrayCount++;
793 s++;
794 }
795
796 if (arrayCount > 255) {
797 // Arrays may have no more than 255 dimensions.
798 return false;
799 }
800
801 if (arrayCount != 0) {
802 /*
803 * If we're looking at an array of some sort, then it doesn't
804 * matter if what is being asked for is a class name; the
805 * format looks the same as a type descriptor in that case, so
806 * treat it as such.
807 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700808 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700809 }
810
Elliott Hughes906e6852011-10-28 14:52:10 -0700811 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700812 /*
813 * We are looking for a descriptor. Either validate it as a
814 * single-character primitive type, or continue on to check the
815 * embedded class name (bracketed by "L" and ";").
816 */
817 switch (*(s++)) {
818 case 'B':
819 case 'C':
820 case 'D':
821 case 'F':
822 case 'I':
823 case 'J':
824 case 'S':
825 case 'Z':
826 // These are all single-character descriptors for primitive types.
827 return (*s == '\0');
828 case 'V':
829 // Non-array void is valid, but you can't have an array of void.
830 return (arrayCount == 0) && (*s == '\0');
831 case 'L':
832 // Class name: Break out and continue below.
833 break;
834 default:
835 // Oddball descriptor character.
836 return false;
837 }
838 }
839
840 /*
841 * We just consumed the 'L' that introduces a class name as part
842 * of a type descriptor, or we are looking for an unadorned class
843 * name.
844 */
845
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700846 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700847 for (;;) {
848 uint8_t c = (uint8_t) *s;
849 switch (c) {
850 case '\0':
851 /*
852 * Premature end for a type descriptor, but valid for
853 * a class name as long as we haven't encountered an
854 * empty component (including the degenerate case of
855 * the empty string "").
856 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700857 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700858 case ';':
859 /*
860 * Invalid character for a class name, but the
861 * legitimate end of a type descriptor. In the latter
862 * case, make sure that this is the end of the string
863 * and that it doesn't end with an empty component
864 * (including the degenerate case of "L;").
865 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700866 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700867 case '/':
868 case '.':
869 if (c != separator) {
870 // The wrong separator character.
871 return false;
872 }
873 if (sepOrFirst) {
874 // Separator at start or two separators in a row.
875 return false;
876 }
877 sepOrFirst = true;
878 s++;
879 break;
880 default:
jeffhao10037c82012-01-23 15:06:23 -0800881 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700882 return false;
883 }
884 sepOrFirst = false;
885 break;
886 }
887 }
888}
889
Elliott Hughes906e6852011-10-28 14:52:10 -0700890bool IsValidBinaryClassName(const char* s) {
891 return IsValidClassName(s, kName, '.');
892}
893
894bool IsValidJniClassName(const char* s) {
895 return IsValidClassName(s, kName, '/');
896}
897
898bool IsValidDescriptor(const char* s) {
899 return IsValidClassName(s, kDescriptor, '/');
900}
901
Elliott Hughes48436bb2012-02-07 15:23:28 -0800902void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700903 const char* p = s.data();
904 const char* end = p + s.size();
905 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800906 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700907 ++p;
908 } else {
909 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800910 while (++p != end && *p != separator) {
911 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700912 }
913 result.push_back(std::string(start, p - start));
914 }
915 }
916}
917
Dave Allison70202782013-10-22 17:52:19 -0700918std::string Trim(std::string s) {
919 std::string result;
920 unsigned int start_index = 0;
921 unsigned int end_index = s.size() - 1;
922
923 // Skip initial whitespace.
924 while (start_index < s.size()) {
925 if (!isspace(s[start_index])) {
926 break;
927 }
928 start_index++;
929 }
930
931 // Skip terminating whitespace.
932 while (end_index >= start_index) {
933 if (!isspace(s[end_index])) {
934 break;
935 }
936 end_index--;
937 }
938
939 // All spaces, no beef.
940 if (end_index < start_index) {
941 return "";
942 }
943 // Start_index is the first non-space, end_index is the last one.
944 return s.substr(start_index, end_index - start_index + 1);
945}
946
Elliott Hughes48436bb2012-02-07 15:23:28 -0800947template <typename StringT>
948std::string Join(std::vector<StringT>& strings, char separator) {
949 if (strings.empty()) {
950 return "";
951 }
952
953 std::string result(strings[0]);
954 for (size_t i = 1; i < strings.size(); ++i) {
955 result += separator;
956 result += strings[i];
957 }
958 return result;
959}
960
961// Explicit instantiations.
962template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
963template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
964template std::string Join<char*>(std::vector<char*>& strings, char separator);
965
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800966bool StartsWith(const std::string& s, const char* prefix) {
967 return s.compare(0, strlen(prefix), prefix) == 0;
968}
969
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700970bool EndsWith(const std::string& s, const char* suffix) {
971 size_t suffix_length = strlen(suffix);
972 size_t string_length = s.size();
973 if (suffix_length > string_length) {
974 return false;
975 }
976 size_t offset = string_length - suffix_length;
977 return s.compare(offset, suffix_length, suffix) == 0;
978}
979
Elliott Hughes22869a92012-03-27 14:08:24 -0700980void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700981 int hasAt = 0;
982 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700983 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700984 while (*s) {
985 if (*s == '.') {
986 hasDot = 1;
987 } else if (*s == '@') {
988 hasAt = 1;
989 }
990 s++;
991 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700992 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700993 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700994 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700995 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700996 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700997 }
998#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700999 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -07001000 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1001 strncpy(buf, s, sizeof(buf)-1);
1002 buf[sizeof(buf)-1] = '\0';
1003 errno = pthread_setname_np(pthread_self(), buf);
1004 if (errno != 0) {
1005 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1006 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -07001007#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -07001008 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001009#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -07001010 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -07001011#else
Elliott Hughes22869a92012-03-27 14:08:24 -07001012 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -07001013#endif
1014}
1015
Brian Carlstrom29212012013-09-12 22:18:30 -07001016void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1017 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001018 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001019 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001020 return;
1021 }
1022 // Skip the command, which may contain spaces.
1023 stats = stats.substr(stats.find(')') + 2);
1024 // Extract the three fields we care about.
1025 std::vector<std::string> fields;
1026 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001027 *state = fields[0][0];
1028 *utime = strtoull(fields[11].c_str(), NULL, 10);
1029 *stime = strtoull(fields[12].c_str(), NULL, 10);
1030 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001031}
1032
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001033std::string GetSchedulerGroupName(pid_t tid) {
1034 // /proc/<pid>/cgroup looks like this:
1035 // 2:devices:/
1036 // 1:cpuacct,cpu:/
1037 // We want the third field from the line whose second field contains the "cpu" token.
1038 std::string cgroup_file;
1039 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1040 return "";
1041 }
1042 std::vector<std::string> cgroup_lines;
1043 Split(cgroup_file, '\n', cgroup_lines);
1044 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1045 std::vector<std::string> cgroup_fields;
1046 Split(cgroup_lines[i], ':', cgroup_fields);
1047 std::vector<std::string> cgroups;
1048 Split(cgroup_fields[1], ',', cgroups);
1049 for (size_t i = 0; i < cgroups.size(); ++i) {
1050 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001051 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001052 }
1053 }
1054 }
1055 return "";
1056}
1057
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001058void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Kenny Root067d20f2014-03-05 14:57:21 -08001059 mirror::ArtMethod* current_method) {
1060 // We may be called from contexts where current_method is not null, so we must assert this.
1061 if (current_method != nullptr) {
1062 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1063 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001064#ifdef __linux__
Ian Rogers700a4022014-05-19 16:49:03 -07001065 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001066 if (!backtrace->Unwind(0)) {
1067 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001068 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001069 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001070 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001071 return;
1072 }
1073
Christopher Ferris943af7d2014-01-16 12:41:46 -08001074 for (Backtrace::const_iterator it = backtrace->begin();
1075 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001076 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001077 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1078 // In order for parsing tools to continue to function, the stack dump
1079 // format must at least adhere to this format:
1080 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1081 // The parsers require a single space before and after pc, and two spaces
1082 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1083 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1084 os << prefix << StringPrintf("#%02zu pc ", it->num);
1085 if (!it->map) {
1086 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001087 } else {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001088 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1089 << it->map->name << " (";
1090 if (!it->func_name.empty()) {
1091 os << it->func_name;
1092 if (it->func_offset != 0) {
1093 os << "+" << it->func_offset;
1094 }
1095 } else if (current_method != nullptr && current_method->IsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001096 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1097 os << JniLongName(current_method) << "+"
1098 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001099 } else {
1100 os << "???";
1101 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001102 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001103 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001104 os << "\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001105 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001106#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001107}
1108
Elliott Hughes058a6de2012-05-24 19:13:02 -07001109#if defined(__APPLE__)
1110
1111// TODO: is there any way to get the kernel stack on Mac OS?
1112void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1113
1114#else
1115
Elliott Hughes46e251b2012-05-22 15:10:45 -07001116void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001117 if (tid == GetTid()) {
1118 // There's no point showing that we're reading our stack out of /proc!
1119 return;
1120 }
1121
Elliott Hughes46e251b2012-05-22 15:10:45 -07001122 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1123 std::string kernel_stack;
1124 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001125 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001126 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001127 }
1128
1129 std::vector<std::string> kernel_stack_frames;
1130 Split(kernel_stack, '\n', kernel_stack_frames);
1131 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1132 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1133 kernel_stack_frames.pop_back();
1134 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001135 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1136 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001137 const char* text = kernel_stack_frames[i].c_str();
1138 const char* close_bracket = strchr(text, ']');
1139 if (close_bracket != NULL) {
1140 text = close_bracket + 2;
1141 }
1142 os << prefix;
1143 if (include_count) {
1144 os << StringPrintf("#%02zd ", i);
1145 }
1146 os << text << "\n";
1147 }
1148}
1149
1150#endif
1151
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001152const char* GetAndroidRoot() {
1153 const char* android_root = getenv("ANDROID_ROOT");
1154 if (android_root == NULL) {
1155 if (OS::DirectoryExists("/system")) {
1156 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001157 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001158 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1159 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001160 }
1161 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001162 if (!OS::DirectoryExists(android_root)) {
1163 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001164 return "";
1165 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001166 return android_root;
1167}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001168
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001169const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001170 std::string error_msg;
1171 const char* dir = GetAndroidDataSafe(&error_msg);
1172 if (dir != nullptr) {
1173 return dir;
1174 } else {
1175 LOG(FATAL) << error_msg;
1176 return "";
1177 }
1178}
1179
1180const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001181 const char* android_data = getenv("ANDROID_DATA");
1182 if (android_data == NULL) {
1183 if (OS::DirectoryExists("/data")) {
1184 android_data = "/data";
1185 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001186 *error_msg = "ANDROID_DATA not set and /data does not exist";
1187 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001188 }
1189 }
1190 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001191 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1192 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001193 }
1194 return android_data;
1195}
1196
Alex Lighta59dd802014-07-02 16:28:08 -07001197void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
1198 bool* have_android_data, bool* dalvik_cache_exists) {
1199 CHECK(subdir != nullptr);
1200 std::string error_msg;
1201 const char* android_data = GetAndroidDataSafe(&error_msg);
1202 if (android_data == nullptr) {
1203 *have_android_data = false;
1204 *dalvik_cache_exists = false;
1205 return;
1206 } else {
1207 *have_android_data = true;
1208 }
1209 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1210 *dalvik_cache = dalvik_cache_root + subdir;
1211 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
1212 if (create_if_absent && !*dalvik_cache_exists && strcmp(android_data, "/data") != 0) {
1213 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1214 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1215 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1216 }
1217}
1218
Narayan Kamath11d9f062014-04-23 20:24:57 +01001219std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1220 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001221 const char* android_data = GetAndroidData();
1222 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001223 const std::string dalvik_cache = dalvik_cache_root + subdir;
1224 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001225 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1226 if (strcmp(android_data, "/data") != 0) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001227 int result = mkdir(dalvik_cache_root.c_str(), 0700);
Narayan Kamathef204fa2014-04-30 17:25:23 +01001228 if (result != 0 && errno != EEXIST) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001229 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1230 return "";
1231 }
1232 result = mkdir(dalvik_cache.c_str(), 0700);
1233 if (result != 0) {
1234 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001235 return "";
1236 }
1237 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001238 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001239 return "";
1240 }
1241 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001242 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001243}
1244
Alex Lighta59dd802014-07-02 16:28:08 -07001245bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1246 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001247 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001248 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1249 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001250 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001251 std::string cache_file(&location[1]); // skip leading slash
Alex Light345c4b12014-07-18 14:57:04 -07001252 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001253 cache_file += "/";
1254 cache_file += DexFile::kClassesDex;
1255 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001256 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001257 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1258 return true;
1259}
1260
1261std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1262 std::string ret;
1263 std::string error_msg;
1264 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1265 LOG(FATAL) << error_msg;
1266 }
1267 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001268}
1269
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001270static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001271 // in = /foo/bar/baz
1272 // out = /foo/bar/<isa>/baz
1273 size_t pos = filename->rfind('/');
1274 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1275 filename->insert(pos, "/", 1);
1276 filename->insert(pos + 1, GetInstructionSetString(isa));
1277}
1278
1279std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1280 // location = /system/framework/boot.art
1281 // filename = /system/framework/<isa>/boot.art
1282 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001283 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001284 return filename;
1285}
1286
1287std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1288 // location = /foo/bar/baz.jar
1289 // odex_location = /foo/bar/<isa>/baz.odex
Andreas Gampe833a4852014-05-21 18:46:59 -07001290
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001291 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1292 std::string odex_location(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001293 InsertIsaDirectory(isa, &odex_location);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001294 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1295 CHECK_EQ('.', odex_location[dot_index]) << location;
1296 odex_location.resize(dot_index + 1);
1297 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1298 odex_location += "odex";
1299 return odex_location;
1300}
1301
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001302bool IsZipMagic(uint32_t magic) {
1303 return (('P' == ((magic >> 0) & 0xff)) &&
1304 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001305}
1306
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001307bool IsDexMagic(uint32_t magic) {
1308 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001309}
1310
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001311bool IsOatMagic(uint32_t magic) {
1312 return (memcmp(reinterpret_cast<const byte*>(magic),
1313 OatHeader::kOatMagic,
1314 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001315}
1316
Brian Carlstrom6449c622014-02-10 23:48:36 -08001317bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1318 const std::string command_line(Join(arg_vector, ' '));
1319
1320 CHECK_GE(arg_vector.size(), 1U) << command_line;
1321
1322 // Convert the args to char pointers.
1323 const char* program = arg_vector[0].c_str();
1324 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001325 for (size_t i = 0; i < arg_vector.size(); ++i) {
1326 const std::string& arg = arg_vector[i];
1327 char* arg_str = const_cast<char*>(arg.c_str());
1328 CHECK(arg_str != nullptr) << i;
1329 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001330 }
1331 args.push_back(NULL);
1332
1333 // fork and exec
1334 pid_t pid = fork();
1335 if (pid == 0) {
1336 // no allocation allowed between fork and exec
1337
1338 // change process groups, so we don't get reaped by ProcessManager
1339 setpgid(0, 0);
1340
1341 execv(program, &args[0]);
1342
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001343 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1344 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001345 } else {
1346 if (pid == -1) {
1347 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1348 command_line.c_str(), strerror(errno));
1349 return false;
1350 }
1351
1352 // wait for subprocess to finish
1353 int status;
1354 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1355 if (got_pid != pid) {
1356 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1357 "wanted %d, got %d: %s",
1358 command_line.c_str(), pid, got_pid, strerror(errno));
1359 return false;
1360 }
1361 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1362 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1363 command_line.c_str());
1364 return false;
1365 }
1366 }
1367 return true;
1368}
1369
Elliott Hughes42ee1422011-09-06 12:33:32 -07001370} // namespace art