blob: 084456d1fcfa9e477333471adee22c9b6e1d0b7d [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 Hughese1884192012-04-23 12:38:15 -070072void GetThreadStack(void*& stack_base, size_t& stack_size) {
73#if defined(__APPLE__)
74 stack_size = pthread_get_stacksize_np(pthread_self());
75 void* stack_addr = pthread_get_stackaddr_np(pthread_self());
76
77 // Check whether stack_addr is the base or end of the stack.
78 // (On Mac OS 10.7, it's the end.)
79 int stack_variable;
80 if (stack_addr > &stack_variable) {
81 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
82 } else {
83 stack_base = stack_addr;
84 }
85#else
86 pthread_attr_t attributes;
87 CHECK_PTHREAD_CALL(pthread_getattr_np, (pthread_self(), &attributes), __FUNCTION__);
88 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
89 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
90#endif
91}
92
Elliott Hughesd92bec42011-09-02 17:04:36 -070093bool ReadFileToString(const std::string& file_name, std::string* result) {
94 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
95 if (file.get() == NULL) {
96 return false;
97 }
buzbeec143c552011-08-20 17:38:58 -070098
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070099 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700100 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700101 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700102 if (n == -1) {
103 return false;
buzbeec143c552011-08-20 17:38:58 -0700104 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700105 if (n == 0) {
106 return true;
107 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700108 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700109 }
buzbeec143c552011-08-20 17:38:58 -0700110}
111
Elliott Hughese27955c2011-08-26 15:21:24 -0700112std::string GetIsoDate() {
113 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700114 tm tmbuf;
115 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700116 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
117 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
118 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
119}
120
Elliott Hughes7162ad92011-10-27 14:08:42 -0700121uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800122#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700123 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700124 clock_gettime(CLOCK_MONOTONIC, &now);
125 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700127 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800128 gettimeofday(&now, NULL);
129 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
130#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700131}
132
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800133uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800134#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700135 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800136 clock_gettime(CLOCK_MONOTONIC, &now);
137 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700139 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800140 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700141 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800143}
144
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700145uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800146#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700147 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700148 clock_gettime(CLOCK_MONOTONIC, &now);
149 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700151 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800152 gettimeofday(&now, NULL);
153 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
154#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700155}
156
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800157uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800158#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700159 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800160 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
161 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162#else
163 UNIMPLEMENTED(WARNING);
164 return -1;
165#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800166}
167
Elliott Hughes0512f022012-03-15 22:10:52 -0700168uint64_t ThreadCpuNanoTime() {
169#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700170 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700171 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
172 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
173#else
174 UNIMPLEMENTED(WARNING);
175 return -1;
176#endif
177}
178
Elliott Hughes5174fe62011-08-23 15:12:35 -0700179std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700180 if (java_descriptor == NULL) {
181 return "null";
182 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700183 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
184}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700185
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800186std::string PrettyDescriptor(const Class* klass) {
187 if (klass == NULL) {
188 return "null";
189 }
190 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800191}
192
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700193std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700194 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700195 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700196 size_t dim = 0;
197 while (*c == '[') {
198 dim++;
199 c++;
200 }
201
202 // Reference or primitive?
203 if (*c == 'L') {
204 // "[[La/b/C;" -> "a.b.C[][]".
205 c++; // Skip the 'L'.
206 } else {
207 // "[[B" -> "byte[][]".
208 // To make life easier, we make primitives look like unqualified
209 // reference types.
210 switch (*c) {
211 case 'B': c = "byte;"; break;
212 case 'C': c = "char;"; break;
213 case 'D': c = "double;"; break;
214 case 'F': c = "float;"; break;
215 case 'I': c = "int;"; break;
216 case 'J': c = "long;"; break;
217 case 'S': c = "short;"; break;
218 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700219 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700220 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700221 }
222 }
223
224 // At this point, 'c' is a string of the form "fully/qualified/Type;"
225 // or "primitive;". Rewrite the type with '.' instead of '/':
226 std::string result;
227 const char* p = c;
228 while (*p != ';') {
229 char ch = *p++;
230 if (ch == '/') {
231 ch = '.';
232 }
233 result.push_back(ch);
234 }
235 // ...and replace the semicolon with 'dim' "[]" pairs:
236 while (dim--) {
237 result += "[]";
238 }
239 return result;
240}
241
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700242std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800243 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700244 return PrettyDescriptor(descriptor_string);
245}
246
Elliott Hughes54e7df12011-09-16 11:47:04 -0700247std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700248 if (f == NULL) {
249 return "null";
250 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800251 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700252 std::string result;
253 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800254 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700255 result += ' ';
256 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800257 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700258 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800259 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700260 return result;
261}
262
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700263std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
264 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
265 std::string result;
266 if (with_type) {
267 result += dex_file.GetFieldTypeDescriptor(field_id);
268 result += ' ';
269 }
270 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
271 result += '.';
272 result += dex_file.GetFieldName(field_id);
273 return result;
274}
275
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700276std::string PrettyArguments(const char* signature) {
277 std::string result;
278 result += '(';
279 CHECK_EQ(*signature, '(');
280 ++signature; // Skip the '('.
281 while (*signature != ')') {
282 size_t argument_length = 0;
283 while (signature[argument_length] == '[') {
284 ++argument_length;
285 }
286 if (signature[argument_length] == 'L') {
287 argument_length = (strchr(signature, ';') - signature + 1);
288 } else {
289 ++argument_length;
290 }
291 std::string argument_descriptor(signature, argument_length);
292 result += PrettyDescriptor(argument_descriptor);
293 if (signature[argument_length] != ')') {
294 result += ", ";
295 }
296 signature += argument_length;
297 }
298 CHECK_EQ(*signature, ')');
299 ++signature; // Skip the ')'.
300 result += ')';
301 return result;
302}
303
304std::string PrettyReturnType(const char* signature) {
305 const char* return_type = strchr(signature, ')');
306 CHECK(return_type != NULL);
307 ++return_type; // Skip ')'.
308 return PrettyDescriptor(return_type);
309}
310
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700311std::string PrettyMethod(const Method* m, bool with_signature) {
312 if (m == NULL) {
313 return "null";
314 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800315 MethodHelper mh(m);
316 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700317 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800318 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700319 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700320 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700321 if (signature == "<no signature>") {
322 return result + signature;
323 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700324 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700325 }
326 return result;
327}
328
Ian Rogers0571d352011-11-03 19:51:38 -0700329std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
330 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
331 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
332 result += '.';
333 result += dex_file.GetMethodName(method_id);
334 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700335 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700336 if (signature == "<no signature>") {
337 return result + signature;
338 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700339 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700340 }
341 return result;
342}
343
Elliott Hughes54e7df12011-09-16 11:47:04 -0700344std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700345 if (obj == NULL) {
346 return "null";
347 }
348 if (obj->GetClass() == NULL) {
349 return "(raw)";
350 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800351 ClassHelper kh(obj->GetClass());
352 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700353 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800354 kh.ChangeClass(obj->AsClass());
355 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700356 }
357 return result;
358}
359
Elliott Hughes54e7df12011-09-16 11:47:04 -0700360std::string PrettyClass(const Class* c) {
361 if (c == NULL) {
362 return "null";
363 }
364 std::string result;
365 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800366 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700367 result += ">";
368 return result;
369}
370
Ian Rogersd81871c2011-10-03 13:57:23 -0700371std::string PrettyClassAndClassLoader(const Class* c) {
372 if (c == NULL) {
373 return "null";
374 }
375 std::string result;
376 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800377 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700378 result += ",";
379 result += PrettyTypeOf(c->GetClassLoader());
380 // TODO: add an identifying hash value for the loader
381 result += ">";
382 return result;
383}
384
Elliott Hughesc967f782012-04-16 10:23:15 -0700385std::string PrettySize(size_t byte_count) {
386 // The byte thresholds at which we display amounts. A byte count is displayed
387 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
388 static const size_t kUnitThresholds[] = {
389 0, // B up to...
390 3*1024, // KB up to...
391 2*1024*1024, // MB up to...
392 1024*1024*1024 // GB from here.
393 };
394 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
395 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
396
397 int i = arraysize(kUnitThresholds);
398 while (--i > 0) {
399 if (byte_count >= kUnitThresholds[i]) {
400 break;
401 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800402 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700403
404 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800405}
406
407std::string PrettyDuration(uint64_t nano_duration) {
408 if (nano_duration == 0) {
409 return "0";
410 } else {
411 const uint64_t one_sec = 1000 * 1000 * 1000;
412 const uint64_t one_ms = 1000 * 1000;
413 const uint64_t one_us = 1000;
414 const char* unit;
415 uint64_t divisor;
416 uint32_t zero_fill;
417 if (nano_duration >= one_sec) {
418 unit = "s";
419 divisor = one_sec;
420 zero_fill = 9;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700421 } else if (nano_duration >= one_ms) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800422 unit = "ms";
423 divisor = one_ms;
424 zero_fill = 6;
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700425 } else if (nano_duration >= one_us) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800426 unit = "us";
427 divisor = one_us;
428 zero_fill = 3;
429 } else {
430 unit = "ns";
431 divisor = 1;
432 zero_fill = 0;
433 }
434 uint64_t whole_part = nano_duration / divisor;
435 uint64_t fractional_part = nano_duration % divisor;
436 if (fractional_part == 0) {
437 return StringPrintf("%llu%s", whole_part, unit);
438 } else {
439 while ((fractional_part % 1000) == 0) {
440 zero_fill -= 3;
441 fractional_part /= 1000;
442 }
443 if (zero_fill == 3) {
444 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
445 } else if (zero_fill == 6) {
446 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
447 } else {
448 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
449 }
450 }
451 }
452}
453
Elliott Hughes82914b62012-04-09 15:56:29 -0700454std::string PrintableString(const std::string& utf) {
455 std::string result;
456 result += '"';
457 const char* p = utf.c_str();
458 size_t char_count = CountModifiedUtf8Chars(p);
459 for (size_t i = 0; i < char_count; ++i) {
460 uint16_t ch = GetUtf16FromUtf8(&p);
461 if (ch == '\\') {
462 result += "\\\\";
463 } else if (ch == '\n') {
464 result += "\\n";
465 } else if (ch == '\r') {
466 result += "\\r";
467 } else if (ch == '\t') {
468 result += "\\t";
469 } else if (NeedsEscaping(ch)) {
470 StringAppendF(&result, "\\u%04x", ch);
471 } else {
472 result += ch;
473 }
474 }
475 result += '"';
476 return result;
477}
478
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800479// 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 -0700480std::string MangleForJni(const std::string& s) {
481 std::string result;
482 size_t char_count = CountModifiedUtf8Chars(s.c_str());
483 const char* cp = &s[0];
484 for (size_t i = 0; i < char_count; ++i) {
485 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800486 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
487 result.push_back(ch);
488 } else if (ch == '.' || ch == '/') {
489 result += "_";
490 } else if (ch == '_') {
491 result += "_1";
492 } else if (ch == ';') {
493 result += "_2";
494 } else if (ch == '[') {
495 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700496 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800497 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700498 }
499 }
500 return result;
501}
502
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700503std::string DotToDescriptor(const char* class_name) {
504 std::string descriptor(class_name);
505 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
506 if (descriptor.length() > 0 && descriptor[0] != '[') {
507 descriptor = "L" + descriptor + ";";
508 }
509 return descriptor;
510}
511
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800512std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800513 size_t length = strlen(descriptor);
514 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
515 std::string result(descriptor + 1, length - 2);
516 std::replace(result.begin(), result.end(), '/', '.');
517 return result;
518 }
519 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800520}
521
522std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800523 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800524 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
525 std::string result(descriptor + 1, length - 2);
526 return result;
527 }
528 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700529}
530
Elliott Hughes79082e32011-08-25 12:07:32 -0700531std::string JniShortName(const Method* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532 MethodHelper mh(m);
533 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700534 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700535 CHECK_EQ(class_name[0], 'L') << class_name;
536 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700537 class_name.erase(0, 1);
538 class_name.erase(class_name.size() - 1, 1);
539
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800540 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700541
542 std::string short_name;
543 short_name += "Java_";
544 short_name += MangleForJni(class_name);
545 short_name += "_";
546 short_name += MangleForJni(method_name);
547 return short_name;
548}
549
550std::string JniLongName(const Method* m) {
551 std::string long_name;
552 long_name += JniShortName(m);
553 long_name += "__";
554
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800555 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700556 signature.erase(0, 1);
557 signature.erase(signature.begin() + signature.find(')'), signature.end());
558
559 long_name += MangleForJni(signature);
560
561 return long_name;
562}
563
jeffhao10037c82012-01-23 15:06:23 -0800564// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700565uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
566 0x00000000, // 00..1f low control characters; nothing valid
567 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
568 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
569 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
570};
571
jeffhao10037c82012-01-23 15:06:23 -0800572// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
573bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700574 /*
575 * It's a multibyte encoded character. Decode it and analyze. We
576 * accept anything that isn't (a) an improperly encoded low value,
577 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
578 * control character, or (e) a high space, layout, or special
579 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
580 * U+fff0..U+ffff). This is all specified in the dex format
581 * document.
582 */
583
584 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
585
586 // Perform follow-up tests based on the high 8 bits.
587 switch (utf16 >> 8) {
588 case 0x00:
589 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
590 return (utf16 > 0x00a0);
591 case 0xd8:
592 case 0xd9:
593 case 0xda:
594 case 0xdb:
595 // It's a leading surrogate. Check to see that a trailing
596 // surrogate follows.
597 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
598 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
599 case 0xdc:
600 case 0xdd:
601 case 0xde:
602 case 0xdf:
603 // It's a trailing surrogate, which is not valid at this point.
604 return false;
605 case 0x20:
606 case 0xff:
607 // It's in the range that has spaces, controls, and specials.
608 switch (utf16 & 0xfff8) {
609 case 0x2000:
610 case 0x2008:
611 case 0x2028:
612 case 0xfff0:
613 case 0xfff8:
614 return false;
615 }
616 break;
617 }
618 return true;
619}
620
621/* Return whether the pointed-at modified-UTF-8 encoded character is
622 * valid as part of a member name, updating the pointer to point past
623 * the consumed character. This will consume two encoded UTF-16 code
624 * points if the character is encoded as a surrogate pair. Also, if
625 * this function returns false, then the given pointer may only have
626 * been partially advanced.
627 */
jeffhao10037c82012-01-23 15:06:23 -0800628bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700629 uint8_t c = (uint8_t) **pUtf8Ptr;
630 if (c <= 0x7f) {
631 // It's low-ascii, so check the table.
632 uint32_t wordIdx = c >> 5;
633 uint32_t bitIdx = c & 0x1f;
634 (*pUtf8Ptr)++;
635 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
636 }
637
638 // It's a multibyte encoded character. Call a non-inline function
639 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800640 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
641}
642
643bool IsValidMemberName(const char* s) {
644 bool angle_name = false;
645
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700646 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800647 case '\0':
648 // The empty string is not a valid name.
649 return false;
650 case '<':
651 angle_name = true;
652 s++;
653 break;
654 }
655
656 while (true) {
657 switch (*s) {
658 case '\0':
659 return !angle_name;
660 case '>':
661 return angle_name && s[1] == '\0';
662 }
663
664 if (!IsValidPartOfMemberNameUtf8(&s)) {
665 return false;
666 }
667 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700668}
669
Elliott Hughes906e6852011-10-28 14:52:10 -0700670enum ClassNameType { kName, kDescriptor };
671bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700672 int arrayCount = 0;
673 while (*s == '[') {
674 arrayCount++;
675 s++;
676 }
677
678 if (arrayCount > 255) {
679 // Arrays may have no more than 255 dimensions.
680 return false;
681 }
682
683 if (arrayCount != 0) {
684 /*
685 * If we're looking at an array of some sort, then it doesn't
686 * matter if what is being asked for is a class name; the
687 * format looks the same as a type descriptor in that case, so
688 * treat it as such.
689 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700690 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700691 }
692
Elliott Hughes906e6852011-10-28 14:52:10 -0700693 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700694 /*
695 * We are looking for a descriptor. Either validate it as a
696 * single-character primitive type, or continue on to check the
697 * embedded class name (bracketed by "L" and ";").
698 */
699 switch (*(s++)) {
700 case 'B':
701 case 'C':
702 case 'D':
703 case 'F':
704 case 'I':
705 case 'J':
706 case 'S':
707 case 'Z':
708 // These are all single-character descriptors for primitive types.
709 return (*s == '\0');
710 case 'V':
711 // Non-array void is valid, but you can't have an array of void.
712 return (arrayCount == 0) && (*s == '\0');
713 case 'L':
714 // Class name: Break out and continue below.
715 break;
716 default:
717 // Oddball descriptor character.
718 return false;
719 }
720 }
721
722 /*
723 * We just consumed the 'L' that introduces a class name as part
724 * of a type descriptor, or we are looking for an unadorned class
725 * name.
726 */
727
728 bool sepOrFirst = true; // first character or just encountered a separator.
729 for (;;) {
730 uint8_t c = (uint8_t) *s;
731 switch (c) {
732 case '\0':
733 /*
734 * Premature end for a type descriptor, but valid for
735 * a class name as long as we haven't encountered an
736 * empty component (including the degenerate case of
737 * the empty string "").
738 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700739 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700740 case ';':
741 /*
742 * Invalid character for a class name, but the
743 * legitimate end of a type descriptor. In the latter
744 * case, make sure that this is the end of the string
745 * and that it doesn't end with an empty component
746 * (including the degenerate case of "L;").
747 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700748 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700749 case '/':
750 case '.':
751 if (c != separator) {
752 // The wrong separator character.
753 return false;
754 }
755 if (sepOrFirst) {
756 // Separator at start or two separators in a row.
757 return false;
758 }
759 sepOrFirst = true;
760 s++;
761 break;
762 default:
jeffhao10037c82012-01-23 15:06:23 -0800763 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700764 return false;
765 }
766 sepOrFirst = false;
767 break;
768 }
769 }
770}
771
Elliott Hughes906e6852011-10-28 14:52:10 -0700772bool IsValidBinaryClassName(const char* s) {
773 return IsValidClassName(s, kName, '.');
774}
775
776bool IsValidJniClassName(const char* s) {
777 return IsValidClassName(s, kName, '/');
778}
779
780bool IsValidDescriptor(const char* s) {
781 return IsValidClassName(s, kDescriptor, '/');
782}
783
Elliott Hughes48436bb2012-02-07 15:23:28 -0800784void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700785 const char* p = s.data();
786 const char* end = p + s.size();
787 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800788 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700789 ++p;
790 } else {
791 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800792 while (++p != end && *p != separator) {
793 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700794 }
795 result.push_back(std::string(start, p - start));
796 }
797 }
798}
799
Elliott Hughes48436bb2012-02-07 15:23:28 -0800800template <typename StringT>
801std::string Join(std::vector<StringT>& strings, char separator) {
802 if (strings.empty()) {
803 return "";
804 }
805
806 std::string result(strings[0]);
807 for (size_t i = 1; i < strings.size(); ++i) {
808 result += separator;
809 result += strings[i];
810 }
811 return result;
812}
813
814// Explicit instantiations.
815template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
816template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
817template std::string Join<char*>(std::vector<char*>& strings, char separator);
818
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800819bool StartsWith(const std::string& s, const char* prefix) {
820 return s.compare(0, strlen(prefix), prefix) == 0;
821}
822
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700823bool EndsWith(const std::string& s, const char* suffix) {
824 size_t suffix_length = strlen(suffix);
825 size_t string_length = s.size();
826 if (suffix_length > string_length) {
827 return false;
828 }
829 size_t offset = string_length - suffix_length;
830 return s.compare(offset, suffix_length, suffix) == 0;
831}
832
Elliott Hughes22869a92012-03-27 14:08:24 -0700833void SetThreadName(const char* thread_name) {
834 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800835
Elliott Hughesdcc24742011-09-07 14:02:44 -0700836 int hasAt = 0;
837 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700838 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700839 while (*s) {
840 if (*s == '.') {
841 hasDot = 1;
842 } else if (*s == '@') {
843 hasAt = 1;
844 }
845 s++;
846 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700847 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700848 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700849 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700850 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700851 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700852 }
853#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700854 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700855 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
856 strncpy(buf, s, sizeof(buf)-1);
857 buf[sizeof(buf)-1] = '\0';
858 errno = pthread_setname_np(pthread_self(), buf);
859 if (errno != 0) {
860 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
861 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700862#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700863 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700864#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700865 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700866#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700867 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700868#endif
869}
870
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700871void GetTaskStats(pid_t tid, int& utime, int& stime, int& task_cpu) {
872 utime = stime = task_cpu = 0;
873 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700874 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700875 return;
876 }
877 // Skip the command, which may contain spaces.
878 stats = stats.substr(stats.find(')') + 2);
879 // Extract the three fields we care about.
880 std::vector<std::string> fields;
881 Split(stats, ' ', fields);
882 utime = strtoull(fields[11].c_str(), NULL, 10);
883 stime = strtoull(fields[12].c_str(), NULL, 10);
884 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
885}
886
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700887std::string GetSchedulerGroupName(pid_t tid) {
888 // /proc/<pid>/cgroup looks like this:
889 // 2:devices:/
890 // 1:cpuacct,cpu:/
891 // We want the third field from the line whose second field contains the "cpu" token.
892 std::string cgroup_file;
893 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
894 return "";
895 }
896 std::vector<std::string> cgroup_lines;
897 Split(cgroup_file, '\n', cgroup_lines);
898 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
899 std::vector<std::string> cgroup_fields;
900 Split(cgroup_lines[i], ':', cgroup_fields);
901 std::vector<std::string> cgroups;
902 Split(cgroup_fields[1], ',', cgroups);
903 for (size_t i = 0; i < cgroups.size(); ++i) {
904 if (cgroups[i] == "cpu") {
905 return cgroup_fields[2].substr(1); // Skip the leading slash.
906 }
907 }
908 }
909 return "";
910}
911
Elliott Hughes46e251b2012-05-22 15:10:45 -0700912static const char* CleanMapName(const backtrace_symbol_t* symbol) {
913 const char* map_name = symbol->map_name;
914 if (map_name == NULL) {
915 map_name = "???";
916 }
917 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
918 // into "libartd.so".
919 const char* last_slash = strrchr(map_name, '/');
920 if (last_slash != NULL) {
921 map_name = last_slash + 1;
922 }
923 return map_name;
924}
925
926static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
927 std::string& symbol_name, uint32_t& pc_offset) {
928 symbol_table_t* symbol_table = NULL;
929 if (symbol->map_name != NULL) {
930 symbol_table = load_symbol_table(symbol->map_name);
931 }
932 const symbol_t* elf_symbol = NULL;
933 if (symbol_table != NULL) {
934 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
935 if (elf_symbol == NULL) {
936 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
937 }
938 }
939 if (elf_symbol != NULL) {
940 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
941 if (demangled_symbol_name != NULL) {
942 symbol_name = demangled_symbol_name;
943 } else {
944 symbol_name = elf_symbol->name;
945 }
946 pc_offset = frame->absolute_pc - elf_symbol->start;
947 } else {
948 symbol_name = "???";
949 }
950 free_symbol_table(symbol_table);
951}
952
953void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
954 const size_t MAX_DEPTH = 32;
955 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
956 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), 0, MAX_DEPTH);
957 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -0700958 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -0700959 return;
960 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -0700961 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -0700962 return;
963 }
964
965 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
966 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
967
968 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
969 const backtrace_frame_t* frame = &frames[i];
970 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
971
972 // We produce output like this:
973 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
974
975 std::string symbol_name;
976 uint32_t pc_offset = 0;
977 if (symbol->demangled_name != NULL) {
978 symbol_name = symbol->demangled_name;
979 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
980 } else if (symbol->symbol_name != NULL) {
981 symbol_name = symbol->symbol_name;
982 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
983 } else {
984 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
985 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
986 }
987
988 os << prefix;
989 if (include_count) {
990 os << StringPrintf("#%02zd ", i);
991 }
992 os << symbol_name;
993 if (pc_offset != 0) {
994 os << "+" << pc_offset;
995 }
996 os << StringPrintf(" [%p] (%s)\n",
997 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
998 }
999
1000 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1001}
1002
Elliott Hughes058a6de2012-05-24 19:13:02 -07001003#if defined(__APPLE__)
1004
1005// TODO: is there any way to get the kernel stack on Mac OS?
1006void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1007
1008#else
1009
Elliott Hughes46e251b2012-05-22 15:10:45 -07001010void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001011 if (tid == GetTid()) {
1012 // There's no point showing that we're reading our stack out of /proc!
1013 return;
1014 }
1015
Elliott Hughes46e251b2012-05-22 15:10:45 -07001016 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1017 std::string kernel_stack;
1018 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001019 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001020 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001021 }
1022
1023 std::vector<std::string> kernel_stack_frames;
1024 Split(kernel_stack, '\n', kernel_stack_frames);
1025 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1026 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1027 kernel_stack_frames.pop_back();
1028 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1029 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1030 const char* text = kernel_stack_frames[i].c_str();
1031 const char* close_bracket = strchr(text, ']');
1032 if (close_bracket != NULL) {
1033 text = close_bracket + 2;
1034 }
1035 os << prefix;
1036 if (include_count) {
1037 os << StringPrintf("#%02zd ", i);
1038 }
1039 os << text << "\n";
1040 }
1041}
1042
1043#endif
1044
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001045const char* GetAndroidRoot() {
1046 const char* android_root = getenv("ANDROID_ROOT");
1047 if (android_root == NULL) {
1048 if (OS::DirectoryExists("/system")) {
1049 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001050 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001051 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1052 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001053 }
1054 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001055 if (!OS::DirectoryExists(android_root)) {
1056 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001057 return "";
1058 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001059 return android_root;
1060}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001061
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001062const char* GetAndroidData() {
1063 const char* android_data = getenv("ANDROID_DATA");
1064 if (android_data == NULL) {
1065 if (OS::DirectoryExists("/data")) {
1066 android_data = "/data";
1067 } else {
1068 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1069 return "";
1070 }
1071 }
1072 if (!OS::DirectoryExists(android_data)) {
1073 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1074 return "";
1075 }
1076 return android_data;
1077}
1078
Shih-wei Liao795e3302012-04-21 00:20:57 -07001079std::string GetArtCacheOrDie(const char* android_data) {
1080 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001081
1082 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001083 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001084 int result = mkdir(art_cache.c_str(), 0700);
1085 if (result != 0) {
1086 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1087 return "";
1088 }
1089 } else {
1090 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1091 return "";
1092 }
1093 }
1094 return art_cache;
1095}
1096
jeffhao262bf462011-10-20 18:36:32 -07001097std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001098 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001099 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001100 std::string cache_file(location, 1); // skip leading slash
1101 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1102 return art_cache + "/" + cache_file;
1103}
1104
jeffhao262bf462011-10-20 18:36:32 -07001105bool IsValidZipFilename(const std::string& filename) {
1106 if (filename.size() < 4) {
1107 return false;
1108 }
1109 std::string suffix(filename.substr(filename.size() - 4));
1110 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1111}
1112
1113bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001114 return EndsWith(filename, ".dex");
1115}
1116
1117bool IsValidOatFilename(const std::string& filename) {
1118 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001119}
1120
Elliott Hughes42ee1422011-09-06 12:33:32 -07001121} // namespace art