blob: 7dea1108ffb1ddee9fd5ea30f893f4ea2bf94701 [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 Hughes46e251b2012-05-22 15:10:45 -070044
45#include <cxxabi.h> // For DumpNativeStack.
46#include <execinfo.h> // For DumpNativeStack.
47
Elliott Hughes4ae722a2012-03-13 11:08:51 -070048#endif
49
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080050#if defined(__linux__)
Elliott Hughes46e251b2012-05-22 15:10:45 -070051#include <corkscrew/backtrace.h> // For DumpNativeStack.
52#include <corkscrew/demangle.h> // For DumpNativeStack.
53
Elliott Hughese1aee692012-01-17 16:40:10 -080054#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080055#endif
56
Elliott Hughes11e45072011-08-16 17:40:46 -070057namespace art {
58
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080059pid_t GetTid() {
Elliott Hughes5d6d5dc2012-03-29 11:59:27 -070060#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
61 // Darwin has a gettid(2), but it does something completely unrelated to tids.
62 // 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 -070063 // pthreads implementation uses.
64 return syscall(SYS_thread_selfid);
Elliott Hughes5d6d5dc2012-03-29 11:59:27 -070065#elif defined(__APPLE__)
66 // On Mac OS 10.5 (which the build servers are still running) there was nothing usable.
Elliott Hughesd23f5202012-03-30 19:50:04 -070067 // We know we build 32-bit binaries and that the pthread_t is a pointer that uniquely identifies
68 // the calling thread.
69 return reinterpret_cast<pid_t>(pthread_self());
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080070#else
71 // Neither bionic nor glibc exposes gettid(2).
72 return syscall(__NR_gettid);
73#endif
74}
75
Elliott Hughese1884192012-04-23 12:38:15 -070076void GetThreadStack(void*& stack_base, size_t& stack_size) {
77#if defined(__APPLE__)
78 stack_size = pthread_get_stacksize_np(pthread_self());
79 void* stack_addr = pthread_get_stackaddr_np(pthread_self());
80
81 // Check whether stack_addr is the base or end of the stack.
82 // (On Mac OS 10.7, it's the end.)
83 int stack_variable;
84 if (stack_addr > &stack_variable) {
85 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
86 } else {
87 stack_base = stack_addr;
88 }
89#else
90 pthread_attr_t attributes;
91 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
92 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
93 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
94#endif
95}
96
Elliott Hughesd92bec42011-09-02 17:04:36 -070097bool ReadFileToString(const std::string& file_name, std::string* result) {
98 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
99 if (file.get() == NULL) {
100 return false;
101 }
buzbeec143c552011-08-20 17:38:58 -0700102
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700103 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700104 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700105 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700106 if (n == -1) {
107 return false;
buzbeec143c552011-08-20 17:38:58 -0700108 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700109 if (n == 0) {
110 return true;
111 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700112 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700113 }
buzbeec143c552011-08-20 17:38:58 -0700114}
115
Elliott Hughese27955c2011-08-26 15:21:24 -0700116std::string GetIsoDate() {
117 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700118 tm tmbuf;
119 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700120 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
121 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
122 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
123}
124
Elliott Hughes7162ad92011-10-27 14:08:42 -0700125uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700127 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700128 clock_gettime(CLOCK_MONOTONIC, &now);
129 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800130#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700131 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800132 gettimeofday(&now, NULL);
133 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
134#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135}
136
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800137uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700139 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800140 clock_gettime(CLOCK_MONOTONIC, &now);
141 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700143 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800144 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700145 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800146#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147}
148
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700149uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700151 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700152 clock_gettime(CLOCK_MONOTONIC, &now);
153 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700155 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156 gettimeofday(&now, NULL);
157 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
158#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159}
160
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800161uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700163 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800164 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
165 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800166#else
167 UNIMPLEMENTED(WARNING);
168 return -1;
169#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800170}
171
Elliott Hughes0512f022012-03-15 22:10:52 -0700172uint64_t ThreadCpuNanoTime() {
173#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700174 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700175 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
176 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
177#else
178 UNIMPLEMENTED(WARNING);
179 return -1;
180#endif
181}
182
Elliott Hughes5174fe62011-08-23 15:12:35 -0700183std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700184 if (java_descriptor == NULL) {
185 return "null";
186 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700187 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
188}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700189
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800190std::string PrettyDescriptor(const Class* klass) {
191 if (klass == NULL) {
192 return "null";
193 }
194 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800195}
196
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700197std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700198 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700199 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700200 size_t dim = 0;
201 while (*c == '[') {
202 dim++;
203 c++;
204 }
205
206 // Reference or primitive?
207 if (*c == 'L') {
208 // "[[La/b/C;" -> "a.b.C[][]".
209 c++; // Skip the 'L'.
210 } else {
211 // "[[B" -> "byte[][]".
212 // To make life easier, we make primitives look like unqualified
213 // reference types.
214 switch (*c) {
215 case 'B': c = "byte;"; break;
216 case 'C': c = "char;"; break;
217 case 'D': c = "double;"; break;
218 case 'F': c = "float;"; break;
219 case 'I': c = "int;"; break;
220 case 'J': c = "long;"; break;
221 case 'S': c = "short;"; break;
222 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700223 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700224 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700225 }
226 }
227
228 // At this point, 'c' is a string of the form "fully/qualified/Type;"
229 // or "primitive;". Rewrite the type with '.' instead of '/':
230 std::string result;
231 const char* p = c;
232 while (*p != ';') {
233 char ch = *p++;
234 if (ch == '/') {
235 ch = '.';
236 }
237 result.push_back(ch);
238 }
239 // ...and replace the semicolon with 'dim' "[]" pairs:
240 while (dim--) {
241 result += "[]";
242 }
243 return result;
244}
245
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700246std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800247 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700248 return PrettyDescriptor(descriptor_string);
249}
250
Elliott Hughes54e7df12011-09-16 11:47:04 -0700251std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700252 if (f == NULL) {
253 return "null";
254 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800255 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700256 std::string result;
257 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800258 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700259 result += ' ';
260 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800261 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700262 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800263 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700264 return result;
265}
266
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700267std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
268 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
269 std::string result;
270 if (with_type) {
271 result += dex_file.GetFieldTypeDescriptor(field_id);
272 result += ' ';
273 }
274 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
275 result += '.';
276 result += dex_file.GetFieldName(field_id);
277 return result;
278}
279
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700280std::string PrettyArguments(const char* signature) {
281 std::string result;
282 result += '(';
283 CHECK_EQ(*signature, '(');
284 ++signature; // Skip the '('.
285 while (*signature != ')') {
286 size_t argument_length = 0;
287 while (signature[argument_length] == '[') {
288 ++argument_length;
289 }
290 if (signature[argument_length] == 'L') {
291 argument_length = (strchr(signature, ';') - signature + 1);
292 } else {
293 ++argument_length;
294 }
295 std::string argument_descriptor(signature, argument_length);
296 result += PrettyDescriptor(argument_descriptor);
297 if (signature[argument_length] != ')') {
298 result += ", ";
299 }
300 signature += argument_length;
301 }
302 CHECK_EQ(*signature, ')');
303 ++signature; // Skip the ')'.
304 result += ')';
305 return result;
306}
307
308std::string PrettyReturnType(const char* signature) {
309 const char* return_type = strchr(signature, ')');
310 CHECK(return_type != NULL);
311 ++return_type; // Skip ')'.
312 return PrettyDescriptor(return_type);
313}
314
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700315std::string PrettyMethod(const Method* m, bool with_signature) {
316 if (m == NULL) {
317 return "null";
318 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800319 MethodHelper mh(m);
320 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700321 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800322 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700323 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700324 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700325 if (signature == "<no signature>") {
326 return result + signature;
327 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700328 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700329 }
330 return result;
331}
332
Ian Rogers0571d352011-11-03 19:51:38 -0700333std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
334 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
335 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
336 result += '.';
337 result += dex_file.GetMethodName(method_id);
338 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700339 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700340 if (signature == "<no signature>") {
341 return result + signature;
342 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700343 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700344 }
345 return result;
346}
347
Elliott Hughes54e7df12011-09-16 11:47:04 -0700348std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700349 if (obj == NULL) {
350 return "null";
351 }
352 if (obj->GetClass() == NULL) {
353 return "(raw)";
354 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800355 ClassHelper kh(obj->GetClass());
356 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700357 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800358 kh.ChangeClass(obj->AsClass());
359 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700360 }
361 return result;
362}
363
Elliott Hughes54e7df12011-09-16 11:47:04 -0700364std::string PrettyClass(const Class* c) {
365 if (c == NULL) {
366 return "null";
367 }
368 std::string result;
369 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800370 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700371 result += ">";
372 return result;
373}
374
Ian Rogersd81871c2011-10-03 13:57:23 -0700375std::string PrettyClassAndClassLoader(const Class* c) {
376 if (c == NULL) {
377 return "null";
378 }
379 std::string result;
380 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800381 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700382 result += ",";
383 result += PrettyTypeOf(c->GetClassLoader());
384 // TODO: add an identifying hash value for the loader
385 result += ">";
386 return result;
387}
388
Elliott Hughesc967f782012-04-16 10:23:15 -0700389std::string PrettySize(size_t byte_count) {
390 // The byte thresholds at which we display amounts. A byte count is displayed
391 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
392 static const size_t kUnitThresholds[] = {
393 0, // B up to...
394 3*1024, // KB up to...
395 2*1024*1024, // MB up to...
396 1024*1024*1024 // GB from here.
397 };
398 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
399 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
400
401 int i = arraysize(kUnitThresholds);
402 while (--i > 0) {
403 if (byte_count >= kUnitThresholds[i]) {
404 break;
405 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800406 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700407
408 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800409}
410
411std::string PrettyDuration(uint64_t nano_duration) {
412 if (nano_duration == 0) {
413 return "0";
414 } else {
415 const uint64_t one_sec = 1000 * 1000 * 1000;
416 const uint64_t one_ms = 1000 * 1000;
417 const uint64_t one_us = 1000;
418 const char* unit;
419 uint64_t divisor;
420 uint32_t zero_fill;
421 if (nano_duration >= one_sec) {
422 unit = "s";
423 divisor = one_sec;
424 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700425 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800426 unit = "ms";
427 divisor = one_ms;
428 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700429 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800430 unit = "us";
431 divisor = one_us;
432 zero_fill = 3;
433 } else {
434 unit = "ns";
435 divisor = 1;
436 zero_fill = 0;
437 }
438 uint64_t whole_part = nano_duration / divisor;
439 uint64_t fractional_part = nano_duration % divisor;
440 if (fractional_part == 0) {
441 return StringPrintf("%llu%s", whole_part, unit);
442 } else {
443 while ((fractional_part % 1000) == 0) {
444 zero_fill -= 3;
445 fractional_part /= 1000;
446 }
447 if (zero_fill == 3) {
448 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
449 } else if (zero_fill == 6) {
450 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
451 } else {
452 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
453 }
454 }
455 }
456}
457
Elliott Hughes82914b62012-04-09 15:56:29 -0700458std::string PrintableString(const std::string& utf) {
459 std::string result;
460 result += '"';
461 const char* p = utf.c_str();
462 size_t char_count = CountModifiedUtf8Chars(p);
463 for (size_t i = 0; i < char_count; ++i) {
464 uint16_t ch = GetUtf16FromUtf8(&p);
465 if (ch == '\\') {
466 result += "\\\\";
467 } else if (ch == '\n') {
468 result += "\\n";
469 } else if (ch == '\r') {
470 result += "\\r";
471 } else if (ch == '\t') {
472 result += "\\t";
473 } else if (NeedsEscaping(ch)) {
474 StringAppendF(&result, "\\u%04x", ch);
475 } else {
476 result += ch;
477 }
478 }
479 result += '"';
480 return result;
481}
482
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800483// 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 -0700484std::string MangleForJni(const std::string& s) {
485 std::string result;
486 size_t char_count = CountModifiedUtf8Chars(s.c_str());
487 const char* cp = &s[0];
488 for (size_t i = 0; i < char_count; ++i) {
489 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800490 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
491 result.push_back(ch);
492 } else if (ch == '.' || ch == '/') {
493 result += "_";
494 } else if (ch == '_') {
495 result += "_1";
496 } else if (ch == ';') {
497 result += "_2";
498 } else if (ch == '[') {
499 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700500 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800501 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700502 }
503 }
504 return result;
505}
506
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700507std::string DotToDescriptor(const char* class_name) {
508 std::string descriptor(class_name);
509 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
510 if (descriptor.length() > 0 && descriptor[0] != '[') {
511 descriptor = "L" + descriptor + ";";
512 }
513 return descriptor;
514}
515
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800516std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800517 size_t length = strlen(descriptor);
518 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
519 std::string result(descriptor + 1, length - 2);
520 std::replace(result.begin(), result.end(), '/', '.');
521 return result;
522 }
523 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800524}
525
526std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800527 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800528 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
529 std::string result(descriptor + 1, length - 2);
530 return result;
531 }
532 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700533}
534
Elliott Hughes79082e32011-08-25 12:07:32 -0700535std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800536 MethodHelper mh(m);
537 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700538 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700539 CHECK_EQ(class_name[0], 'L') << class_name;
540 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700541 class_name.erase(0, 1);
542 class_name.erase(class_name.size() - 1, 1);
543
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800544 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700545
546 std::string short_name;
547 short_name += "Java_";
548 short_name += MangleForJni(class_name);
549 short_name += "_";
550 short_name += MangleForJni(method_name);
551 return short_name;
552}
553
554std::string JniLongName(const Method* m) {
555 std::string long_name;
556 long_name += JniShortName(m);
557 long_name += "__";
558
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800559 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700560 signature.erase(0, 1);
561 signature.erase(signature.begin() + signature.find(')'), signature.end());
562
563 long_name += MangleForJni(signature);
564
565 return long_name;
566}
567
jeffhao10037c82012-01-23 15:06:23 -0800568// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700569uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
570 0x00000000, // 00..1f low control characters; nothing valid
571 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
572 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
573 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
574};
575
jeffhao10037c82012-01-23 15:06:23 -0800576// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
577bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700578 /*
579 * It's a multibyte encoded character. Decode it and analyze. We
580 * accept anything that isn't (a) an improperly encoded low value,
581 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
582 * control character, or (e) a high space, layout, or special
583 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
584 * U+fff0..U+ffff). This is all specified in the dex format
585 * document.
586 */
587
588 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
589
590 // Perform follow-up tests based on the high 8 bits.
591 switch (utf16 >> 8) {
592 case 0x00:
593 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
594 return (utf16 > 0x00a0);
595 case 0xd8:
596 case 0xd9:
597 case 0xda:
598 case 0xdb:
599 // It's a leading surrogate. Check to see that a trailing
600 // surrogate follows.
601 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
602 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
603 case 0xdc:
604 case 0xdd:
605 case 0xde:
606 case 0xdf:
607 // It's a trailing surrogate, which is not valid at this point.
608 return false;
609 case 0x20:
610 case 0xff:
611 // It's in the range that has spaces, controls, and specials.
612 switch (utf16 & 0xfff8) {
613 case 0x2000:
614 case 0x2008:
615 case 0x2028:
616 case 0xfff0:
617 case 0xfff8:
618 return false;
619 }
620 break;
621 }
622 return true;
623}
624
625/* Return whether the pointed-at modified-UTF-8 encoded character is
626 * valid as part of a member name, updating the pointer to point past
627 * the consumed character. This will consume two encoded UTF-16 code
628 * points if the character is encoded as a surrogate pair. Also, if
629 * this function returns false, then the given pointer may only have
630 * been partially advanced.
631 */
jeffhao10037c82012-01-23 15:06:23 -0800632bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700633 uint8_t c = (uint8_t) **pUtf8Ptr;
634 if (c <= 0x7f) {
635 // It's low-ascii, so check the table.
636 uint32_t wordIdx = c >> 5;
637 uint32_t bitIdx = c & 0x1f;
638 (*pUtf8Ptr)++;
639 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
640 }
641
642 // It's a multibyte encoded character. Call a non-inline function
643 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800644 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
645}
646
647bool IsValidMemberName(const char* s) {
648 bool angle_name = false;
649
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700650 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800651 case '\0':
652 // The empty string is not a valid name.
653 return false;
654 case '<':
655 angle_name = true;
656 s++;
657 break;
658 }
659
660 while (true) {
661 switch (*s) {
662 case '\0':
663 return !angle_name;
664 case '>':
665 return angle_name && s[1] == '\0';
666 }
667
668 if (!IsValidPartOfMemberNameUtf8(&s)) {
669 return false;
670 }
671 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700672}
673
Elliott Hughes906e6852011-10-28 14:52:10 -0700674enum ClassNameType { kName, kDescriptor };
675bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700676 int arrayCount = 0;
677 while (*s == '[') {
678 arrayCount++;
679 s++;
680 }
681
682 if (arrayCount > 255) {
683 // Arrays may have no more than 255 dimensions.
684 return false;
685 }
686
687 if (arrayCount != 0) {
688 /*
689 * If we're looking at an array of some sort, then it doesn't
690 * matter if what is being asked for is a class name; the
691 * format looks the same as a type descriptor in that case, so
692 * treat it as such.
693 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700694 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700695 }
696
Elliott Hughes906e6852011-10-28 14:52:10 -0700697 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700698 /*
699 * We are looking for a descriptor. Either validate it as a
700 * single-character primitive type, or continue on to check the
701 * embedded class name (bracketed by "L" and ";").
702 */
703 switch (*(s++)) {
704 case 'B':
705 case 'C':
706 case 'D':
707 case 'F':
708 case 'I':
709 case 'J':
710 case 'S':
711 case 'Z':
712 // These are all single-character descriptors for primitive types.
713 return (*s == '\0');
714 case 'V':
715 // Non-array void is valid, but you can't have an array of void.
716 return (arrayCount == 0) && (*s == '\0');
717 case 'L':
718 // Class name: Break out and continue below.
719 break;
720 default:
721 // Oddball descriptor character.
722 return false;
723 }
724 }
725
726 /*
727 * We just consumed the 'L' that introduces a class name as part
728 * of a type descriptor, or we are looking for an unadorned class
729 * name.
730 */
731
732 bool sepOrFirst = true; // first character or just encountered a separator.
733 for (;;) {
734 uint8_t c = (uint8_t) *s;
735 switch (c) {
736 case '\0':
737 /*
738 * Premature end for a type descriptor, but valid for
739 * a class name as long as we haven't encountered an
740 * empty component (including the degenerate case of
741 * the empty string "").
742 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700743 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700744 case ';':
745 /*
746 * Invalid character for a class name, but the
747 * legitimate end of a type descriptor. In the latter
748 * case, make sure that this is the end of the string
749 * and that it doesn't end with an empty component
750 * (including the degenerate case of "L;").
751 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700752 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700753 case '/':
754 case '.':
755 if (c != separator) {
756 // The wrong separator character.
757 return false;
758 }
759 if (sepOrFirst) {
760 // Separator at start or two separators in a row.
761 return false;
762 }
763 sepOrFirst = true;
764 s++;
765 break;
766 default:
jeffhao10037c82012-01-23 15:06:23 -0800767 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700768 return false;
769 }
770 sepOrFirst = false;
771 break;
772 }
773 }
774}
775
Elliott Hughes906e6852011-10-28 14:52:10 -0700776bool IsValidBinaryClassName(const char* s) {
777 return IsValidClassName(s, kName, '.');
778}
779
780bool IsValidJniClassName(const char* s) {
781 return IsValidClassName(s, kName, '/');
782}
783
784bool IsValidDescriptor(const char* s) {
785 return IsValidClassName(s, kDescriptor, '/');
786}
787
Elliott Hughes48436bb2012-02-07 15:23:28 -0800788void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700789 const char* p = s.data();
790 const char* end = p + s.size();
791 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800792 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700793 ++p;
794 } else {
795 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800796 while (++p != end && *p != separator) {
797 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700798 }
799 result.push_back(std::string(start, p - start));
800 }
801 }
802}
803
Elliott Hughes48436bb2012-02-07 15:23:28 -0800804template <typename StringT>
805std::string Join(std::vector<StringT>& strings, char separator) {
806 if (strings.empty()) {
807 return "";
808 }
809
810 std::string result(strings[0]);
811 for (size_t i = 1; i < strings.size(); ++i) {
812 result += separator;
813 result += strings[i];
814 }
815 return result;
816}
817
818// Explicit instantiations.
819template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
820template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
821template std::string Join<char*>(std::vector<char*>& strings, char separator);
822
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800823bool StartsWith(const std::string& s, const char* prefix) {
824 return s.compare(0, strlen(prefix), prefix) == 0;
825}
826
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700827bool EndsWith(const std::string& s, const char* suffix) {
828 size_t suffix_length = strlen(suffix);
829 size_t string_length = s.size();
830 if (suffix_length > string_length) {
831 return false;
832 }
833 size_t offset = string_length - suffix_length;
834 return s.compare(offset, suffix_length, suffix) == 0;
835}
836
Elliott Hughes22869a92012-03-27 14:08:24 -0700837void SetThreadName(const char* thread_name) {
838 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800839
Elliott Hughesdcc24742011-09-07 14:02:44 -0700840 int hasAt = 0;
841 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700842 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700843 while (*s) {
844 if (*s == '.') {
845 hasDot = 1;
846 } else if (*s == '@') {
847 hasAt = 1;
848 }
849 s++;
850 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700851 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700852 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700853 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700854 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700855 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700856 }
857#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700858 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700859 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
860 strncpy(buf, s, sizeof(buf)-1);
861 buf[sizeof(buf)-1] = '\0';
862 errno = pthread_setname_np(pthread_self(), buf);
863 if (errno != 0) {
864 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
865 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700866#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700867 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700868#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700869 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700870#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700871 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700872#endif
873}
874
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700875void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
876 utime = stime = task_cpu = 0;
877 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700878 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700879 return;
880 }
881 // Skip the command, which may contain spaces.
882 stats = stats.substr(stats.find(')') + 2);
883 // Extract the three fields we care about.
884 std::vector<std::string> fields;
885 Split(stats, ' ', fields);
886 utime = strtoull(fields[11].c_str(), NULL, 10);
887 stime = strtoull(fields[12].c_str(), NULL, 10);
888 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
889}
890
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700891std::string GetSchedulerGroupName(pid_t tid) {
892 // /proc/<pid>/cgroup looks like this:
893 // 2:devices:/
894 // 1:cpuacct,cpu:/
895 // We want the third field from the line whose second field contains the "cpu" token.
896 std::string cgroup_file;
897 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
898 return "";
899 }
900 std::vector<std::string> cgroup_lines;
901 Split(cgroup_file, '\n', cgroup_lines);
902 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
903 std::vector<std::string> cgroup_fields;
904 Split(cgroup_lines[i], ':', cgroup_fields);
905 std::vector<std::string> cgroups;
906 Split(cgroup_fields[1], ',', cgroups);
907 for (size_t i = 0; i < cgroups.size(); ++i) {
908 if (cgroups[i] == "cpu") {
909 return cgroup_fields[2].substr(1); // Skip the leading slash.
910 }
911 }
912 }
913 return "";
914}
915
Elliott Hughes46e251b2012-05-22 15:10:45 -0700916#if defined(__APPLE__)
917
918static std::string Demangle(const std::string& mangled_name) {
919 if (mangled_name.empty()) {
920 return "??";
921 }
922
923 // http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html
924 int status;
925 char* name(abi::__cxa_demangle(mangled_name.c_str(), NULL, NULL, &status));
926 if (name != NULL) {
927 std::string result(name);
928 free(name);
929 return result;
930 }
931
932 return mangled_name;
933}
934
935// TODO: port libcorkscrew to Mac OS (or find an equivalent).
936void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
937 if (tid != GetTid()) {
938 // backtrace(3) only works for the current thread.
939 return;
940 }
941
942 // Get the raw stack frames.
943 size_t MAX_STACK_FRAMES = 128;
944 void* frames[MAX_STACK_FRAMES];
945 size_t frame_count = backtrace(frames, MAX_STACK_FRAMES);
946 if (frame_count == 0) {
947 os << prefix << "--- backtrace(3) returned no frames";
948 return;
949 }
950
951 // Turn them into something human-readable with symbols.
952 char** symbols = backtrace_symbols(frames, frame_count);
953 if (symbols == NULL) {
954 os << prefix << "--- backtrace_symbols(3) failed";
955 return;
956 }
957
958 // Parse the backtrace strings and demangle, so we can produce output like this:
959 // ] #00 art::Runtime::Abort(char const*, int)+0x15b [0xf770dd51] (libartd.so)
960 for (size_t i = 0; i < frame_count; ++i) {
961 std::string text(symbols[i]);
962 std::string filename("???");
963 std::string function_name;
964
965 // backtrace_symbols(3) gives us lines like this on Mac OS:
966 // "0 libartd.dylib 0x001cd29a _ZN3art9Backtrace4DumpERSo + 40>"
967 // "3 ??? 0xffffffff 0x0 + 4294967295>"
968 text.erase(0, 4);
969 size_t index = text.find(' ');
970 filename = text.substr(0, index);
971 text.erase(0, 40 - 4);
972 index = text.find(' ');
973 std::string address(text.substr(0, index));
974 text.erase(0, index + 1);
975 index = text.find(' ');
976 function_name = Demangle(text.substr(0, index));
977 text.erase(0, index);
978 text += " [" + address + "]";
979
980 const char* last_slash = strrchr(filename.c_str(), '/');
981 const char* so_name = (last_slash == NULL) ? filename.c_str() : last_slash + 1;
982 os << prefix;
983 if (include_count) {
984 os << StringPrintf("\t#%02zd ", i);
985 }
986 os << function_name << text << " (" << so_name << ")\n";
987 }
988
989 free(symbols);
990}
991
992// TODO: is there any way to get the kernel stack on Mac OS?
993void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
994
995#else
996
997static const char* CleanMapName(const backtrace_symbol_t* symbol) {
998 const char* map_name = symbol->map_name;
999 if (map_name == NULL) {
1000 map_name = "???";
1001 }
1002 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1003 // into "libartd.so".
1004 const char* last_slash = strrchr(map_name, '/');
1005 if (last_slash != NULL) {
1006 map_name = last_slash + 1;
1007 }
1008 return map_name;
1009}
1010
1011static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
1012 std::string& symbol_name, uint32_t& pc_offset) {
1013 symbol_table_t* symbol_table = NULL;
1014 if (symbol->map_name != NULL) {
1015 symbol_table = load_symbol_table(symbol->map_name);
1016 }
1017 const symbol_t* elf_symbol = NULL;
1018 if (symbol_table != NULL) {
1019 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
1020 if (elf_symbol == NULL) {
1021 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
1022 }
1023 }
1024 if (elf_symbol != NULL) {
1025 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
1026 if (demangled_symbol_name != NULL) {
1027 symbol_name = demangled_symbol_name;
1028 } else {
1029 symbol_name = elf_symbol->name;
1030 }
1031 pc_offset = frame->absolute_pc - elf_symbol->start;
1032 } else {
1033 symbol_name = "???";
1034 }
1035 free_symbol_table(symbol_table);
1036}
1037
1038void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
1039 const size_t MAX_DEPTH = 32;
1040 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
1041 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), 0, MAX_DEPTH);
1042 if (frame_count == -1) {
1043 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ".)";
1044 return;
1045 } else if (frame_count == 0) {
1046 os << prefix << "(no native stack frames)";
1047 return;
1048 }
1049
1050 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1051 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1052
1053 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1054 const backtrace_frame_t* frame = &frames[i];
1055 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1056
1057 // We produce output like this:
1058 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1059
1060 std::string symbol_name;
1061 uint32_t pc_offset = 0;
1062 if (symbol->demangled_name != NULL) {
1063 symbol_name = symbol->demangled_name;
1064 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1065 } else if (symbol->symbol_name != NULL) {
1066 symbol_name = symbol->symbol_name;
1067 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1068 } else {
1069 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1070 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1071 }
1072
1073 os << prefix;
1074 if (include_count) {
1075 os << StringPrintf("#%02zd ", i);
1076 }
1077 os << symbol_name;
1078 if (pc_offset != 0) {
1079 os << "+" << pc_offset;
1080 }
1081 os << StringPrintf(" [%p] (%s)\n",
1082 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1083 }
1084
1085 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1086}
1087
1088void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
1089 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1090 std::string kernel_stack;
1091 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
1092 os << " (couldn't read " << kernel_stack_filename << ")";
1093 }
1094
1095 std::vector<std::string> kernel_stack_frames;
1096 Split(kernel_stack, '\n', kernel_stack_frames);
1097 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1098 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1099 kernel_stack_frames.pop_back();
1100 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1101 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1102 const char* text = kernel_stack_frames[i].c_str();
1103 const char* close_bracket = strchr(text, ']');
1104 if (close_bracket != NULL) {
1105 text = close_bracket + 2;
1106 }
1107 os << prefix;
1108 if (include_count) {
1109 os << StringPrintf("#%02zd ", i);
1110 }
1111 os << text << "\n";
1112 }
1113}
1114
1115#endif
1116
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001117const char* GetAndroidRoot() {
1118 const char* android_root = getenv("ANDROID_ROOT");
1119 if (android_root == NULL) {
1120 if (OS::DirectoryExists("/system")) {
1121 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001122 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001123 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1124 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001125 }
1126 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001127 if (!OS::DirectoryExists(android_root)) {
1128 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001129 return "";
1130 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001131 return android_root;
1132}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001133
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001134const char* GetAndroidData() {
1135 const char* android_data = getenv("ANDROID_DATA");
1136 if (android_data == NULL) {
1137 if (OS::DirectoryExists("/data")) {
1138 android_data = "/data";
1139 } else {
1140 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1141 return "";
1142 }
1143 }
1144 if (!OS::DirectoryExists(android_data)) {
1145 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1146 return "";
1147 }
1148 return android_data;
1149}
1150
Shih-wei Liao795e3302012-04-21 00:20:57 -07001151std::string GetArtCacheOrDie(const char* android_data) {
1152 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001153
1154 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001155 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001156 int result = mkdir(art_cache.c_str(), 0700);
1157 if (result != 0) {
1158 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1159 return "";
1160 }
1161 } else {
1162 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1163 return "";
1164 }
1165 }
1166 return art_cache;
1167}
1168
jeffhao262bf462011-10-20 18:36:32 -07001169std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001170 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001171 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001172 std::string cache_file(location, 1); // skip leading slash
1173 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1174 return art_cache + "/" + cache_file;
1175}
1176
jeffhao262bf462011-10-20 18:36:32 -07001177bool IsValidZipFilename(const std::string& filename) {
1178 if (filename.size() < 4) {
1179 return false;
1180 }
1181 std::string suffix(filename.substr(filename.size() - 4));
1182 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1183}
1184
1185bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001186 return EndsWith(filename, ".dex");
1187}
1188
1189bool IsValidOatFilename(const std::string& filename) {
1190 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001191}
1192
Elliott Hughes42ee1422011-09-06 12:33:32 -07001193} // namespace art