blob: d45568e5ff382ee5caac4dd10e706508d9f794e8 [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() {
Elliott Hughes5d6d5dc2012-03-29 11:59:27 -070056#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
57 // Darwin has a gettid(2), but it does something completely unrelated to tids.
58 // There is a thread_selfid(2) that does what we want though, and it seems to be what their
Elliott Hughesf1498432012-03-28 19:34:27 -070059 // pthreads implementation uses.
60 return syscall(SYS_thread_selfid);
Elliott Hughes5d6d5dc2012-03-29 11:59:27 -070061#elif defined(__APPLE__)
62 // On Mac OS 10.5 (which the build servers are still running) there was nothing usable.
Elliott Hughesd23f5202012-03-30 19:50:04 -070063 // We know we build 32-bit binaries and that the pthread_t is a pointer that uniquely identifies
64 // the calling thread.
65 return reinterpret_cast<pid_t>(pthread_self());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080066#else
67 // Neither bionic nor glibc exposes gettid(2).
68 return syscall(__NR_gettid);
69#endif
70}
71
Elliott Hughes289be852012-06-12 13:57:20 -070072std::string GetThreadName(pid_t tid) {
73 std::string result;
74 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
75 result.resize(result.size() - 1); // Lose the trailing '\n'.
76 } else {
77 result = "<unknown>";
78 }
79 return result;
80}
81
Elliott Hughese1884192012-04-23 12:38:15 -070082void GetThreadStack(void*& stack_base, size_t& stack_size) {
83#if defined(__APPLE__)
84 stack_size = pthread_get_stacksize_np(pthread_self());
85 void* stack_addr = pthread_get_stackaddr_np(pthread_self());
86
87 // Check whether stack_addr is the base or end of the stack.
88 // (On Mac OS 10.7, it's the end.)
89 int stack_variable;
90 if (stack_addr > &stack_variable) {
91 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
92 } else {
93 stack_base = stack_addr;
94 }
95#else
96 pthread_attr_t attributes;
97 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
98 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
99 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
100#endif
101}
102
Elliott Hughesd92bec42011-09-02 17:04:36 -0700103bool ReadFileToString(const std::string& file_name, std::string* result) {
104 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
105 if (file.get() == NULL) {
106 return false;
107 }
buzbeec143c552011-08-20 17:38:58 -0700108
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700109 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700110 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700111 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700112 if (n == -1) {
113 return false;
buzbeec143c552011-08-20 17:38:58 -0700114 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700115 if (n == 0) {
116 return true;
117 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700118 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700119 }
buzbeec143c552011-08-20 17:38:58 -0700120}
121
Elliott Hughese27955c2011-08-26 15:21:24 -0700122std::string GetIsoDate() {
123 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700124 tm tmbuf;
125 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700126 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
127 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
128 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
129}
130
Elliott Hughes7162ad92011-10-27 14:08:42 -0700131uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800132#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700133 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700134 clock_gettime(CLOCK_MONOTONIC, &now);
135 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800136#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700137 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138 gettimeofday(&now, NULL);
139 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
140#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700141}
142
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800143uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800144#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700145 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800146 clock_gettime(CLOCK_MONOTONIC, &now);
147 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800148#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700149 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700151 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800152#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800153}
154
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700155uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700157 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700158 clock_gettime(CLOCK_MONOTONIC, &now);
159 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800160#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700161 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162 gettimeofday(&now, NULL);
163 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
164#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700165}
166
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800167uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800168#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700169 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800170 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
171 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800172#else
173 UNIMPLEMENTED(WARNING);
174 return -1;
175#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800176}
177
Elliott Hughes0512f022012-03-15 22:10:52 -0700178uint64_t ThreadCpuNanoTime() {
179#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700180 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700181 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
182 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
183#else
184 UNIMPLEMENTED(WARNING);
185 return -1;
186#endif
187}
188
Elliott Hughes5174fe62011-08-23 15:12:35 -0700189std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700190 if (java_descriptor == NULL) {
191 return "null";
192 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700193 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
194}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700195
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800196std::string PrettyDescriptor(const Class* klass) {
197 if (klass == NULL) {
198 return "null";
199 }
200 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800201}
202
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700203std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700204 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700205 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700206 size_t dim = 0;
207 while (*c == '[') {
208 dim++;
209 c++;
210 }
211
212 // Reference or primitive?
213 if (*c == 'L') {
214 // "[[La/b/C;" -> "a.b.C[][]".
215 c++; // Skip the 'L'.
216 } else {
217 // "[[B" -> "byte[][]".
218 // To make life easier, we make primitives look like unqualified
219 // reference types.
220 switch (*c) {
221 case 'B': c = "byte;"; break;
222 case 'C': c = "char;"; break;
223 case 'D': c = "double;"; break;
224 case 'F': c = "float;"; break;
225 case 'I': c = "int;"; break;
226 case 'J': c = "long;"; break;
227 case 'S': c = "short;"; break;
228 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700229 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700230 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700231 }
232 }
233
234 // At this point, 'c' is a string of the form "fully/qualified/Type;"
235 // or "primitive;". Rewrite the type with '.' instead of '/':
236 std::string result;
237 const char* p = c;
238 while (*p != ';') {
239 char ch = *p++;
240 if (ch == '/') {
241 ch = '.';
242 }
243 result.push_back(ch);
244 }
245 // ...and replace the semicolon with 'dim' "[]" pairs:
246 while (dim--) {
247 result += "[]";
248 }
249 return result;
250}
251
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700252std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800253 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700254 return PrettyDescriptor(descriptor_string);
255}
256
Elliott Hughes54e7df12011-09-16 11:47:04 -0700257std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700258 if (f == NULL) {
259 return "null";
260 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800261 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700262 std::string result;
263 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800264 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700265 result += ' ';
266 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800267 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700268 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800269 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700270 return result;
271}
272
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700273std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
274 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
275 std::string result;
276 if (with_type) {
277 result += dex_file.GetFieldTypeDescriptor(field_id);
278 result += ' ';
279 }
280 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
281 result += '.';
282 result += dex_file.GetFieldName(field_id);
283 return result;
284}
285
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700286std::string PrettyArguments(const char* signature) {
287 std::string result;
288 result += '(';
289 CHECK_EQ(*signature, '(');
290 ++signature; // Skip the '('.
291 while (*signature != ')') {
292 size_t argument_length = 0;
293 while (signature[argument_length] == '[') {
294 ++argument_length;
295 }
296 if (signature[argument_length] == 'L') {
297 argument_length = (strchr(signature, ';') - signature + 1);
298 } else {
299 ++argument_length;
300 }
301 std::string argument_descriptor(signature, argument_length);
302 result += PrettyDescriptor(argument_descriptor);
303 if (signature[argument_length] != ')') {
304 result += ", ";
305 }
306 signature += argument_length;
307 }
308 CHECK_EQ(*signature, ')');
309 ++signature; // Skip the ')'.
310 result += ')';
311 return result;
312}
313
314std::string PrettyReturnType(const char* signature) {
315 const char* return_type = strchr(signature, ')');
316 CHECK(return_type != NULL);
317 ++return_type; // Skip ')'.
318 return PrettyDescriptor(return_type);
319}
320
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700321std::string PrettyMethod(const Method* m, bool with_signature) {
322 if (m == NULL) {
323 return "null";
324 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800325 MethodHelper mh(m);
326 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700327 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800328 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700329 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700330 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700331 if (signature == "<no signature>") {
332 return result + signature;
333 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700334 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700335 }
336 return result;
337}
338
Ian Rogers0571d352011-11-03 19:51:38 -0700339std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
340 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
341 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
342 result += '.';
343 result += dex_file.GetMethodName(method_id);
344 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700345 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700346 if (signature == "<no signature>") {
347 return result + signature;
348 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700349 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700350 }
351 return result;
352}
353
Elliott Hughes54e7df12011-09-16 11:47:04 -0700354std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700355 if (obj == NULL) {
356 return "null";
357 }
358 if (obj->GetClass() == NULL) {
359 return "(raw)";
360 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800361 ClassHelper kh(obj->GetClass());
362 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700363 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800364 kh.ChangeClass(obj->AsClass());
365 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700366 }
367 return result;
368}
369
Elliott Hughes54e7df12011-09-16 11:47:04 -0700370std::string PrettyClass(const Class* c) {
371 if (c == NULL) {
372 return "null";
373 }
374 std::string result;
375 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800376 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700377 result += ">";
378 return result;
379}
380
Ian Rogersd81871c2011-10-03 13:57:23 -0700381std::string PrettyClassAndClassLoader(const Class* c) {
382 if (c == NULL) {
383 return "null";
384 }
385 std::string result;
386 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800387 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700388 result += ",";
389 result += PrettyTypeOf(c->GetClassLoader());
390 // TODO: add an identifying hash value for the loader
391 result += ">";
392 return result;
393}
394
Elliott Hughesc967f782012-04-16 10:23:15 -0700395std::string PrettySize(size_t byte_count) {
396 // The byte thresholds at which we display amounts. A byte count is displayed
397 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
398 static const size_t kUnitThresholds[] = {
399 0, // B up to...
400 3*1024, // KB up to...
401 2*1024*1024, // MB up to...
402 1024*1024*1024 // GB from here.
403 };
404 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
405 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
406
407 int i = arraysize(kUnitThresholds);
408 while (--i > 0) {
409 if (byte_count >= kUnitThresholds[i]) {
410 break;
411 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800412 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700413
414 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800415}
416
417std::string PrettyDuration(uint64_t nano_duration) {
418 if (nano_duration == 0) {
419 return "0";
420 } else {
421 const uint64_t one_sec = 1000 * 1000 * 1000;
422 const uint64_t one_ms = 1000 * 1000;
423 const uint64_t one_us = 1000;
424 const char* unit;
425 uint64_t divisor;
426 uint32_t zero_fill;
427 if (nano_duration >= one_sec) {
428 unit = "s";
429 divisor = one_sec;
430 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700431 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800432 unit = "ms";
433 divisor = one_ms;
434 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700435 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800436 unit = "us";
437 divisor = one_us;
438 zero_fill = 3;
439 } else {
440 unit = "ns";
441 divisor = 1;
442 zero_fill = 0;
443 }
444 uint64_t whole_part = nano_duration / divisor;
445 uint64_t fractional_part = nano_duration % divisor;
446 if (fractional_part == 0) {
447 return StringPrintf("%llu%s", whole_part, unit);
448 } else {
449 while ((fractional_part % 1000) == 0) {
450 zero_fill -= 3;
451 fractional_part /= 1000;
452 }
453 if (zero_fill == 3) {
454 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
455 } else if (zero_fill == 6) {
456 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
457 } else {
458 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
459 }
460 }
461 }
462}
463
Elliott Hughes82914b62012-04-09 15:56:29 -0700464std::string PrintableString(const std::string& utf) {
465 std::string result;
466 result += '"';
467 const char* p = utf.c_str();
468 size_t char_count = CountModifiedUtf8Chars(p);
469 for (size_t i = 0; i < char_count; ++i) {
470 uint16_t ch = GetUtf16FromUtf8(&p);
471 if (ch == '\\') {
472 result += "\\\\";
473 } else if (ch == '\n') {
474 result += "\\n";
475 } else if (ch == '\r') {
476 result += "\\r";
477 } else if (ch == '\t') {
478 result += "\\t";
479 } else if (NeedsEscaping(ch)) {
480 StringAppendF(&result, "\\u%04x", ch);
481 } else {
482 result += ch;
483 }
484 }
485 result += '"';
486 return result;
487}
488
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800489// 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 -0700490std::string MangleForJni(const std::string& s) {
491 std::string result;
492 size_t char_count = CountModifiedUtf8Chars(s.c_str());
493 const char* cp = &s[0];
494 for (size_t i = 0; i < char_count; ++i) {
495 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800496 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
497 result.push_back(ch);
498 } else if (ch == '.' || ch == '/') {
499 result += "_";
500 } else if (ch == '_') {
501 result += "_1";
502 } else if (ch == ';') {
503 result += "_2";
504 } else if (ch == '[') {
505 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700506 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800507 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700508 }
509 }
510 return result;
511}
512
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700513std::string DotToDescriptor(const char* class_name) {
514 std::string descriptor(class_name);
515 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
516 if (descriptor.length() > 0 && descriptor[0] != '[') {
517 descriptor = "L" + descriptor + ";";
518 }
519 return descriptor;
520}
521
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800522std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800523 size_t length = strlen(descriptor);
524 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
525 std::string result(descriptor + 1, length - 2);
526 std::replace(result.begin(), result.end(), '/', '.');
527 return result;
528 }
529 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800530}
531
532std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800533 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800534 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
535 std::string result(descriptor + 1, length - 2);
536 return result;
537 }
538 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700539}
540
Elliott Hughes79082e32011-08-25 12:07:32 -0700541std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800542 MethodHelper mh(m);
543 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700544 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700545 CHECK_EQ(class_name[0], 'L') << class_name;
546 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700547 class_name.erase(0, 1);
548 class_name.erase(class_name.size() - 1, 1);
549
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800550 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700551
552 std::string short_name;
553 short_name += "Java_";
554 short_name += MangleForJni(class_name);
555 short_name += "_";
556 short_name += MangleForJni(method_name);
557 return short_name;
558}
559
560std::string JniLongName(const Method* m) {
561 std::string long_name;
562 long_name += JniShortName(m);
563 long_name += "__";
564
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800565 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700566 signature.erase(0, 1);
567 signature.erase(signature.begin() + signature.find(')'), signature.end());
568
569 long_name += MangleForJni(signature);
570
571 return long_name;
572}
573
jeffhao10037c82012-01-23 15:06:23 -0800574// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700575uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
576 0x00000000, // 00..1f low control characters; nothing valid
577 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
578 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
579 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
580};
581
jeffhao10037c82012-01-23 15:06:23 -0800582// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
583bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700584 /*
585 * It's a multibyte encoded character. Decode it and analyze. We
586 * accept anything that isn't (a) an improperly encoded low value,
587 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
588 * control character, or (e) a high space, layout, or special
589 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
590 * U+fff0..U+ffff). This is all specified in the dex format
591 * document.
592 */
593
594 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
595
596 // Perform follow-up tests based on the high 8 bits.
597 switch (utf16 >> 8) {
598 case 0x00:
599 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
600 return (utf16 > 0x00a0);
601 case 0xd8:
602 case 0xd9:
603 case 0xda:
604 case 0xdb:
605 // It's a leading surrogate. Check to see that a trailing
606 // surrogate follows.
607 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
608 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
609 case 0xdc:
610 case 0xdd:
611 case 0xde:
612 case 0xdf:
613 // It's a trailing surrogate, which is not valid at this point.
614 return false;
615 case 0x20:
616 case 0xff:
617 // It's in the range that has spaces, controls, and specials.
618 switch (utf16 & 0xfff8) {
619 case 0x2000:
620 case 0x2008:
621 case 0x2028:
622 case 0xfff0:
623 case 0xfff8:
624 return false;
625 }
626 break;
627 }
628 return true;
629}
630
631/* Return whether the pointed-at modified-UTF-8 encoded character is
632 * valid as part of a member name, updating the pointer to point past
633 * the consumed character. This will consume two encoded UTF-16 code
634 * points if the character is encoded as a surrogate pair. Also, if
635 * this function returns false, then the given pointer may only have
636 * been partially advanced.
637 */
jeffhao10037c82012-01-23 15:06:23 -0800638bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700639 uint8_t c = (uint8_t) **pUtf8Ptr;
640 if (c <= 0x7f) {
641 // It's low-ascii, so check the table.
642 uint32_t wordIdx = c >> 5;
643 uint32_t bitIdx = c & 0x1f;
644 (*pUtf8Ptr)++;
645 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
646 }
647
648 // It's a multibyte encoded character. Call a non-inline function
649 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800650 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
651}
652
653bool IsValidMemberName(const char* s) {
654 bool angle_name = false;
655
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700656 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800657 case '\0':
658 // The empty string is not a valid name.
659 return false;
660 case '<':
661 angle_name = true;
662 s++;
663 break;
664 }
665
666 while (true) {
667 switch (*s) {
668 case '\0':
669 return !angle_name;
670 case '>':
671 return angle_name && s[1] == '\0';
672 }
673
674 if (!IsValidPartOfMemberNameUtf8(&s)) {
675 return false;
676 }
677 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700678}
679
Elliott Hughes906e6852011-10-28 14:52:10 -0700680enum ClassNameType { kName, kDescriptor };
681bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700682 int arrayCount = 0;
683 while (*s == '[') {
684 arrayCount++;
685 s++;
686 }
687
688 if (arrayCount > 255) {
689 // Arrays may have no more than 255 dimensions.
690 return false;
691 }
692
693 if (arrayCount != 0) {
694 /*
695 * If we're looking at an array of some sort, then it doesn't
696 * matter if what is being asked for is a class name; the
697 * format looks the same as a type descriptor in that case, so
698 * treat it as such.
699 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700700 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700701 }
702
Elliott Hughes906e6852011-10-28 14:52:10 -0700703 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700704 /*
705 * We are looking for a descriptor. Either validate it as a
706 * single-character primitive type, or continue on to check the
707 * embedded class name (bracketed by "L" and ";").
708 */
709 switch (*(s++)) {
710 case 'B':
711 case 'C':
712 case 'D':
713 case 'F':
714 case 'I':
715 case 'J':
716 case 'S':
717 case 'Z':
718 // These are all single-character descriptors for primitive types.
719 return (*s == '\0');
720 case 'V':
721 // Non-array void is valid, but you can't have an array of void.
722 return (arrayCount == 0) && (*s == '\0');
723 case 'L':
724 // Class name: Break out and continue below.
725 break;
726 default:
727 // Oddball descriptor character.
728 return false;
729 }
730 }
731
732 /*
733 * We just consumed the 'L' that introduces a class name as part
734 * of a type descriptor, or we are looking for an unadorned class
735 * name.
736 */
737
738 bool sepOrFirst = true; // first character or just encountered a separator.
739 for (;;) {
740 uint8_t c = (uint8_t) *s;
741 switch (c) {
742 case '\0':
743 /*
744 * Premature end for a type descriptor, but valid for
745 * a class name as long as we haven't encountered an
746 * empty component (including the degenerate case of
747 * the empty string "").
748 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700749 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700750 case ';':
751 /*
752 * Invalid character for a class name, but the
753 * legitimate end of a type descriptor. In the latter
754 * case, make sure that this is the end of the string
755 * and that it doesn't end with an empty component
756 * (including the degenerate case of "L;").
757 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700758 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700759 case '/':
760 case '.':
761 if (c != separator) {
762 // The wrong separator character.
763 return false;
764 }
765 if (sepOrFirst) {
766 // Separator at start or two separators in a row.
767 return false;
768 }
769 sepOrFirst = true;
770 s++;
771 break;
772 default:
jeffhao10037c82012-01-23 15:06:23 -0800773 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700774 return false;
775 }
776 sepOrFirst = false;
777 break;
778 }
779 }
780}
781
Elliott Hughes906e6852011-10-28 14:52:10 -0700782bool IsValidBinaryClassName(const char* s) {
783 return IsValidClassName(s, kName, '.');
784}
785
786bool IsValidJniClassName(const char* s) {
787 return IsValidClassName(s, kName, '/');
788}
789
790bool IsValidDescriptor(const char* s) {
791 return IsValidClassName(s, kDescriptor, '/');
792}
793
Elliott Hughes48436bb2012-02-07 15:23:28 -0800794void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700795 const char* p = s.data();
796 const char* end = p + s.size();
797 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800798 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700799 ++p;
800 } else {
801 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800802 while (++p != end && *p != separator) {
803 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700804 }
805 result.push_back(std::string(start, p - start));
806 }
807 }
808}
809
Elliott Hughes48436bb2012-02-07 15:23:28 -0800810template <typename StringT>
811std::string Join(std::vector<StringT>& strings, char separator) {
812 if (strings.empty()) {
813 return "";
814 }
815
816 std::string result(strings[0]);
817 for (size_t i = 1; i < strings.size(); ++i) {
818 result += separator;
819 result += strings[i];
820 }
821 return result;
822}
823
824// Explicit instantiations.
825template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
826template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
827template std::string Join<char*>(std::vector<char*>& strings, char separator);
828
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800829bool StartsWith(const std::string& s, const char* prefix) {
830 return s.compare(0, strlen(prefix), prefix) == 0;
831}
832
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700833bool EndsWith(const std::string& s, const char* suffix) {
834 size_t suffix_length = strlen(suffix);
835 size_t string_length = s.size();
836 if (suffix_length > string_length) {
837 return false;
838 }
839 size_t offset = string_length - suffix_length;
840 return s.compare(offset, suffix_length, suffix) == 0;
841}
842
Elliott Hughes22869a92012-03-27 14:08:24 -0700843void SetThreadName(const char* thread_name) {
844 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800845
Elliott Hughesdcc24742011-09-07 14:02:44 -0700846 int hasAt = 0;
847 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700848 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700849 while (*s) {
850 if (*s == '.') {
851 hasDot = 1;
852 } else if (*s == '@') {
853 hasAt = 1;
854 }
855 s++;
856 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700857 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700858 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700859 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700860 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700861 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700862 }
863#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700864 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700865 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
866 strncpy(buf, s, sizeof(buf)-1);
867 buf[sizeof(buf)-1] = '\0';
868 errno = pthread_setname_np(pthread_self(), buf);
869 if (errno != 0) {
870 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
871 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700872#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700873 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700874#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700875 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700876#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700877 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700878#endif
879}
880
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700881void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
882 utime = stime = task_cpu = 0;
883 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700884 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700885 return;
886 }
887 // Skip the command, which may contain spaces.
888 stats = stats.substr(stats.find(')') + 2);
889 // Extract the three fields we care about.
890 std::vector<std::string> fields;
891 Split(stats, ' ', fields);
892 utime = strtoull(fields[11].c_str(), NULL, 10);
893 stime = strtoull(fields[12].c_str(), NULL, 10);
894 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
895}
896
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700897std::string GetSchedulerGroupName(pid_t tid) {
898 // /proc/<pid>/cgroup looks like this:
899 // 2:devices:/
900 // 1:cpuacct,cpu:/
901 // We want the third field from the line whose second field contains the "cpu" token.
902 std::string cgroup_file;
903 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
904 return "";
905 }
906 std::vector<std::string> cgroup_lines;
907 Split(cgroup_file, '\n', cgroup_lines);
908 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
909 std::vector<std::string> cgroup_fields;
910 Split(cgroup_lines[i], ':', cgroup_fields);
911 std::vector<std::string> cgroups;
912 Split(cgroup_fields[1], ',', cgroups);
913 for (size_t i = 0; i < cgroups.size(); ++i) {
914 if (cgroups[i] == "cpu") {
915 return cgroup_fields[2].substr(1); // Skip the leading slash.
916 }
917 }
918 }
919 return "";
920}
921
Elliott Hughes46e251b2012-05-22 15:10:45 -0700922static const char* CleanMapName(const backtrace_symbol_t* symbol) {
923 const char* map_name = symbol->map_name;
924 if (map_name == NULL) {
925 map_name = "???";
926 }
927 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
928 // into "libartd.so".
929 const char* last_slash = strrchr(map_name, '/');
930 if (last_slash != NULL) {
931 map_name = last_slash + 1;
932 }
933 return map_name;
934}
935
936static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
937 std::string& symbol_name, uint32_t& pc_offset) {
938 symbol_table_t* symbol_table = NULL;
939 if (symbol->map_name != NULL) {
940 symbol_table = load_symbol_table(symbol->map_name);
941 }
942 const symbol_t* elf_symbol = NULL;
943 if (symbol_table != NULL) {
944 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
945 if (elf_symbol == NULL) {
946 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
947 }
948 }
949 if (elf_symbol != NULL) {
950 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
951 if (demangled_symbol_name != NULL) {
952 symbol_name = demangled_symbol_name;
953 } else {
954 symbol_name = elf_symbol->name;
955 }
956 pc_offset = frame->absolute_pc - elf_symbol->start;
957 } else {
958 symbol_name = "???";
959 }
960 free_symbol_table(symbol_table);
961}
962
963void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
964 const size_t MAX_DEPTH = 32;
965 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
966 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), 0, MAX_DEPTH);
967 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -0700968 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -0700969 return;
970 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -0700971 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -0700972 return;
973 }
974
975 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
976 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
977
978 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
979 const backtrace_frame_t* frame = &frames[i];
980 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
981
982 // We produce output like this:
983 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
984
985 std::string symbol_name;
986 uint32_t pc_offset = 0;
987 if (symbol->demangled_name != NULL) {
988 symbol_name = symbol->demangled_name;
989 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
990 } else if (symbol->symbol_name != NULL) {
991 symbol_name = symbol->symbol_name;
992 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
993 } else {
994 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
995 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
996 }
997
998 os << prefix;
999 if (include_count) {
1000 os << StringPrintf("#%02zd ", i);
1001 }
1002 os << symbol_name;
1003 if (pc_offset != 0) {
1004 os << "+" << pc_offset;
1005 }
1006 os << StringPrintf(" [%p] (%s)\n",
1007 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1008 }
1009
1010 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1011}
1012
Elliott Hughes058a6de2012-05-24 19:13:02 -07001013#if defined(__APPLE__)
1014
1015// TODO: is there any way to get the kernel stack on Mac OS?
1016void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1017
1018#else
1019
Elliott Hughes46e251b2012-05-22 15:10:45 -07001020void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001021 if (tid == GetTid()) {
1022 // There's no point showing that we're reading our stack out of /proc!
1023 return;
1024 }
1025
Elliott Hughes46e251b2012-05-22 15:10:45 -07001026 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1027 std::string kernel_stack;
1028 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001029 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001030 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001031 }
1032
1033 std::vector<std::string> kernel_stack_frames;
1034 Split(kernel_stack, '\n', kernel_stack_frames);
1035 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1036 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1037 kernel_stack_frames.pop_back();
1038 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1039 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1040 const char* text = kernel_stack_frames[i].c_str();
1041 const char* close_bracket = strchr(text, ']');
1042 if (close_bracket != NULL) {
1043 text = close_bracket + 2;
1044 }
1045 os << prefix;
1046 if (include_count) {
1047 os << StringPrintf("#%02zd ", i);
1048 }
1049 os << text << "\n";
1050 }
1051}
1052
1053#endif
1054
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001055const char* GetAndroidRoot() {
1056 const char* android_root = getenv("ANDROID_ROOT");
1057 if (android_root == NULL) {
1058 if (OS::DirectoryExists("/system")) {
1059 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001060 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001061 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1062 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001063 }
1064 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001065 if (!OS::DirectoryExists(android_root)) {
1066 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001067 return "";
1068 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001069 return android_root;
1070}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001071
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001072const char* GetAndroidData() {
1073 const char* android_data = getenv("ANDROID_DATA");
1074 if (android_data == NULL) {
1075 if (OS::DirectoryExists("/data")) {
1076 android_data = "/data";
1077 } else {
1078 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1079 return "";
1080 }
1081 }
1082 if (!OS::DirectoryExists(android_data)) {
1083 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1084 return "";
1085 }
1086 return android_data;
1087}
1088
Shih-wei Liao795e3302012-04-21 00:20:57 -07001089std::string GetArtCacheOrDie(const char* android_data) {
1090 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001091
1092 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001093 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001094 int result = mkdir(art_cache.c_str(), 0700);
1095 if (result != 0) {
1096 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1097 return "";
1098 }
1099 } else {
1100 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1101 return "";
1102 }
1103 }
1104 return art_cache;
1105}
1106
jeffhao262bf462011-10-20 18:36:32 -07001107std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001108 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001109 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001110 std::string cache_file(location, 1); // skip leading slash
1111 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1112 return art_cache + "/" + cache_file;
1113}
1114
jeffhao262bf462011-10-20 18:36:32 -07001115bool IsValidZipFilename(const std::string& filename) {
1116 if (filename.size() < 4) {
1117 return false;
1118 }
1119 std::string suffix(filename.substr(filename.size() - 4));
1120 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1121}
1122
1123bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001124 return EndsWith(filename, ".dex");
1125}
1126
1127bool IsValidOatFilename(const std::string& filename) {
1128 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001129}
1130
Elliott Hughes42ee1422011-09-06 12:33:32 -07001131} // namespace art