blob: d038f6d814c182e1bff233c13b3a83c5f55947b7 [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
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700280std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
281 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
282 std::string result;
283 result += PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
284 result += ' ';
285 return result;
286}
287
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700288std::string PrettyArguments(const char* signature) {
289 std::string result;
290 result += '(';
291 CHECK_EQ(*signature, '(');
292 ++signature; // Skip the '('.
293 while (*signature != ')') {
294 size_t argument_length = 0;
295 while (signature[argument_length] == '[') {
296 ++argument_length;
297 }
298 if (signature[argument_length] == 'L') {
299 argument_length = (strchr(signature, ';') - signature + 1);
300 } else {
301 ++argument_length;
302 }
303 std::string argument_descriptor(signature, argument_length);
304 result += PrettyDescriptor(argument_descriptor);
305 if (signature[argument_length] != ')') {
306 result += ", ";
307 }
308 signature += argument_length;
309 }
310 CHECK_EQ(*signature, ')');
311 ++signature; // Skip the ')'.
312 result += ')';
313 return result;
314}
315
316std::string PrettyReturnType(const char* signature) {
317 const char* return_type = strchr(signature, ')');
318 CHECK(return_type != NULL);
319 ++return_type; // Skip ')'.
320 return PrettyDescriptor(return_type);
321}
322
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700323std::string PrettyMethod(const Method* m, bool with_signature) {
324 if (m == NULL) {
325 return "null";
326 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800327 MethodHelper mh(m);
328 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700329 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800330 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700331 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700332 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700333 if (signature == "<no signature>") {
334 return result + signature;
335 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700336 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700337 }
338 return result;
339}
340
Ian Rogers0571d352011-11-03 19:51:38 -0700341std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
342 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
343 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
344 result += '.';
345 result += dex_file.GetMethodName(method_id);
346 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700347 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700348 if (signature == "<no signature>") {
349 return result + signature;
350 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700351 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700352 }
353 return result;
354}
355
Elliott Hughes54e7df12011-09-16 11:47:04 -0700356std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700357 if (obj == NULL) {
358 return "null";
359 }
360 if (obj->GetClass() == NULL) {
361 return "(raw)";
362 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800363 ClassHelper kh(obj->GetClass());
364 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700365 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800366 kh.ChangeClass(obj->AsClass());
367 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700368 }
369 return result;
370}
371
Elliott Hughes54e7df12011-09-16 11:47:04 -0700372std::string PrettyClass(const Class* c) {
373 if (c == NULL) {
374 return "null";
375 }
376 std::string result;
377 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800378 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700379 result += ">";
380 return result;
381}
382
Ian Rogersd81871c2011-10-03 13:57:23 -0700383std::string PrettyClassAndClassLoader(const Class* c) {
384 if (c == NULL) {
385 return "null";
386 }
387 std::string result;
388 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800389 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700390 result += ",";
391 result += PrettyTypeOf(c->GetClassLoader());
392 // TODO: add an identifying hash value for the loader
393 result += ">";
394 return result;
395}
396
Elliott Hughesc967f782012-04-16 10:23:15 -0700397std::string PrettySize(size_t byte_count) {
398 // The byte thresholds at which we display amounts. A byte count is displayed
399 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
400 static const size_t kUnitThresholds[] = {
401 0, // B up to...
402 3*1024, // KB up to...
403 2*1024*1024, // MB up to...
404 1024*1024*1024 // GB from here.
405 };
406 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
407 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
408
409 int i = arraysize(kUnitThresholds);
410 while (--i > 0) {
411 if (byte_count >= kUnitThresholds[i]) {
412 break;
413 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800414 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700415
416 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800417}
418
419std::string PrettyDuration(uint64_t nano_duration) {
420 if (nano_duration == 0) {
421 return "0";
422 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700423 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
424 }
425}
426
427TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
428 const uint64_t one_sec = 1000 * 1000 * 1000;
429 const uint64_t one_ms = 1000 * 1000;
430 const uint64_t one_us = 1000;
431 if (nano_duration >= one_sec) {
432 return kTimeUnitSecond;
433 } else if (nano_duration >= one_ms) {
434 return kTimeUnitMillisecond;
435 } else if (nano_duration >= one_us) {
436 return kTimeUnitMicrosecond;
437 } else {
438 return kTimeUnitNanosecond;
439 }
440}
441
442uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
443 const uint64_t one_sec = 1000 * 1000 * 1000;
444 const uint64_t one_ms = 1000 * 1000;
445 const uint64_t one_us = 1000;
446
447 switch (time_unit) {
448 case kTimeUnitSecond:
449 return one_sec;
450 case kTimeUnitMillisecond:
451 return one_ms;
452 case kTimeUnitMicrosecond:
453 return one_us;
454 case kTimeUnitNanosecond:
455 return 1;
456 }
457 return 0;
458}
459
460std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
461 const char* unit = NULL;
462 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
463 uint32_t zero_fill = 1;
464 switch (time_unit) {
465 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800466 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800467 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700468 break;
469 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800470 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800471 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700472 break;
473 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800474 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800475 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700476 break;
477 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800478 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800479 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700480 break;
481 }
482
483 uint64_t whole_part = nano_duration / divisor;
484 uint64_t fractional_part = nano_duration % divisor;
485 if (fractional_part == 0) {
486 return StringPrintf("%llu%s", whole_part, unit);
487 } else {
488 while ((fractional_part % 1000) == 0) {
489 zero_fill -= 3;
490 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800491 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700492 if (zero_fill == 3) {
493 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
494 } else if (zero_fill == 6) {
495 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800496 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700497 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800498 }
499 }
500}
501
Elliott Hughes82914b62012-04-09 15:56:29 -0700502std::string PrintableString(const std::string& utf) {
503 std::string result;
504 result += '"';
505 const char* p = utf.c_str();
506 size_t char_count = CountModifiedUtf8Chars(p);
507 for (size_t i = 0; i < char_count; ++i) {
508 uint16_t ch = GetUtf16FromUtf8(&p);
509 if (ch == '\\') {
510 result += "\\\\";
511 } else if (ch == '\n') {
512 result += "\\n";
513 } else if (ch == '\r') {
514 result += "\\r";
515 } else if (ch == '\t') {
516 result += "\\t";
517 } else if (NeedsEscaping(ch)) {
518 StringAppendF(&result, "\\u%04x", ch);
519 } else {
520 result += ch;
521 }
522 }
523 result += '"';
524 return result;
525}
526
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800527// 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 -0700528std::string MangleForJni(const std::string& s) {
529 std::string result;
530 size_t char_count = CountModifiedUtf8Chars(s.c_str());
531 const char* cp = &s[0];
532 for (size_t i = 0; i < char_count; ++i) {
533 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800534 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
535 result.push_back(ch);
536 } else if (ch == '.' || ch == '/') {
537 result += "_";
538 } else if (ch == '_') {
539 result += "_1";
540 } else if (ch == ';') {
541 result += "_2";
542 } else if (ch == '[') {
543 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700544 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800545 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700546 }
547 }
548 return result;
549}
550
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700551std::string DotToDescriptor(const char* class_name) {
552 std::string descriptor(class_name);
553 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
554 if (descriptor.length() > 0 && descriptor[0] != '[') {
555 descriptor = "L" + descriptor + ";";
556 }
557 return descriptor;
558}
559
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800560std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800561 size_t length = strlen(descriptor);
562 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
563 std::string result(descriptor + 1, length - 2);
564 std::replace(result.begin(), result.end(), '/', '.');
565 return result;
566 }
567 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800568}
569
570std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800571 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800572 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
573 std::string result(descriptor + 1, length - 2);
574 return result;
575 }
576 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700577}
578
Elliott Hughes79082e32011-08-25 12:07:32 -0700579std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800580 MethodHelper mh(m);
581 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700582 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700583 CHECK_EQ(class_name[0], 'L') << class_name;
584 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700585 class_name.erase(0, 1);
586 class_name.erase(class_name.size() - 1, 1);
587
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800588 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700589
590 std::string short_name;
591 short_name += "Java_";
592 short_name += MangleForJni(class_name);
593 short_name += "_";
594 short_name += MangleForJni(method_name);
595 return short_name;
596}
597
598std::string JniLongName(const Method* m) {
599 std::string long_name;
600 long_name += JniShortName(m);
601 long_name += "__";
602
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800603 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700604 signature.erase(0, 1);
605 signature.erase(signature.begin() + signature.find(')'), signature.end());
606
607 long_name += MangleForJni(signature);
608
609 return long_name;
610}
611
jeffhao10037c82012-01-23 15:06:23 -0800612// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700613uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
614 0x00000000, // 00..1f low control characters; nothing valid
615 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
616 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
617 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
618};
619
jeffhao10037c82012-01-23 15:06:23 -0800620// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
621bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700622 /*
623 * It's a multibyte encoded character. Decode it and analyze. We
624 * accept anything that isn't (a) an improperly encoded low value,
625 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
626 * control character, or (e) a high space, layout, or special
627 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
628 * U+fff0..U+ffff). This is all specified in the dex format
629 * document.
630 */
631
632 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
633
634 // Perform follow-up tests based on the high 8 bits.
635 switch (utf16 >> 8) {
636 case 0x00:
637 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
638 return (utf16 > 0x00a0);
639 case 0xd8:
640 case 0xd9:
641 case 0xda:
642 case 0xdb:
643 // It's a leading surrogate. Check to see that a trailing
644 // surrogate follows.
645 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
646 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
647 case 0xdc:
648 case 0xdd:
649 case 0xde:
650 case 0xdf:
651 // It's a trailing surrogate, which is not valid at this point.
652 return false;
653 case 0x20:
654 case 0xff:
655 // It's in the range that has spaces, controls, and specials.
656 switch (utf16 & 0xfff8) {
657 case 0x2000:
658 case 0x2008:
659 case 0x2028:
660 case 0xfff0:
661 case 0xfff8:
662 return false;
663 }
664 break;
665 }
666 return true;
667}
668
669/* Return whether the pointed-at modified-UTF-8 encoded character is
670 * valid as part of a member name, updating the pointer to point past
671 * the consumed character. This will consume two encoded UTF-16 code
672 * points if the character is encoded as a surrogate pair. Also, if
673 * this function returns false, then the given pointer may only have
674 * been partially advanced.
675 */
jeffhao10037c82012-01-23 15:06:23 -0800676bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700677 uint8_t c = (uint8_t) **pUtf8Ptr;
678 if (c <= 0x7f) {
679 // It's low-ascii, so check the table.
680 uint32_t wordIdx = c >> 5;
681 uint32_t bitIdx = c & 0x1f;
682 (*pUtf8Ptr)++;
683 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
684 }
685
686 // It's a multibyte encoded character. Call a non-inline function
687 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800688 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
689}
690
691bool IsValidMemberName(const char* s) {
692 bool angle_name = false;
693
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700694 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800695 case '\0':
696 // The empty string is not a valid name.
697 return false;
698 case '<':
699 angle_name = true;
700 s++;
701 break;
702 }
703
704 while (true) {
705 switch (*s) {
706 case '\0':
707 return !angle_name;
708 case '>':
709 return angle_name && s[1] == '\0';
710 }
711
712 if (!IsValidPartOfMemberNameUtf8(&s)) {
713 return false;
714 }
715 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700716}
717
Elliott Hughes906e6852011-10-28 14:52:10 -0700718enum ClassNameType { kName, kDescriptor };
719bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700720 int arrayCount = 0;
721 while (*s == '[') {
722 arrayCount++;
723 s++;
724 }
725
726 if (arrayCount > 255) {
727 // Arrays may have no more than 255 dimensions.
728 return false;
729 }
730
731 if (arrayCount != 0) {
732 /*
733 * If we're looking at an array of some sort, then it doesn't
734 * matter if what is being asked for is a class name; the
735 * format looks the same as a type descriptor in that case, so
736 * treat it as such.
737 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700738 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700739 }
740
Elliott Hughes906e6852011-10-28 14:52:10 -0700741 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700742 /*
743 * We are looking for a descriptor. Either validate it as a
744 * single-character primitive type, or continue on to check the
745 * embedded class name (bracketed by "L" and ";").
746 */
747 switch (*(s++)) {
748 case 'B':
749 case 'C':
750 case 'D':
751 case 'F':
752 case 'I':
753 case 'J':
754 case 'S':
755 case 'Z':
756 // These are all single-character descriptors for primitive types.
757 return (*s == '\0');
758 case 'V':
759 // Non-array void is valid, but you can't have an array of void.
760 return (arrayCount == 0) && (*s == '\0');
761 case 'L':
762 // Class name: Break out and continue below.
763 break;
764 default:
765 // Oddball descriptor character.
766 return false;
767 }
768 }
769
770 /*
771 * We just consumed the 'L' that introduces a class name as part
772 * of a type descriptor, or we are looking for an unadorned class
773 * name.
774 */
775
776 bool sepOrFirst = true; // first character or just encountered a separator.
777 for (;;) {
778 uint8_t c = (uint8_t) *s;
779 switch (c) {
780 case '\0':
781 /*
782 * Premature end for a type descriptor, but valid for
783 * a class name as long as we haven't encountered an
784 * empty component (including the degenerate case of
785 * the empty string "").
786 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700787 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700788 case ';':
789 /*
790 * Invalid character for a class name, but the
791 * legitimate end of a type descriptor. In the latter
792 * case, make sure that this is the end of the string
793 * and that it doesn't end with an empty component
794 * (including the degenerate case of "L;").
795 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700796 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700797 case '/':
798 case '.':
799 if (c != separator) {
800 // The wrong separator character.
801 return false;
802 }
803 if (sepOrFirst) {
804 // Separator at start or two separators in a row.
805 return false;
806 }
807 sepOrFirst = true;
808 s++;
809 break;
810 default:
jeffhao10037c82012-01-23 15:06:23 -0800811 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700812 return false;
813 }
814 sepOrFirst = false;
815 break;
816 }
817 }
818}
819
Elliott Hughes906e6852011-10-28 14:52:10 -0700820bool IsValidBinaryClassName(const char* s) {
821 return IsValidClassName(s, kName, '.');
822}
823
824bool IsValidJniClassName(const char* s) {
825 return IsValidClassName(s, kName, '/');
826}
827
828bool IsValidDescriptor(const char* s) {
829 return IsValidClassName(s, kDescriptor, '/');
830}
831
Elliott Hughes48436bb2012-02-07 15:23:28 -0800832void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700833 const char* p = s.data();
834 const char* end = p + s.size();
835 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800836 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700837 ++p;
838 } else {
839 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800840 while (++p != end && *p != separator) {
841 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700842 }
843 result.push_back(std::string(start, p - start));
844 }
845 }
846}
847
Elliott Hughes48436bb2012-02-07 15:23:28 -0800848template <typename StringT>
849std::string Join(std::vector<StringT>& strings, char separator) {
850 if (strings.empty()) {
851 return "";
852 }
853
854 std::string result(strings[0]);
855 for (size_t i = 1; i < strings.size(); ++i) {
856 result += separator;
857 result += strings[i];
858 }
859 return result;
860}
861
862// Explicit instantiations.
863template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
864template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
865template std::string Join<char*>(std::vector<char*>& strings, char separator);
866
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800867bool StartsWith(const std::string& s, const char* prefix) {
868 return s.compare(0, strlen(prefix), prefix) == 0;
869}
870
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700871bool EndsWith(const std::string& s, const char* suffix) {
872 size_t suffix_length = strlen(suffix);
873 size_t string_length = s.size();
874 if (suffix_length > string_length) {
875 return false;
876 }
877 size_t offset = string_length - suffix_length;
878 return s.compare(offset, suffix_length, suffix) == 0;
879}
880
Elliott Hughes22869a92012-03-27 14:08:24 -0700881void SetThreadName(const char* thread_name) {
882 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800883
Elliott Hughesdcc24742011-09-07 14:02:44 -0700884 int hasAt = 0;
885 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700886 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700887 while (*s) {
888 if (*s == '.') {
889 hasDot = 1;
890 } else if (*s == '@') {
891 hasAt = 1;
892 }
893 s++;
894 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700895 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700896 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700897 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700898 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700899 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700900 }
901#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700902 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700903 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
904 strncpy(buf, s, sizeof(buf)-1);
905 buf[sizeof(buf)-1] = '\0';
906 errno = pthread_setname_np(pthread_self(), buf);
907 if (errno != 0) {
908 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
909 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700910#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700911 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700912#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700913 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700914#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700915 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700916#endif
917}
918
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700919void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
920 utime = stime = task_cpu = 0;
921 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700922 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700923 return;
924 }
925 // Skip the command, which may contain spaces.
926 stats = stats.substr(stats.find(')') + 2);
927 // Extract the three fields we care about.
928 std::vector<std::string> fields;
929 Split(stats, ' ', fields);
930 utime = strtoull(fields[11].c_str(), NULL, 10);
931 stime = strtoull(fields[12].c_str(), NULL, 10);
932 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
933}
934
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700935std::string GetSchedulerGroupName(pid_t tid) {
936 // /proc/<pid>/cgroup looks like this:
937 // 2:devices:/
938 // 1:cpuacct,cpu:/
939 // We want the third field from the line whose second field contains the "cpu" token.
940 std::string cgroup_file;
941 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
942 return "";
943 }
944 std::vector<std::string> cgroup_lines;
945 Split(cgroup_file, '\n', cgroup_lines);
946 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
947 std::vector<std::string> cgroup_fields;
948 Split(cgroup_lines[i], ':', cgroup_fields);
949 std::vector<std::string> cgroups;
950 Split(cgroup_fields[1], ',', cgroups);
951 for (size_t i = 0; i < cgroups.size(); ++i) {
952 if (cgroups[i] == "cpu") {
953 return cgroup_fields[2].substr(1); // Skip the leading slash.
954 }
955 }
956 }
957 return "";
958}
959
Elliott Hughes46e251b2012-05-22 15:10:45 -0700960static const char* CleanMapName(const backtrace_symbol_t* symbol) {
961 const char* map_name = symbol->map_name;
962 if (map_name == NULL) {
963 map_name = "???";
964 }
965 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
966 // into "libartd.so".
967 const char* last_slash = strrchr(map_name, '/');
968 if (last_slash != NULL) {
969 map_name = last_slash + 1;
970 }
971 return map_name;
972}
973
974static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
975 std::string& symbol_name, uint32_t& pc_offset) {
976 symbol_table_t* symbol_table = NULL;
977 if (symbol->map_name != NULL) {
978 symbol_table = load_symbol_table(symbol->map_name);
979 }
980 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -0700981 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700982 if (symbol_table != NULL) {
983 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
984 if (elf_symbol == NULL) {
985 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -0700986 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700987 }
988 }
989 if (elf_symbol != NULL) {
990 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
991 if (demangled_symbol_name != NULL) {
992 symbol_name = demangled_symbol_name;
993 } else {
994 symbol_name = elf_symbol->name;
995 }
Elliott Hughes95aff772012-06-12 17:44:15 -0700996
997 // TODO: is it a libcorkscrew bug that we have to do this?
998 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700999 } else {
1000 symbol_name = "???";
1001 }
1002 free_symbol_table(symbol_table);
1003}
1004
1005void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001006 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1007 flush_my_map_info_list();
1008
Elliott Hughes46e251b2012-05-22 15:10:45 -07001009 const size_t MAX_DEPTH = 32;
1010 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001011 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
1012 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001013 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001014 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001015 return;
1016 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001017 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001018 return;
1019 }
1020
1021 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1022 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1023
1024 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1025 const backtrace_frame_t* frame = &frames[i];
1026 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1027
1028 // We produce output like this:
1029 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1030
1031 std::string symbol_name;
1032 uint32_t pc_offset = 0;
1033 if (symbol->demangled_name != NULL) {
1034 symbol_name = symbol->demangled_name;
1035 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1036 } else if (symbol->symbol_name != NULL) {
1037 symbol_name = symbol->symbol_name;
1038 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1039 } else {
1040 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1041 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1042 }
1043
1044 os << prefix;
1045 if (include_count) {
1046 os << StringPrintf("#%02zd ", i);
1047 }
1048 os << symbol_name;
1049 if (pc_offset != 0) {
1050 os << "+" << pc_offset;
1051 }
1052 os << StringPrintf(" [%p] (%s)\n",
1053 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1054 }
1055
1056 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1057}
1058
Elliott Hughes058a6de2012-05-24 19:13:02 -07001059#if defined(__APPLE__)
1060
1061// TODO: is there any way to get the kernel stack on Mac OS?
1062void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1063
1064#else
1065
Elliott Hughes46e251b2012-05-22 15:10:45 -07001066void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001067 if (tid == GetTid()) {
1068 // There's no point showing that we're reading our stack out of /proc!
1069 return;
1070 }
1071
Elliott Hughes46e251b2012-05-22 15:10:45 -07001072 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1073 std::string kernel_stack;
1074 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001075 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001076 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001077 }
1078
1079 std::vector<std::string> kernel_stack_frames;
1080 Split(kernel_stack, '\n', kernel_stack_frames);
1081 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1082 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1083 kernel_stack_frames.pop_back();
1084 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1085 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1086 const char* text = kernel_stack_frames[i].c_str();
1087 const char* close_bracket = strchr(text, ']');
1088 if (close_bracket != NULL) {
1089 text = close_bracket + 2;
1090 }
1091 os << prefix;
1092 if (include_count) {
1093 os << StringPrintf("#%02zd ", i);
1094 }
1095 os << text << "\n";
1096 }
1097}
1098
1099#endif
1100
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001101const char* GetAndroidRoot() {
1102 const char* android_root = getenv("ANDROID_ROOT");
1103 if (android_root == NULL) {
1104 if (OS::DirectoryExists("/system")) {
1105 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001106 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001107 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1108 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001109 }
1110 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001111 if (!OS::DirectoryExists(android_root)) {
1112 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001113 return "";
1114 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001115 return android_root;
1116}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001117
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001118const char* GetAndroidData() {
1119 const char* android_data = getenv("ANDROID_DATA");
1120 if (android_data == NULL) {
1121 if (OS::DirectoryExists("/data")) {
1122 android_data = "/data";
1123 } else {
1124 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1125 return "";
1126 }
1127 }
1128 if (!OS::DirectoryExists(android_data)) {
1129 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1130 return "";
1131 }
1132 return android_data;
1133}
1134
Shih-wei Liao795e3302012-04-21 00:20:57 -07001135std::string GetArtCacheOrDie(const char* android_data) {
1136 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001137
1138 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001139 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001140 int result = mkdir(art_cache.c_str(), 0700);
1141 if (result != 0) {
1142 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1143 return "";
1144 }
1145 } else {
1146 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1147 return "";
1148 }
1149 }
1150 return art_cache;
1151}
1152
jeffhao262bf462011-10-20 18:36:32 -07001153std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001154 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001155 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001156 std::string cache_file(location, 1); // skip leading slash
1157 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1158 return art_cache + "/" + cache_file;
1159}
1160
jeffhao262bf462011-10-20 18:36:32 -07001161bool IsValidZipFilename(const std::string& filename) {
1162 if (filename.size() < 4) {
1163 return false;
1164 }
1165 std::string suffix(filename.substr(filename.size() - 4));
1166 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1167}
1168
1169bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001170 return EndsWith(filename, ".dex");
1171}
1172
1173bool IsValidOatFilename(const std::string& filename) {
1174 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001175}
1176
Elliott Hughes42ee1422011-09-06 12:33:32 -07001177} // namespace art