blob: cbe07a2fa6595c814d9c2ba78e9bc0bcecc6db82 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Elliott Hughes11e45072011-08-16 17:40:46 -070016
Elliott Hughes42ee1422011-09-06 12:33:32 -070017#include "utils.h"
18
Elliott Hughes06e3ad42012-02-07 14:51:57 -080019#include <dynamic_annotations.h>
Elliott Hughes92b3b562011-09-08 16:32:26 -070020#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070021#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070022#include <sys/syscall.h>
23#include <sys/types.h>
24#include <unistd.h>
25
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include "UniquePtr.h"
Ian Rogersd81871c2011-10-03 13:57:23 -070027#include "class_loader.h"
buzbeec143c552011-08-20 17:38:58 -070028#include "file.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070029#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070031#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070032
Elliott Hughesad6c9c32012-01-19 17:39:12 -080033#if !defined(HAVE_POSIX_CLOCKS)
34#include <sys/time.h>
35#endif
36
Elliott Hughesdcc24742011-09-07 14:02:44 -070037#if defined(HAVE_PRCTL)
38#include <sys/prctl.h>
39#endif
40
Elliott Hughes4ae722a2012-03-13 11:08:51 -070041#if defined(__APPLE__)
Elliott Hughesb08e8a32012-04-02 10:51:41 -070042#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070043#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070044#endif
45
Elliott Hughes46e251b2012-05-22 15:10:45 -070046#include <corkscrew/backtrace.h> // For DumpNativeStack.
47#include <corkscrew/demangle.h> // For DumpNativeStack.
48
Elliott Hughes058a6de2012-05-24 19:13:02 -070049#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080050#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080051#endif
52
Elliott Hughes11e45072011-08-16 17:40:46 -070053namespace art {
54
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080055pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070056#if defined(__APPLE__)
57 uint64_t owner;
58 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
59 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080060#else
61 // Neither bionic nor glibc exposes gettid(2).
62 return syscall(__NR_gettid);
63#endif
64}
65
Elliott Hughes289be852012-06-12 13:57:20 -070066std::string GetThreadName(pid_t tid) {
67 std::string result;
68 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
69 result.resize(result.size() - 1); // Lose the trailing '\n'.
70 } else {
71 result = "<unknown>";
72 }
73 return result;
74}
75
Ian Rogers120f1c72012-09-28 17:17:10 -070076void GetThreadStack(pthread_t thread, void*& stack_base, size_t& stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070077#if defined(__APPLE__)
Ian Rogers120f1c72012-09-28 17:17:10 -070078 stack_size = pthread_get_stacksize_np(thread);
79 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070080
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;
Ian Rogers120f1c72012-09-28 17:17:10 -070091 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070092 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
93 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
94#endif
95}
96
Elliott Hughesd92bec42011-09-02 17:04:36 -070097bool ReadFileToString(const std::string& file_name, std::string* result) {
98 UniquePtr<File> file(OS::OpenFile(file_name.c_str(), false));
99 if (file.get() == NULL) {
100 return false;
101 }
buzbeec143c552011-08-20 17:38:58 -0700102
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700103 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700104 while (true) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700105 int64_t n = file->Read(&buf[0], buf.size());
Elliott Hughesd92bec42011-09-02 17:04:36 -0700106 if (n == -1) {
107 return false;
buzbeec143c552011-08-20 17:38:58 -0700108 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700109 if (n == 0) {
110 return true;
111 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700112 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700113 }
buzbeec143c552011-08-20 17:38:58 -0700114}
115
Elliott Hughese27955c2011-08-26 15:21:24 -0700116std::string GetIsoDate() {
117 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700118 tm tmbuf;
119 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700120 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
121 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
122 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
123}
124
Elliott Hughes7162ad92011-10-27 14:08:42 -0700125uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700127 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700128 clock_gettime(CLOCK_MONOTONIC, &now);
129 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800130#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700131 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800132 gettimeofday(&now, NULL);
133 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
134#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135}
136
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800137uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700139 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800140 clock_gettime(CLOCK_MONOTONIC, &now);
141 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700143 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800144 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700145 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800146#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147}
148
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700149uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700151 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700152 clock_gettime(CLOCK_MONOTONIC, &now);
153 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700155 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156 gettimeofday(&now, NULL);
157 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
158#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159}
160
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800161uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700163 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800164 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
165 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800166#else
167 UNIMPLEMENTED(WARNING);
168 return -1;
169#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800170}
171
Elliott Hughes0512f022012-03-15 22:10:52 -0700172uint64_t ThreadCpuNanoTime() {
173#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700174 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700175 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
176 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
177#else
178 UNIMPLEMENTED(WARNING);
179 return -1;
180#endif
181}
182
Elliott Hughes5174fe62011-08-23 15:12:35 -0700183std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700184 if (java_descriptor == NULL) {
185 return "null";
186 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700187 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
188}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700189
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800190std::string PrettyDescriptor(const Class* klass) {
191 if (klass == NULL) {
192 return "null";
193 }
194 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800195}
196
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700197std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700198 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700199 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700200 size_t dim = 0;
201 while (*c == '[') {
202 dim++;
203 c++;
204 }
205
206 // Reference or primitive?
207 if (*c == 'L') {
208 // "[[La/b/C;" -> "a.b.C[][]".
209 c++; // Skip the 'L'.
210 } else {
211 // "[[B" -> "byte[][]".
212 // To make life easier, we make primitives look like unqualified
213 // reference types.
214 switch (*c) {
215 case 'B': c = "byte;"; break;
216 case 'C': c = "char;"; break;
217 case 'D': c = "double;"; break;
218 case 'F': c = "float;"; break;
219 case 'I': c = "int;"; break;
220 case 'J': c = "long;"; break;
221 case 'S': c = "short;"; break;
222 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700223 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700224 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700225 }
226 }
227
228 // At this point, 'c' is a string of the form "fully/qualified/Type;"
229 // or "primitive;". Rewrite the type with '.' instead of '/':
230 std::string result;
231 const char* p = c;
232 while (*p != ';') {
233 char ch = *p++;
234 if (ch == '/') {
235 ch = '.';
236 }
237 result.push_back(ch);
238 }
239 // ...and replace the semicolon with 'dim' "[]" pairs:
240 while (dim--) {
241 result += "[]";
242 }
243 return result;
244}
245
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700246std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800247 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700248 return PrettyDescriptor(descriptor_string);
249}
250
Elliott Hughes54e7df12011-09-16 11:47:04 -0700251std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700252 if (f == NULL) {
253 return "null";
254 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800255 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700256 std::string result;
257 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800258 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700259 result += ' ';
260 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800261 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700262 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800263 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700264 return result;
265}
266
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700267std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
268 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
269 std::string result;
270 if (with_type) {
271 result += dex_file.GetFieldTypeDescriptor(field_id);
272 result += ' ';
273 }
274 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
275 result += '.';
276 result += dex_file.GetFieldName(field_id);
277 return result;
278}
279
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700280std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
281 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700282 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700283}
284
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700285std::string PrettyArguments(const char* signature) {
286 std::string result;
287 result += '(';
288 CHECK_EQ(*signature, '(');
289 ++signature; // Skip the '('.
290 while (*signature != ')') {
291 size_t argument_length = 0;
292 while (signature[argument_length] == '[') {
293 ++argument_length;
294 }
295 if (signature[argument_length] == 'L') {
296 argument_length = (strchr(signature, ';') - signature + 1);
297 } else {
298 ++argument_length;
299 }
300 std::string argument_descriptor(signature, argument_length);
301 result += PrettyDescriptor(argument_descriptor);
302 if (signature[argument_length] != ')') {
303 result += ", ";
304 }
305 signature += argument_length;
306 }
307 CHECK_EQ(*signature, ')');
308 ++signature; // Skip the ')'.
309 result += ')';
310 return result;
311}
312
313std::string PrettyReturnType(const char* signature) {
314 const char* return_type = strchr(signature, ')');
315 CHECK(return_type != NULL);
316 ++return_type; // Skip ')'.
317 return PrettyDescriptor(return_type);
318}
319
Mathieu Chartier66f19252012-09-18 08:57:04 -0700320std::string PrettyMethod(const AbstractMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700321 if (m == NULL) {
322 return "null";
323 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800324 MethodHelper mh(m);
325 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700326 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800327 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700328 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700329 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700330 if (signature == "<no signature>") {
331 return result + signature;
332 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700333 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700334 }
335 return result;
336}
337
Ian Rogers0571d352011-11-03 19:51:38 -0700338std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
339 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
340 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
341 result += '.';
342 result += dex_file.GetMethodName(method_id);
343 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700344 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700345 if (signature == "<no signature>") {
346 return result + signature;
347 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700348 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700349 }
350 return result;
351}
352
Elliott Hughes54e7df12011-09-16 11:47:04 -0700353std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700354 if (obj == NULL) {
355 return "null";
356 }
357 if (obj->GetClass() == NULL) {
358 return "(raw)";
359 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800360 ClassHelper kh(obj->GetClass());
361 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700362 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800363 kh.ChangeClass(obj->AsClass());
364 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700365 }
366 return result;
367}
368
Elliott Hughes54e7df12011-09-16 11:47:04 -0700369std::string PrettyClass(const Class* c) {
370 if (c == NULL) {
371 return "null";
372 }
373 std::string result;
374 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800375 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700376 result += ">";
377 return result;
378}
379
Ian Rogersd81871c2011-10-03 13:57:23 -0700380std::string PrettyClassAndClassLoader(const Class* c) {
381 if (c == NULL) {
382 return "null";
383 }
384 std::string result;
385 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800386 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700387 result += ",";
388 result += PrettyTypeOf(c->GetClassLoader());
389 // TODO: add an identifying hash value for the loader
390 result += ">";
391 return result;
392}
393
Elliott Hughesc967f782012-04-16 10:23:15 -0700394std::string PrettySize(size_t byte_count) {
395 // The byte thresholds at which we display amounts. A byte count is displayed
396 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
397 static const size_t kUnitThresholds[] = {
398 0, // B up to...
399 3*1024, // KB up to...
400 2*1024*1024, // MB up to...
401 1024*1024*1024 // GB from here.
402 };
403 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
404 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
405
406 int i = arraysize(kUnitThresholds);
407 while (--i > 0) {
408 if (byte_count >= kUnitThresholds[i]) {
409 break;
410 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800411 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700412
413 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800414}
415
416std::string PrettyDuration(uint64_t nano_duration) {
417 if (nano_duration == 0) {
418 return "0";
419 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700420 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
421 }
422}
423
424TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
425 const uint64_t one_sec = 1000 * 1000 * 1000;
426 const uint64_t one_ms = 1000 * 1000;
427 const uint64_t one_us = 1000;
428 if (nano_duration >= one_sec) {
429 return kTimeUnitSecond;
430 } else if (nano_duration >= one_ms) {
431 return kTimeUnitMillisecond;
432 } else if (nano_duration >= one_us) {
433 return kTimeUnitMicrosecond;
434 } else {
435 return kTimeUnitNanosecond;
436 }
437}
438
439uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
440 const uint64_t one_sec = 1000 * 1000 * 1000;
441 const uint64_t one_ms = 1000 * 1000;
442 const uint64_t one_us = 1000;
443
444 switch (time_unit) {
445 case kTimeUnitSecond:
446 return one_sec;
447 case kTimeUnitMillisecond:
448 return one_ms;
449 case kTimeUnitMicrosecond:
450 return one_us;
451 case kTimeUnitNanosecond:
452 return 1;
453 }
454 return 0;
455}
456
457std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
458 const char* unit = NULL;
459 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
460 uint32_t zero_fill = 1;
461 switch (time_unit) {
462 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800463 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800464 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700465 break;
466 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800467 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800468 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700469 break;
470 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800471 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800472 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700473 break;
474 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800475 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800476 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700477 break;
478 }
479
480 uint64_t whole_part = nano_duration / divisor;
481 uint64_t fractional_part = nano_duration % divisor;
482 if (fractional_part == 0) {
483 return StringPrintf("%llu%s", whole_part, unit);
484 } else {
485 while ((fractional_part % 1000) == 0) {
486 zero_fill -= 3;
487 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800488 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700489 if (zero_fill == 3) {
490 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
491 } else if (zero_fill == 6) {
492 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800493 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700494 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800495 }
496 }
497}
498
Elliott Hughes82914b62012-04-09 15:56:29 -0700499std::string PrintableString(const std::string& utf) {
500 std::string result;
501 result += '"';
502 const char* p = utf.c_str();
503 size_t char_count = CountModifiedUtf8Chars(p);
504 for (size_t i = 0; i < char_count; ++i) {
505 uint16_t ch = GetUtf16FromUtf8(&p);
506 if (ch == '\\') {
507 result += "\\\\";
508 } else if (ch == '\n') {
509 result += "\\n";
510 } else if (ch == '\r') {
511 result += "\\r";
512 } else if (ch == '\t') {
513 result += "\\t";
514 } else if (NeedsEscaping(ch)) {
515 StringAppendF(&result, "\\u%04x", ch);
516 } else {
517 result += ch;
518 }
519 }
520 result += '"';
521 return result;
522}
523
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800524// 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 -0700525std::string MangleForJni(const std::string& s) {
526 std::string result;
527 size_t char_count = CountModifiedUtf8Chars(s.c_str());
528 const char* cp = &s[0];
529 for (size_t i = 0; i < char_count; ++i) {
530 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800531 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
532 result.push_back(ch);
533 } else if (ch == '.' || ch == '/') {
534 result += "_";
535 } else if (ch == '_') {
536 result += "_1";
537 } else if (ch == ';') {
538 result += "_2";
539 } else if (ch == '[') {
540 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700541 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800542 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700543 }
544 }
545 return result;
546}
547
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700548std::string DotToDescriptor(const char* class_name) {
549 std::string descriptor(class_name);
550 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
551 if (descriptor.length() > 0 && descriptor[0] != '[') {
552 descriptor = "L" + descriptor + ";";
553 }
554 return descriptor;
555}
556
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800557std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800558 size_t length = strlen(descriptor);
559 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
560 std::string result(descriptor + 1, length - 2);
561 std::replace(result.begin(), result.end(), '/', '.');
562 return result;
563 }
564 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800565}
566
567std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800568 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800569 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
570 std::string result(descriptor + 1, length - 2);
571 return result;
572 }
573 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700574}
575
Mathieu Chartier66f19252012-09-18 08:57:04 -0700576std::string JniShortName(const AbstractMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800577 MethodHelper mh(m);
578 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700579 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700580 CHECK_EQ(class_name[0], 'L') << class_name;
581 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700582 class_name.erase(0, 1);
583 class_name.erase(class_name.size() - 1, 1);
584
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800585 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700586
587 std::string short_name;
588 short_name += "Java_";
589 short_name += MangleForJni(class_name);
590 short_name += "_";
591 short_name += MangleForJni(method_name);
592 return short_name;
593}
594
Mathieu Chartier66f19252012-09-18 08:57:04 -0700595std::string JniLongName(const AbstractMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700596 std::string long_name;
597 long_name += JniShortName(m);
598 long_name += "__";
599
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800600 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700601 signature.erase(0, 1);
602 signature.erase(signature.begin() + signature.find(')'), signature.end());
603
604 long_name += MangleForJni(signature);
605
606 return long_name;
607}
608
jeffhao10037c82012-01-23 15:06:23 -0800609// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700610uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
611 0x00000000, // 00..1f low control characters; nothing valid
612 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
613 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
614 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
615};
616
jeffhao10037c82012-01-23 15:06:23 -0800617// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
618bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700619 /*
620 * It's a multibyte encoded character. Decode it and analyze. We
621 * accept anything that isn't (a) an improperly encoded low value,
622 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
623 * control character, or (e) a high space, layout, or special
624 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
625 * U+fff0..U+ffff). This is all specified in the dex format
626 * document.
627 */
628
629 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
630
631 // Perform follow-up tests based on the high 8 bits.
632 switch (utf16 >> 8) {
633 case 0x00:
634 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
635 return (utf16 > 0x00a0);
636 case 0xd8:
637 case 0xd9:
638 case 0xda:
639 case 0xdb:
640 // It's a leading surrogate. Check to see that a trailing
641 // surrogate follows.
642 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
643 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
644 case 0xdc:
645 case 0xdd:
646 case 0xde:
647 case 0xdf:
648 // It's a trailing surrogate, which is not valid at this point.
649 return false;
650 case 0x20:
651 case 0xff:
652 // It's in the range that has spaces, controls, and specials.
653 switch (utf16 & 0xfff8) {
654 case 0x2000:
655 case 0x2008:
656 case 0x2028:
657 case 0xfff0:
658 case 0xfff8:
659 return false;
660 }
661 break;
662 }
663 return true;
664}
665
666/* Return whether the pointed-at modified-UTF-8 encoded character is
667 * valid as part of a member name, updating the pointer to point past
668 * the consumed character. This will consume two encoded UTF-16 code
669 * points if the character is encoded as a surrogate pair. Also, if
670 * this function returns false, then the given pointer may only have
671 * been partially advanced.
672 */
jeffhao10037c82012-01-23 15:06:23 -0800673bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700674 uint8_t c = (uint8_t) **pUtf8Ptr;
675 if (c <= 0x7f) {
676 // It's low-ascii, so check the table.
677 uint32_t wordIdx = c >> 5;
678 uint32_t bitIdx = c & 0x1f;
679 (*pUtf8Ptr)++;
680 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
681 }
682
683 // It's a multibyte encoded character. Call a non-inline function
684 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800685 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
686}
687
688bool IsValidMemberName(const char* s) {
689 bool angle_name = false;
690
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700691 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800692 case '\0':
693 // The empty string is not a valid name.
694 return false;
695 case '<':
696 angle_name = true;
697 s++;
698 break;
699 }
700
701 while (true) {
702 switch (*s) {
703 case '\0':
704 return !angle_name;
705 case '>':
706 return angle_name && s[1] == '\0';
707 }
708
709 if (!IsValidPartOfMemberNameUtf8(&s)) {
710 return false;
711 }
712 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700713}
714
Elliott Hughes906e6852011-10-28 14:52:10 -0700715enum ClassNameType { kName, kDescriptor };
716bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700717 int arrayCount = 0;
718 while (*s == '[') {
719 arrayCount++;
720 s++;
721 }
722
723 if (arrayCount > 255) {
724 // Arrays may have no more than 255 dimensions.
725 return false;
726 }
727
728 if (arrayCount != 0) {
729 /*
730 * If we're looking at an array of some sort, then it doesn't
731 * matter if what is being asked for is a class name; the
732 * format looks the same as a type descriptor in that case, so
733 * treat it as such.
734 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700735 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700736 }
737
Elliott Hughes906e6852011-10-28 14:52:10 -0700738 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700739 /*
740 * We are looking for a descriptor. Either validate it as a
741 * single-character primitive type, or continue on to check the
742 * embedded class name (bracketed by "L" and ";").
743 */
744 switch (*(s++)) {
745 case 'B':
746 case 'C':
747 case 'D':
748 case 'F':
749 case 'I':
750 case 'J':
751 case 'S':
752 case 'Z':
753 // These are all single-character descriptors for primitive types.
754 return (*s == '\0');
755 case 'V':
756 // Non-array void is valid, but you can't have an array of void.
757 return (arrayCount == 0) && (*s == '\0');
758 case 'L':
759 // Class name: Break out and continue below.
760 break;
761 default:
762 // Oddball descriptor character.
763 return false;
764 }
765 }
766
767 /*
768 * We just consumed the 'L' that introduces a class name as part
769 * of a type descriptor, or we are looking for an unadorned class
770 * name.
771 */
772
773 bool sepOrFirst = true; // first character or just encountered a separator.
774 for (;;) {
775 uint8_t c = (uint8_t) *s;
776 switch (c) {
777 case '\0':
778 /*
779 * Premature end for a type descriptor, but valid for
780 * a class name as long as we haven't encountered an
781 * empty component (including the degenerate case of
782 * the empty string "").
783 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700784 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700785 case ';':
786 /*
787 * Invalid character for a class name, but the
788 * legitimate end of a type descriptor. In the latter
789 * case, make sure that this is the end of the string
790 * and that it doesn't end with an empty component
791 * (including the degenerate case of "L;").
792 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700793 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700794 case '/':
795 case '.':
796 if (c != separator) {
797 // The wrong separator character.
798 return false;
799 }
800 if (sepOrFirst) {
801 // Separator at start or two separators in a row.
802 return false;
803 }
804 sepOrFirst = true;
805 s++;
806 break;
807 default:
jeffhao10037c82012-01-23 15:06:23 -0800808 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700809 return false;
810 }
811 sepOrFirst = false;
812 break;
813 }
814 }
815}
816
Elliott Hughes906e6852011-10-28 14:52:10 -0700817bool IsValidBinaryClassName(const char* s) {
818 return IsValidClassName(s, kName, '.');
819}
820
821bool IsValidJniClassName(const char* s) {
822 return IsValidClassName(s, kName, '/');
823}
824
825bool IsValidDescriptor(const char* s) {
826 return IsValidClassName(s, kDescriptor, '/');
827}
828
Elliott Hughes48436bb2012-02-07 15:23:28 -0800829void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700830 const char* p = s.data();
831 const char* end = p + s.size();
832 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800833 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700834 ++p;
835 } else {
836 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800837 while (++p != end && *p != separator) {
838 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700839 }
840 result.push_back(std::string(start, p - start));
841 }
842 }
843}
844
Elliott Hughes48436bb2012-02-07 15:23:28 -0800845template <typename StringT>
846std::string Join(std::vector<StringT>& strings, char separator) {
847 if (strings.empty()) {
848 return "";
849 }
850
851 std::string result(strings[0]);
852 for (size_t i = 1; i < strings.size(); ++i) {
853 result += separator;
854 result += strings[i];
855 }
856 return result;
857}
858
859// Explicit instantiations.
860template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
861template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
862template std::string Join<char*>(std::vector<char*>& strings, char separator);
863
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800864bool StartsWith(const std::string& s, const char* prefix) {
865 return s.compare(0, strlen(prefix), prefix) == 0;
866}
867
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700868bool EndsWith(const std::string& s, const char* suffix) {
869 size_t suffix_length = strlen(suffix);
870 size_t string_length = s.size();
871 if (suffix_length > string_length) {
872 return false;
873 }
874 size_t offset = string_length - suffix_length;
875 return s.compare(offset, suffix_length, suffix) == 0;
876}
877
Elliott Hughes22869a92012-03-27 14:08:24 -0700878void SetThreadName(const char* thread_name) {
879 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800880
Elliott Hughesdcc24742011-09-07 14:02:44 -0700881 int hasAt = 0;
882 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700883 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700884 while (*s) {
885 if (*s == '.') {
886 hasDot = 1;
887 } else if (*s == '@') {
888 hasAt = 1;
889 }
890 s++;
891 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700892 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700893 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700894 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700895 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700896 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700897 }
898#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700899 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700900 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
901 strncpy(buf, s, sizeof(buf)-1);
902 buf[sizeof(buf)-1] = '\0';
903 errno = pthread_setname_np(pthread_self(), buf);
904 if (errno != 0) {
905 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
906 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700907#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700908 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700909#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700910 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700911#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700912 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700913#endif
914}
915
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700916void GetTaskStats(pid_t tid, char& state, int& utime, int& stime, int& task_cpu) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700917 utime = stime = task_cpu = 0;
918 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700919 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700920 return;
921 }
922 // Skip the command, which may contain spaces.
923 stats = stats.substr(stats.find(')') + 2);
924 // Extract the three fields we care about.
925 std::vector<std::string> fields;
926 Split(stats, ' ', fields);
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700927 state = fields[0][0];
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700928 utime = strtoull(fields[11].c_str(), NULL, 10);
929 stime = strtoull(fields[12].c_str(), NULL, 10);
930 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
931}
932
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700933std::string GetSchedulerGroupName(pid_t tid) {
934 // /proc/<pid>/cgroup looks like this:
935 // 2:devices:/
936 // 1:cpuacct,cpu:/
937 // We want the third field from the line whose second field contains the "cpu" token.
938 std::string cgroup_file;
939 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
940 return "";
941 }
942 std::vector<std::string> cgroup_lines;
943 Split(cgroup_file, '\n', cgroup_lines);
944 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
945 std::vector<std::string> cgroup_fields;
946 Split(cgroup_lines[i], ':', cgroup_fields);
947 std::vector<std::string> cgroups;
948 Split(cgroup_fields[1], ',', cgroups);
949 for (size_t i = 0; i < cgroups.size(); ++i) {
950 if (cgroups[i] == "cpu") {
951 return cgroup_fields[2].substr(1); // Skip the leading slash.
952 }
953 }
954 }
955 return "";
956}
957
Elliott Hughes46e251b2012-05-22 15:10:45 -0700958static const char* CleanMapName(const backtrace_symbol_t* symbol) {
959 const char* map_name = symbol->map_name;
960 if (map_name == NULL) {
961 map_name = "???";
962 }
963 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
964 // into "libartd.so".
965 const char* last_slash = strrchr(map_name, '/');
966 if (last_slash != NULL) {
967 map_name = last_slash + 1;
968 }
969 return map_name;
970}
971
972static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
973 std::string& symbol_name, uint32_t& pc_offset) {
974 symbol_table_t* symbol_table = NULL;
975 if (symbol->map_name != NULL) {
976 symbol_table = load_symbol_table(symbol->map_name);
977 }
978 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -0700979 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700980 if (symbol_table != NULL) {
981 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
982 if (elf_symbol == NULL) {
983 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -0700984 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700985 }
986 }
987 if (elf_symbol != NULL) {
988 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
989 if (demangled_symbol_name != NULL) {
990 symbol_name = demangled_symbol_name;
991 } else {
992 symbol_name = elf_symbol->name;
993 }
Elliott Hughes95aff772012-06-12 17:44:15 -0700994
995 // TODO: is it a libcorkscrew bug that we have to do this?
996 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -0700997 } else {
998 symbol_name = "???";
999 }
1000 free_symbol_table(symbol_table);
1001}
1002
1003void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001004 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1005 flush_my_map_info_list();
1006
Elliott Hughes46e251b2012-05-22 15:10:45 -07001007 const size_t MAX_DEPTH = 32;
1008 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001009 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
1010 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001011 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001012 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001013 return;
1014 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001015 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001016 return;
1017 }
1018
1019 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1020 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1021
1022 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1023 const backtrace_frame_t* frame = &frames[i];
1024 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1025
1026 // We produce output like this:
1027 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1028
1029 std::string symbol_name;
1030 uint32_t pc_offset = 0;
1031 if (symbol->demangled_name != NULL) {
1032 symbol_name = symbol->demangled_name;
1033 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1034 } else if (symbol->symbol_name != NULL) {
1035 symbol_name = symbol->symbol_name;
1036 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1037 } else {
1038 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1039 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1040 }
1041
1042 os << prefix;
1043 if (include_count) {
1044 os << StringPrintf("#%02zd ", i);
1045 }
1046 os << symbol_name;
1047 if (pc_offset != 0) {
1048 os << "+" << pc_offset;
1049 }
1050 os << StringPrintf(" [%p] (%s)\n",
1051 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1052 }
1053
1054 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1055}
1056
Elliott Hughes058a6de2012-05-24 19:13:02 -07001057#if defined(__APPLE__)
1058
1059// TODO: is there any way to get the kernel stack on Mac OS?
1060void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1061
1062#else
1063
Elliott Hughes46e251b2012-05-22 15:10:45 -07001064void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001065 if (tid == GetTid()) {
1066 // There's no point showing that we're reading our stack out of /proc!
1067 return;
1068 }
1069
Elliott Hughes46e251b2012-05-22 15:10:45 -07001070 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1071 std::string kernel_stack;
1072 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001073 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001074 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001075 }
1076
1077 std::vector<std::string> kernel_stack_frames;
1078 Split(kernel_stack, '\n', kernel_stack_frames);
1079 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1080 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1081 kernel_stack_frames.pop_back();
1082 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1083 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1084 const char* text = kernel_stack_frames[i].c_str();
1085 const char* close_bracket = strchr(text, ']');
1086 if (close_bracket != NULL) {
1087 text = close_bracket + 2;
1088 }
1089 os << prefix;
1090 if (include_count) {
1091 os << StringPrintf("#%02zd ", i);
1092 }
1093 os << text << "\n";
1094 }
1095}
1096
1097#endif
1098
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001099const char* GetAndroidRoot() {
1100 const char* android_root = getenv("ANDROID_ROOT");
1101 if (android_root == NULL) {
1102 if (OS::DirectoryExists("/system")) {
1103 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001104 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001105 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1106 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001107 }
1108 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001109 if (!OS::DirectoryExists(android_root)) {
1110 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001111 return "";
1112 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001113 return android_root;
1114}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001115
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001116const char* GetAndroidData() {
1117 const char* android_data = getenv("ANDROID_DATA");
1118 if (android_data == NULL) {
1119 if (OS::DirectoryExists("/data")) {
1120 android_data = "/data";
1121 } else {
1122 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1123 return "";
1124 }
1125 }
1126 if (!OS::DirectoryExists(android_data)) {
1127 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1128 return "";
1129 }
1130 return android_data;
1131}
1132
Shih-wei Liao795e3302012-04-21 00:20:57 -07001133std::string GetArtCacheOrDie(const char* android_data) {
1134 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001135
1136 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001137 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001138 int result = mkdir(art_cache.c_str(), 0700);
1139 if (result != 0) {
1140 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1141 return "";
1142 }
1143 } else {
1144 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1145 return "";
1146 }
1147 }
1148 return art_cache;
1149}
1150
jeffhao262bf462011-10-20 18:36:32 -07001151std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001152 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001153 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001154 std::string cache_file(location, 1); // skip leading slash
1155 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1156 return art_cache + "/" + cache_file;
1157}
1158
jeffhao262bf462011-10-20 18:36:32 -07001159bool IsValidZipFilename(const std::string& filename) {
1160 if (filename.size() < 4) {
1161 return false;
1162 }
1163 std::string suffix(filename.substr(filename.size() - 4));
1164 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1165}
1166
1167bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001168 return EndsWith(filename, ".dex");
1169}
1170
1171bool IsValidOatFilename(const std::string& filename) {
1172 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001173}
1174
Elliott Hughes42ee1422011-09-06 12:33:32 -07001175} // namespace art