blob: 71a7ebfc790a523efbf9de92b3eb010b7072c151 [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
Elliott Hughes06e3ad42012-02-07 14:51:57 -080019#include <dynamic_annotations.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>
24#include <unistd.h>
25
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include "UniquePtr.h"
Ian Rogersd81871c2011-10-03 13:57:23 -070027#include "class_loader.h"
buzbeec143c552011-08-20 17:38:58 -070028#include "file.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070029#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070031#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070032
Elliott Hughesad6c9c32012-01-19 17:39:12 -080033#if !defined(HAVE_POSIX_CLOCKS)
34#include <sys/time.h>
35#endif
36
Elliott Hughesdcc24742011-09-07 14:02:44 -070037#if defined(HAVE_PRCTL)
38#include <sys/prctl.h>
39#endif
40
Elliott Hughes4ae722a2012-03-13 11:08:51 -070041#if defined(__APPLE__)
Elliott Hughesb08e8a32012-04-02 10:51:41 -070042#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070043#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070044#endif
45
Elliott Hughes46e251b2012-05-22 15:10:45 -070046#include <corkscrew/backtrace.h> // For DumpNativeStack.
47#include <corkscrew/demangle.h> // For DumpNativeStack.
48
Elliott Hughes058a6de2012-05-24 19:13:02 -070049#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080050#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080051#endif
52
Elliott Hughes11e45072011-08-16 17:40:46 -070053namespace art {
54
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080055pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070056#if defined(__APPLE__)
57 uint64_t owner;
58 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
59 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080060#else
61 // Neither bionic nor glibc exposes gettid(2).
62 return syscall(__NR_gettid);
63#endif
64}
65
Elliott Hughes289be852012-06-12 13:57:20 -070066std::string GetThreadName(pid_t tid) {
67 std::string result;
68 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
69 result.resize(result.size() - 1); // Lose the trailing '\n'.
70 } else {
71 result = "<unknown>";
72 }
73 return result;
74}
75
Elliott Hughese1884192012-04-23 12:38:15 -070076void GetThreadStack(void*& stack_base, size_t& stack_size) {
77#if defined(__APPLE__)
78 stack_size = pthread_get_stacksize_np(pthread_self());
79 void* stack_addr = pthread_get_stackaddr_np(pthread_self());
80
81 // Check whether stack_addr is the base or end of the stack.
82 // (On Mac OS 10.7, it's the end.)
83 int stack_variable;
84 if (stack_addr > &stack_variable) {
85 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
86 } else {
87 stack_base = stack_addr;
88 }
89#else
90 pthread_attr_t attributes;
91 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
92 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
93 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
94#endif
95}
96
Elliott Hughesd92bec42011-09-02 17:04:36 -070097bool ReadFileToString(const std::string& file_name, std::string* result) {
98 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
99 if (file.get() == NULL) {
100 return false;
101 }
buzbeec143c552011-08-20 17:38:58 -0700102
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700103 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700104 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700105 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700106 if (n == -1) {
107 return false;
buzbeec143c552011-08-20 17:38:58 -0700108 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700109 if (n == 0) {
110 return true;
111 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700112 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700113 }
buzbeec143c552011-08-20 17:38:58 -0700114}
115
Elliott Hughese27955c2011-08-26 15:21:24 -0700116std::string GetIsoDate() {
117 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700118 tm tmbuf;
119 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700120 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
121 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
122 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
123}
124
Elliott Hughes7162ad92011-10-27 14:08:42 -0700125uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700127 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700128 clock_gettime(CLOCK_MONOTONIC, &now);
129 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800130#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700131 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800132 gettimeofday(&now, NULL);
133 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
134#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135}
136
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800137uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700139 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800140 clock_gettime(CLOCK_MONOTONIC, &now);
141 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700143 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800144 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700145 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800146#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147}
148
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700149uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700151 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700152 clock_gettime(CLOCK_MONOTONIC, &now);
153 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700155 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156 gettimeofday(&now, NULL);
157 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
158#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159}
160
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800161uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700163 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800164 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
165 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800166#else
167 UNIMPLEMENTED(WARNING);
168 return -1;
169#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800170}
171
Elliott Hughes0512f022012-03-15 22:10:52 -0700172uint64_t ThreadCpuNanoTime() {
173#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700174 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700175 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
176 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
177#else
178 UNIMPLEMENTED(WARNING);
179 return -1;
180#endif
181}
182
Elliott Hughes5174fe62011-08-23 15:12:35 -0700183std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700184 if (java_descriptor == NULL) {
185 return "null";
186 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700187 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
188}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700189
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800190std::string PrettyDescriptor(const Class* klass) {
191 if (klass == NULL) {
192 return "null";
193 }
194 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800195}
196
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700197std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700198 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700199 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700200 size_t dim = 0;
201 while (*c == '[') {
202 dim++;
203 c++;
204 }
205
206 // Reference or primitive?
207 if (*c == 'L') {
208 // "[[La/b/C;" -> "a.b.C[][]".
209 c++; // Skip the 'L'.
210 } else {
211 // "[[B" -> "byte[][]".
212 // To make life easier, we make primitives look like unqualified
213 // reference types.
214 switch (*c) {
215 case 'B': c = "byte;"; break;
216 case 'C': c = "char;"; break;
217 case 'D': c = "double;"; break;
218 case 'F': c = "float;"; break;
219 case 'I': c = "int;"; break;
220 case 'J': c = "long;"; break;
221 case 'S': c = "short;"; break;
222 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700223 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700224 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700225 }
226 }
227
228 // At this point, 'c' is a string of the form "fully/qualified/Type;"
229 // or "primitive;". Rewrite the type with '.' instead of '/':
230 std::string result;
231 const char* p = c;
232 while (*p != ';') {
233 char ch = *p++;
234 if (ch == '/') {
235 ch = '.';
236 }
237 result.push_back(ch);
238 }
239 // ...and replace the semicolon with 'dim' "[]" pairs:
240 while (dim--) {
241 result += "[]";
242 }
243 return result;
244}
245
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700246std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800247 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700248 return PrettyDescriptor(descriptor_string);
249}
250
Elliott Hughes54e7df12011-09-16 11:47:04 -0700251std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700252 if (f == NULL) {
253 return "null";
254 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800255 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700256 std::string result;
257 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800258 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700259 result += ' ';
260 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800261 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700262 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800263 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700264 return result;
265}
266
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700267std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
268 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
269 std::string result;
270 if (with_type) {
271 result += dex_file.GetFieldTypeDescriptor(field_id);
272 result += ' ';
273 }
274 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
275 result += '.';
276 result += dex_file.GetFieldName(field_id);
277 return result;
278}
279
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700280std::string PrettyArguments(const char* signature) {
281 std::string result;
282 result += '(';
283 CHECK_EQ(*signature, '(');
284 ++signature; // Skip the '('.
285 while (*signature != ')') {
286 size_t argument_length = 0;
287 while (signature[argument_length] == '[') {
288 ++argument_length;
289 }
290 if (signature[argument_length] == 'L') {
291 argument_length = (strchr(signature, ';') - signature + 1);
292 } else {
293 ++argument_length;
294 }
295 std::string argument_descriptor(signature, argument_length);
296 result += PrettyDescriptor(argument_descriptor);
297 if (signature[argument_length] != ')') {
298 result += ", ";
299 }
300 signature += argument_length;
301 }
302 CHECK_EQ(*signature, ')');
303 ++signature; // Skip the ')'.
304 result += ')';
305 return result;
306}
307
308std::string PrettyReturnType(const char* signature) {
309 const char* return_type = strchr(signature, ')');
310 CHECK(return_type != NULL);
311 ++return_type; // Skip ')'.
312 return PrettyDescriptor(return_type);
313}
314
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700315std::string PrettyMethod(const Method* m, bool with_signature) {
316 if (m == NULL) {
317 return "null";
318 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800319 MethodHelper mh(m);
320 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700321 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800322 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700323 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700324 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700325 if (signature == "<no signature>") {
326 return result + signature;
327 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700328 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700329 }
330 return result;
331}
332
Ian Rogers0571d352011-11-03 19:51:38 -0700333std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
334 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
335 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
336 result += '.';
337 result += dex_file.GetMethodName(method_id);
338 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700339 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700340 if (signature == "<no signature>") {
341 return result + signature;
342 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700343 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700344 }
345 return result;
346}
347
Elliott Hughes54e7df12011-09-16 11:47:04 -0700348std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700349 if (obj == NULL) {
350 return "null";
351 }
352 if (obj->GetClass() == NULL) {
353 return "(raw)";
354 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800355 ClassHelper kh(obj->GetClass());
356 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700357 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800358 kh.ChangeClass(obj->AsClass());
359 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700360 }
361 return result;
362}
363
Elliott Hughes54e7df12011-09-16 11:47:04 -0700364std::string PrettyClass(const Class* c) {
365 if (c == NULL) {
366 return "null";
367 }
368 std::string result;
369 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800370 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700371 result += ">";
372 return result;
373}
374
Ian Rogersd81871c2011-10-03 13:57:23 -0700375std::string PrettyClassAndClassLoader(const Class* c) {
376 if (c == NULL) {
377 return "null";
378 }
379 std::string result;
380 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800381 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700382 result += ",";
383 result += PrettyTypeOf(c->GetClassLoader());
384 // TODO: add an identifying hash value for the loader
385 result += ">";
386 return result;
387}
388
Elliott Hughesc967f782012-04-16 10:23:15 -0700389std::string PrettySize(size_t byte_count) {
390 // The byte thresholds at which we display amounts. A byte count is displayed
391 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
392 static const size_t kUnitThresholds[] = {
393 0, // B up to...
394 3*1024, // KB up to...
395 2*1024*1024, // MB up to...
396 1024*1024*1024 // GB from here.
397 };
398 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
399 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
400
401 int i = arraysize(kUnitThresholds);
402 while (--i > 0) {
403 if (byte_count >= kUnitThresholds[i]) {
404 break;
405 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800406 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700407
408 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800409}
410
411std::string PrettyDuration(uint64_t nano_duration) {
412 if (nano_duration == 0) {
413 return "0";
414 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700415 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
416 }
417}
418
419TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
420 const uint64_t one_sec = 1000 * 1000 * 1000;
421 const uint64_t one_ms = 1000 * 1000;
422 const uint64_t one_us = 1000;
423 if (nano_duration >= one_sec) {
424 return kTimeUnitSecond;
425 } else if (nano_duration >= one_ms) {
426 return kTimeUnitMillisecond;
427 } else if (nano_duration >= one_us) {
428 return kTimeUnitMicrosecond;
429 } else {
430 return kTimeUnitNanosecond;
431 }
432}
433
434uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
435 const uint64_t one_sec = 1000 * 1000 * 1000;
436 const uint64_t one_ms = 1000 * 1000;
437 const uint64_t one_us = 1000;
438
439 switch (time_unit) {
440 case kTimeUnitSecond:
441 return one_sec;
442 case kTimeUnitMillisecond:
443 return one_ms;
444 case kTimeUnitMicrosecond:
445 return one_us;
446 case kTimeUnitNanosecond:
447 return 1;
448 }
449 return 0;
450}
451
452std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
453 const char* unit = NULL;
454 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
455 uint32_t zero_fill = 1;
456 switch (time_unit) {
457 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800458 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800459 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700460 break;
461 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800462 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800463 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700464 break;
465 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800466 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800467 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700468 break;
469 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800470 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800471 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700472 break;
473 }
474
475 uint64_t whole_part = nano_duration / divisor;
476 uint64_t fractional_part = nano_duration % divisor;
477 if (fractional_part == 0) {
478 return StringPrintf("%llu%s", whole_part, unit);
479 } else {
480 while ((fractional_part % 1000) == 0) {
481 zero_fill -= 3;
482 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800483 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700484 if (zero_fill == 3) {
485 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
486 } else if (zero_fill == 6) {
487 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800488 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700489 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800490 }
491 }
492}
493
Elliott Hughes82914b62012-04-09 15:56:29 -0700494std::string PrintableString(const std::string& utf) {
495 std::string result;
496 result += '"';
497 const char* p = utf.c_str();
498 size_t char_count = CountModifiedUtf8Chars(p);
499 for (size_t i = 0; i < char_count; ++i) {
500 uint16_t ch = GetUtf16FromUtf8(&p);
501 if (ch == '\\') {
502 result += "\\\\";
503 } else if (ch == '\n') {
504 result += "\\n";
505 } else if (ch == '\r') {
506 result += "\\r";
507 } else if (ch == '\t') {
508 result += "\\t";
509 } else if (NeedsEscaping(ch)) {
510 StringAppendF(&result, "\\u%04x", ch);
511 } else {
512 result += ch;
513 }
514 }
515 result += '"';
516 return result;
517}
518
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800519// 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 -0700520std::string MangleForJni(const std::string& s) {
521 std::string result;
522 size_t char_count = CountModifiedUtf8Chars(s.c_str());
523 const char* cp = &s[0];
524 for (size_t i = 0; i < char_count; ++i) {
525 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800526 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
527 result.push_back(ch);
528 } else if (ch == '.' || ch == '/') {
529 result += "_";
530 } else if (ch == '_') {
531 result += "_1";
532 } else if (ch == ';') {
533 result += "_2";
534 } else if (ch == '[') {
535 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700536 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800537 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700538 }
539 }
540 return result;
541}
542
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700543std::string DotToDescriptor(const char* class_name) {
544 std::string descriptor(class_name);
545 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
546 if (descriptor.length() > 0 && descriptor[0] != '[') {
547 descriptor = "L" + descriptor + ";";
548 }
549 return descriptor;
550}
551
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800552std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800553 size_t length = strlen(descriptor);
554 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
555 std::string result(descriptor + 1, length - 2);
556 std::replace(result.begin(), result.end(), '/', '.');
557 return result;
558 }
559 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800560}
561
562std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800563 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800564 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
565 std::string result(descriptor + 1, length - 2);
566 return result;
567 }
568 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700569}
570
Elliott Hughes79082e32011-08-25 12:07:32 -0700571std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800572 MethodHelper mh(m);
573 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700574 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700575 CHECK_EQ(class_name[0], 'L') << class_name;
576 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700577 class_name.erase(0, 1);
578 class_name.erase(class_name.size() - 1, 1);
579
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800580 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700581
582 std::string short_name;
583 short_name += "Java_";
584 short_name += MangleForJni(class_name);
585 short_name += "_";
586 short_name += MangleForJni(method_name);
587 return short_name;
588}
589
590std::string JniLongName(const Method* m) {
591 std::string long_name;
592 long_name += JniShortName(m);
593 long_name += "__";
594
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800595 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700596 signature.erase(0, 1);
597 signature.erase(signature.begin() + signature.find(')'), signature.end());
598
599 long_name += MangleForJni(signature);
600
601 return long_name;
602}
603
jeffhao10037c82012-01-23 15:06:23 -0800604// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700605uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
606 0x00000000, // 00..1f low control characters; nothing valid
607 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
608 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
609 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
610};
611
jeffhao10037c82012-01-23 15:06:23 -0800612// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
613bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700614 /*
615 * It's a multibyte encoded character. Decode it and analyze. We
616 * accept anything that isn't (a) an improperly encoded low value,
617 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
618 * control character, or (e) a high space, layout, or special
619 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
620 * U+fff0..U+ffff). This is all specified in the dex format
621 * document.
622 */
623
624 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
625
626 // Perform follow-up tests based on the high 8 bits.
627 switch (utf16 >> 8) {
628 case 0x00:
629 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
630 return (utf16 > 0x00a0);
631 case 0xd8:
632 case 0xd9:
633 case 0xda:
634 case 0xdb:
635 // It's a leading surrogate. Check to see that a trailing
636 // surrogate follows.
637 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
638 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
639 case 0xdc:
640 case 0xdd:
641 case 0xde:
642 case 0xdf:
643 // It's a trailing surrogate, which is not valid at this point.
644 return false;
645 case 0x20:
646 case 0xff:
647 // It's in the range that has spaces, controls, and specials.
648 switch (utf16 & 0xfff8) {
649 case 0x2000:
650 case 0x2008:
651 case 0x2028:
652 case 0xfff0:
653 case 0xfff8:
654 return false;
655 }
656 break;
657 }
658 return true;
659}
660
661/* Return whether the pointed-at modified-UTF-8 encoded character is
662 * valid as part of a member name, updating the pointer to point past
663 * the consumed character. This will consume two encoded UTF-16 code
664 * points if the character is encoded as a surrogate pair. Also, if
665 * this function returns false, then the given pointer may only have
666 * been partially advanced.
667 */
jeffhao10037c82012-01-23 15:06:23 -0800668bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700669 uint8_t c = (uint8_t) **pUtf8Ptr;
670 if (c <= 0x7f) {
671 // It's low-ascii, so check the table.
672 uint32_t wordIdx = c >> 5;
673 uint32_t bitIdx = c & 0x1f;
674 (*pUtf8Ptr)++;
675 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
676 }
677
678 // It's a multibyte encoded character. Call a non-inline function
679 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800680 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
681}
682
683bool IsValidMemberName(const char* s) {
684 bool angle_name = false;
685
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700686 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800687 case '\0':
688 // The empty string is not a valid name.
689 return false;
690 case '<':
691 angle_name = true;
692 s++;
693 break;
694 }
695
696 while (true) {
697 switch (*s) {
698 case '\0':
699 return !angle_name;
700 case '>':
701 return angle_name && s[1] == '\0';
702 }
703
704 if (!IsValidPartOfMemberNameUtf8(&s)) {
705 return false;
706 }
707 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700708}
709
Elliott Hughes906e6852011-10-28 14:52:10 -0700710enum ClassNameType { kName, kDescriptor };
711bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700712 int arrayCount = 0;
713 while (*s == '[') {
714 arrayCount++;
715 s++;
716 }
717
718 if (arrayCount > 255) {
719 // Arrays may have no more than 255 dimensions.
720 return false;
721 }
722
723 if (arrayCount != 0) {
724 /*
725 * If we're looking at an array of some sort, then it doesn't
726 * matter if what is being asked for is a class name; the
727 * format looks the same as a type descriptor in that case, so
728 * treat it as such.
729 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700730 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700731 }
732
Elliott Hughes906e6852011-10-28 14:52:10 -0700733 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700734 /*
735 * We are looking for a descriptor. Either validate it as a
736 * single-character primitive type, or continue on to check the
737 * embedded class name (bracketed by "L" and ";").
738 */
739 switch (*(s++)) {
740 case 'B':
741 case 'C':
742 case 'D':
743 case 'F':
744 case 'I':
745 case 'J':
746 case 'S':
747 case 'Z':
748 // These are all single-character descriptors for primitive types.
749 return (*s == '\0');
750 case 'V':
751 // Non-array void is valid, but you can't have an array of void.
752 return (arrayCount == 0) && (*s == '\0');
753 case 'L':
754 // Class name: Break out and continue below.
755 break;
756 default:
757 // Oddball descriptor character.
758 return false;
759 }
760 }
761
762 /*
763 * We just consumed the 'L' that introduces a class name as part
764 * of a type descriptor, or we are looking for an unadorned class
765 * name.
766 */
767
768 bool sepOrFirst = true; // first character or just encountered a separator.
769 for (;;) {
770 uint8_t c = (uint8_t) *s;
771 switch (c) {
772 case '\0':
773 /*
774 * Premature end for a type descriptor, but valid for
775 * a class name as long as we haven't encountered an
776 * empty component (including the degenerate case of
777 * the empty string "").
778 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700779 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700780 case ';':
781 /*
782 * Invalid character for a class name, but the
783 * legitimate end of a type descriptor. In the latter
784 * case, make sure that this is the end of the string
785 * and that it doesn't end with an empty component
786 * (including the degenerate case of "L;").
787 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700788 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700789 case '/':
790 case '.':
791 if (c != separator) {
792 // The wrong separator character.
793 return false;
794 }
795 if (sepOrFirst) {
796 // Separator at start or two separators in a row.
797 return false;
798 }
799 sepOrFirst = true;
800 s++;
801 break;
802 default:
jeffhao10037c82012-01-23 15:06:23 -0800803 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700804 return false;
805 }
806 sepOrFirst = false;
807 break;
808 }
809 }
810}
811
Elliott Hughes906e6852011-10-28 14:52:10 -0700812bool IsValidBinaryClassName(const char* s) {
813 return IsValidClassName(s, kName, '.');
814}
815
816bool IsValidJniClassName(const char* s) {
817 return IsValidClassName(s, kName, '/');
818}
819
820bool IsValidDescriptor(const char* s) {
821 return IsValidClassName(s, kDescriptor, '/');
822}
823
Elliott Hughes48436bb2012-02-07 15:23:28 -0800824void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700825 const char* p = s.data();
826 const char* end = p + s.size();
827 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800828 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700829 ++p;
830 } else {
831 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800832 while (++p != end && *p != separator) {
833 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700834 }
835 result.push_back(std::string(start, p - start));
836 }
837 }
838}
839
Elliott Hughes48436bb2012-02-07 15:23:28 -0800840template <typename StringT>
841std::string Join(std::vector<StringT>& strings, char separator) {
842 if (strings.empty()) {
843 return "";
844 }
845
846 std::string result(strings[0]);
847 for (size_t i = 1; i < strings.size(); ++i) {
848 result += separator;
849 result += strings[i];
850 }
851 return result;
852}
853
854// Explicit instantiations.
855template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
856template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
857template std::string Join<char*>(std::vector<char*>& strings, char separator);
858
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800859bool StartsWith(const std::string& s, const char* prefix) {
860 return s.compare(0, strlen(prefix), prefix) == 0;
861}
862
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700863bool EndsWith(const std::string& s, const char* suffix) {
864 size_t suffix_length = strlen(suffix);
865 size_t string_length = s.size();
866 if (suffix_length > string_length) {
867 return false;
868 }
869 size_t offset = string_length - suffix_length;
870 return s.compare(offset, suffix_length, suffix) == 0;
871}
872
Elliott Hughes22869a92012-03-27 14:08:24 -0700873void SetThreadName(const char* thread_name) {
874 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800875
Elliott Hughesdcc24742011-09-07 14:02:44 -0700876 int hasAt = 0;
877 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700878 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700879 while (*s) {
880 if (*s == '.') {
881 hasDot = 1;
882 } else if (*s == '@') {
883 hasAt = 1;
884 }
885 s++;
886 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700887 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700888 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700889 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700890 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700891 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700892 }
893#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700894 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700895 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
896 strncpy(buf, s, sizeof(buf)-1);
897 buf[sizeof(buf)-1] = '\0';
898 errno = pthread_setname_np(pthread_self(), buf);
899 if (errno != 0) {
900 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
901 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700902#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700903 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700904#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700905 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700906#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700907 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700908#endif
909}
910
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700911void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
912 utime = stime = task_cpu = 0;
913 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700914 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700915 return;
916 }
917 // Skip the command, which may contain spaces.
918 stats = stats.substr(stats.find(')') + 2);
919 // Extract the three fields we care about.
920 std::vector<std::string> fields;
921 Split(stats, ' ', fields);
922 utime = strtoull(fields[11].c_str(), NULL, 10);
923 stime = strtoull(fields[12].c_str(), NULL, 10);
924 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
925}
926
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700927std::string GetSchedulerGroupName(pid_t tid) {
928 // /proc/<pid>/cgroup looks like this:
929 // 2:devices:/
930 // 1:cpuacct,cpu:/
931 // We want the third field from the line whose second field contains the "cpu" token.
932 std::string cgroup_file;
933 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
934 return "";
935 }
936 std::vector<std::string> cgroup_lines;
937 Split(cgroup_file, '\n', cgroup_lines);
938 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
939 std::vector<std::string> cgroup_fields;
940 Split(cgroup_lines[i], ':', cgroup_fields);
941 std::vector<std::string> cgroups;
942 Split(cgroup_fields[1], ',', cgroups);
943 for (size_t i = 0; i < cgroups.size(); ++i) {
944 if (cgroups[i] == "cpu") {
945 return cgroup_fields[2].substr(1); // Skip the leading slash.
946 }
947 }
948 }
949 return "";
950}
951
Elliott Hughes46e251b2012-05-22 15:10:45 -0700952static const char* CleanMapName(const backtrace_symbol_t* symbol) {
953 const char* map_name = symbol->map_name;
954 if (map_name == NULL) {
955 map_name = "???";
956 }
957 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
958 // into "libartd.so".
959 const char* last_slash = strrchr(map_name, '/');
960 if (last_slash != NULL) {
961 map_name = last_slash + 1;
962 }
963 return map_name;
964}
965
966static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
967 std::string& symbol_name, uint32_t& pc_offset) {
968 symbol_table_t* symbol_table = NULL;
969 if (symbol->map_name != NULL) {
970 symbol_table = load_symbol_table(symbol->map_name);
971 }
972 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -0700973 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700974 if (symbol_table != NULL) {
975 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
976 if (elf_symbol == NULL) {
977 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -0700978 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700979 }
980 }
981 if (elf_symbol != NULL) {
982 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
983 if (demangled_symbol_name != NULL) {
984 symbol_name = demangled_symbol_name;
985 } else {
986 symbol_name = elf_symbol->name;
987 }
Elliott Hughes95aff772012-06-12 17:44:15 -0700988
989 // TODO: is it a libcorkscrew bug that we have to do this?
990 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700991 } else {
992 symbol_name = "???";
993 }
994 free_symbol_table(symbol_table);
995}
996
997void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -0700998 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
999 flush_my_map_info_list();
1000
Elliott Hughes46e251b2012-05-22 15:10:45 -07001001 const size_t MAX_DEPTH = 32;
1002 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001003 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
1004 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001005 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001006 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001007 return;
1008 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001009 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001010 return;
1011 }
1012
1013 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1014 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1015
1016 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1017 const backtrace_frame_t* frame = &frames[i];
1018 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1019
1020 // We produce output like this:
1021 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1022
1023 std::string symbol_name;
1024 uint32_t pc_offset = 0;
1025 if (symbol->demangled_name != NULL) {
1026 symbol_name = symbol->demangled_name;
1027 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1028 } else if (symbol->symbol_name != NULL) {
1029 symbol_name = symbol->symbol_name;
1030 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1031 } else {
1032 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1033 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1034 }
1035
1036 os << prefix;
1037 if (include_count) {
1038 os << StringPrintf("#%02zd ", i);
1039 }
1040 os << symbol_name;
1041 if (pc_offset != 0) {
1042 os << "+" << pc_offset;
1043 }
1044 os << StringPrintf(" [%p] (%s)\n",
1045 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1046 }
1047
1048 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1049}
1050
Elliott Hughes058a6de2012-05-24 19:13:02 -07001051#if defined(__APPLE__)
1052
1053// TODO: is there any way to get the kernel stack on Mac OS?
1054void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1055
1056#else
1057
Elliott Hughes46e251b2012-05-22 15:10:45 -07001058void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001059 if (tid == GetTid()) {
1060 // There's no point showing that we're reading our stack out of /proc!
1061 return;
1062 }
1063
Elliott Hughes46e251b2012-05-22 15:10:45 -07001064 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1065 std::string kernel_stack;
1066 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001067 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001068 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001069 }
1070
1071 std::vector<std::string> kernel_stack_frames;
1072 Split(kernel_stack, '\n', kernel_stack_frames);
1073 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1074 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1075 kernel_stack_frames.pop_back();
1076 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1077 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1078 const char* text = kernel_stack_frames[i].c_str();
1079 const char* close_bracket = strchr(text, ']');
1080 if (close_bracket != NULL) {
1081 text = close_bracket + 2;
1082 }
1083 os << prefix;
1084 if (include_count) {
1085 os << StringPrintf("#%02zd ", i);
1086 }
1087 os << text << "\n";
1088 }
1089}
1090
1091#endif
1092
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001093const char* GetAndroidRoot() {
1094 const char* android_root = getenv("ANDROID_ROOT");
1095 if (android_root == NULL) {
1096 if (OS::DirectoryExists("/system")) {
1097 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001098 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001099 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1100 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001101 }
1102 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001103 if (!OS::DirectoryExists(android_root)) {
1104 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001105 return "";
1106 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001107 return android_root;
1108}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001109
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001110const char* GetAndroidData() {
1111 const char* android_data = getenv("ANDROID_DATA");
1112 if (android_data == NULL) {
1113 if (OS::DirectoryExists("/data")) {
1114 android_data = "/data";
1115 } else {
1116 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1117 return "";
1118 }
1119 }
1120 if (!OS::DirectoryExists(android_data)) {
1121 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1122 return "";
1123 }
1124 return android_data;
1125}
1126
Shih-wei Liao795e3302012-04-21 00:20:57 -07001127std::string GetArtCacheOrDie(const char* android_data) {
1128 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001129
1130 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001131 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001132 int result = mkdir(art_cache.c_str(), 0700);
1133 if (result != 0) {
1134 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1135 return "";
1136 }
1137 } else {
1138 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1139 return "";
1140 }
1141 }
1142 return art_cache;
1143}
1144
jeffhao262bf462011-10-20 18:36:32 -07001145std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001146 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001147 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001148 std::string cache_file(location, 1); // skip leading slash
1149 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1150 return art_cache + "/" + cache_file;
1151}
1152
jeffhao262bf462011-10-20 18:36:32 -07001153bool IsValidZipFilename(const std::string& filename) {
1154 if (filename.size() < 4) {
1155 return false;
1156 }
1157 std::string suffix(filename.substr(filename.size() - 4));
1158 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1159}
1160
1161bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001162 return EndsWith(filename, ".dex");
1163}
1164
1165bool IsValidOatFilename(const std::string& filename) {
1166 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001167}
1168
Elliott Hughes42ee1422011-09-06 12:33:32 -07001169} // namespace art