blob: 50db7fa33a8ac26a735865f583593fb592405488 [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"
Elliott Hughes76160052012-12-12 16:31:20 -080027#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070028#include "dex_file-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "mirror/abstract_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "mirror/class_loader.h"
32#include "mirror/field.h"
33#include "mirror/field-inl.h"
34#include "mirror/object-inl.h"
35#include "mirror/object_array-inl.h"
36#include "mirror/string.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080037#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070038#include "os.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "utf.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070040
Elliott Hughesad6c9c32012-01-19 17:39:12 -080041#if !defined(HAVE_POSIX_CLOCKS)
42#include <sys/time.h>
43#endif
44
Elliott Hughesdcc24742011-09-07 14:02:44 -070045#if defined(HAVE_PRCTL)
46#include <sys/prctl.h>
47#endif
48
Elliott Hughes4ae722a2012-03-13 11:08:51 -070049#if defined(__APPLE__)
Elliott Hughesb08e8a32012-04-02 10:51:41 -070050#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070051#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070052#endif
53
Elliott Hughes46e251b2012-05-22 15:10:45 -070054#include <corkscrew/backtrace.h> // For DumpNativeStack.
55#include <corkscrew/demangle.h> // For DumpNativeStack.
56
Elliott Hughes058a6de2012-05-24 19:13:02 -070057#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080058#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080059#endif
60
Elliott Hughes11e45072011-08-16 17:40:46 -070061namespace art {
62
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080063pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070064#if defined(__APPLE__)
65 uint64_t owner;
66 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
67 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080068#else
69 // Neither bionic nor glibc exposes gettid(2).
70 return syscall(__NR_gettid);
71#endif
72}
73
Elliott Hughes289be852012-06-12 13:57:20 -070074std::string GetThreadName(pid_t tid) {
75 std::string result;
76 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
77 result.resize(result.size() - 1); // Lose the trailing '\n'.
78 } else {
79 result = "<unknown>";
80 }
81 return result;
82}
83
Ian Rogers120f1c72012-09-28 17:17:10 -070084void GetThreadStack(pthread_t thread, void*& stack_base, size_t& stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070085#if defined(__APPLE__)
Ian Rogers120f1c72012-09-28 17:17:10 -070086 stack_size = pthread_get_stacksize_np(thread);
87 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070088
89 // Check whether stack_addr is the base or end of the stack.
90 // (On Mac OS 10.7, it's the end.)
91 int stack_variable;
92 if (stack_addr > &stack_variable) {
93 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
94 } else {
95 stack_base = stack_addr;
96 }
97#else
98 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070099 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700100 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
101 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
102#endif
103}
104
Elliott Hughesd92bec42011-09-02 17:04:36 -0700105bool ReadFileToString(const std::string& file_name, std::string* result) {
Elliott Hughes76160052012-12-12 16:31:20 -0800106 UniquePtr<File> file(new File);
107 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700108 return false;
109 }
buzbeec143c552011-08-20 17:38:58 -0700110
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700111 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700112 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800113 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700114 if (n == -1) {
115 return false;
buzbeec143c552011-08-20 17:38:58 -0700116 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700117 if (n == 0) {
118 return true;
119 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700120 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700121 }
buzbeec143c552011-08-20 17:38:58 -0700122}
123
Elliott Hughese27955c2011-08-26 15:21:24 -0700124std::string GetIsoDate() {
125 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700126 tm tmbuf;
127 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700128 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
129 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
130 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
131}
132
Elliott Hughes7162ad92011-10-27 14:08:42 -0700133uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800134#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700135 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700136 clock_gettime(CLOCK_MONOTONIC, &now);
137 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
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);
141 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
142#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700143}
144
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800145uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800146#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700147 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800148 clock_gettime(CLOCK_MONOTONIC, &now);
149 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
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);
TDYa12754825032012-04-11 10:45:23 -0700153 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800155}
156
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700157uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800158#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700159 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700160 clock_gettime(CLOCK_MONOTONIC, &now);
161 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700163 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800164 gettimeofday(&now, NULL);
165 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
166#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700167}
168
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800169uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800170#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700171 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800172 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
173 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800174#else
175 UNIMPLEMENTED(WARNING);
176 return -1;
177#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800178}
179
Elliott Hughes0512f022012-03-15 22:10:52 -0700180uint64_t ThreadCpuNanoTime() {
181#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700182 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700183 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
184 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
185#else
186 UNIMPLEMENTED(WARNING);
187 return -1;
188#endif
189}
190
Ian Rogers56edc432013-01-18 16:51:51 -0800191void NanoSleep(uint64_t ns) {
192 timespec tm;
193 tm.tv_sec = 0;
194 tm.tv_nsec = ns;
195 nanosleep(&tm, NULL);
196}
197
Brian Carlstrombcc29262012-11-02 11:36:03 -0700198void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
199 int64_t endSec;
200
201 if (absolute) {
202#if !defined(__APPLE__)
203 clock_gettime(clock, ts);
204#else
205 UNUSED(clock);
206 timeval tv;
207 gettimeofday(&tv, NULL);
208 ts->tv_sec = tv.tv_sec;
209 ts->tv_nsec = tv.tv_usec * 1000;
210#endif
211 } else {
212 ts->tv_sec = 0;
213 ts->tv_nsec = 0;
214 }
215 endSec = ts->tv_sec + ms / 1000;
216 if (UNLIKELY(endSec >= 0x7fffffff)) {
217 std::ostringstream ss;
218 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
219 endSec = 0x7ffffffe;
220 }
221 ts->tv_sec = endSec;
222 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
223
224 // Catch rollover.
225 if (ts->tv_nsec >= 1000000000L) {
226 ts->tv_sec++;
227 ts->tv_nsec -= 1000000000L;
228 }
229}
230
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800231std::string PrettyDescriptor(const mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700232 if (java_descriptor == NULL) {
233 return "null";
234 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700235 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
236}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700237
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800238std::string PrettyDescriptor(const mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800239 if (klass == NULL) {
240 return "null";
241 }
242 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800243}
244
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700245std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700246 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700247 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700248 size_t dim = 0;
249 while (*c == '[') {
250 dim++;
251 c++;
252 }
253
254 // Reference or primitive?
255 if (*c == 'L') {
256 // "[[La/b/C;" -> "a.b.C[][]".
257 c++; // Skip the 'L'.
258 } else {
259 // "[[B" -> "byte[][]".
260 // To make life easier, we make primitives look like unqualified
261 // reference types.
262 switch (*c) {
263 case 'B': c = "byte;"; break;
264 case 'C': c = "char;"; break;
265 case 'D': c = "double;"; break;
266 case 'F': c = "float;"; break;
267 case 'I': c = "int;"; break;
268 case 'J': c = "long;"; break;
269 case 'S': c = "short;"; break;
270 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700271 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700272 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700273 }
274 }
275
276 // At this point, 'c' is a string of the form "fully/qualified/Type;"
277 // or "primitive;". Rewrite the type with '.' instead of '/':
278 std::string result;
279 const char* p = c;
280 while (*p != ';') {
281 char ch = *p++;
282 if (ch == '/') {
283 ch = '.';
284 }
285 result.push_back(ch);
286 }
287 // ...and replace the semicolon with 'dim' "[]" pairs:
288 while (dim--) {
289 result += "[]";
290 }
291 return result;
292}
293
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700294std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800295 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700296 return PrettyDescriptor(descriptor_string);
297}
298
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800299std::string PrettyField(const mirror::Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700300 if (f == NULL) {
301 return "null";
302 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800303 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700304 std::string result;
305 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800306 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700307 result += ' ';
308 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800309 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700310 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800311 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700312 return result;
313}
314
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700315std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800316 if (field_idx >= dex_file.NumFieldIds()) {
317 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
318 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700319 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
320 std::string result;
321 if (with_type) {
322 result += dex_file.GetFieldTypeDescriptor(field_id);
323 result += ' ';
324 }
325 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
326 result += '.';
327 result += dex_file.GetFieldName(field_id);
328 return result;
329}
330
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700331std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800332 if (type_idx >= dex_file.NumTypeIds()) {
333 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
334 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700335 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700336 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700337}
338
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700339std::string PrettyArguments(const char* signature) {
340 std::string result;
341 result += '(';
342 CHECK_EQ(*signature, '(');
343 ++signature; // Skip the '('.
344 while (*signature != ')') {
345 size_t argument_length = 0;
346 while (signature[argument_length] == '[') {
347 ++argument_length;
348 }
349 if (signature[argument_length] == 'L') {
350 argument_length = (strchr(signature, ';') - signature + 1);
351 } else {
352 ++argument_length;
353 }
354 std::string argument_descriptor(signature, argument_length);
355 result += PrettyDescriptor(argument_descriptor);
356 if (signature[argument_length] != ')') {
357 result += ", ";
358 }
359 signature += argument_length;
360 }
361 CHECK_EQ(*signature, ')');
362 ++signature; // Skip the ')'.
363 result += ')';
364 return result;
365}
366
367std::string PrettyReturnType(const char* signature) {
368 const char* return_type = strchr(signature, ')');
369 CHECK(return_type != NULL);
370 ++return_type; // Skip ')'.
371 return PrettyDescriptor(return_type);
372}
373
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800374std::string PrettyMethod(const mirror::AbstractMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700375 if (m == NULL) {
376 return "null";
377 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800378 MethodHelper mh(m);
379 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700380 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800381 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700382 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700383 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700384 if (signature == "<no signature>") {
385 return result + signature;
386 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700387 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700388 }
389 return result;
390}
391
Ian Rogers0571d352011-11-03 19:51:38 -0700392std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800393 if (method_idx >= dex_file.NumMethodIds()) {
394 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
395 }
Ian Rogers0571d352011-11-03 19:51:38 -0700396 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
397 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
398 result += '.';
399 result += dex_file.GetMethodName(method_id);
400 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700401 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700402 if (signature == "<no signature>") {
403 return result + signature;
404 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700405 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700406 }
407 return result;
408}
409
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800410std::string PrettyTypeOf(const mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700411 if (obj == NULL) {
412 return "null";
413 }
414 if (obj->GetClass() == NULL) {
415 return "(raw)";
416 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800417 ClassHelper kh(obj->GetClass());
418 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700419 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800420 kh.ChangeClass(obj->AsClass());
421 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700422 }
423 return result;
424}
425
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800426std::string PrettyClass(const mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700427 if (c == NULL) {
428 return "null";
429 }
430 std::string result;
431 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800432 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700433 result += ">";
434 return result;
435}
436
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800437std::string PrettyClassAndClassLoader(const mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700438 if (c == NULL) {
439 return "null";
440 }
441 std::string result;
442 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800443 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700444 result += ",";
445 result += PrettyTypeOf(c->GetClassLoader());
446 // TODO: add an identifying hash value for the loader
447 result += ">";
448 return result;
449}
450
Elliott Hughesc967f782012-04-16 10:23:15 -0700451std::string PrettySize(size_t byte_count) {
452 // The byte thresholds at which we display amounts. A byte count is displayed
453 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
454 static const size_t kUnitThresholds[] = {
455 0, // B up to...
456 3*1024, // KB up to...
457 2*1024*1024, // MB up to...
458 1024*1024*1024 // GB from here.
459 };
460 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
461 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
462
463 int i = arraysize(kUnitThresholds);
464 while (--i > 0) {
465 if (byte_count >= kUnitThresholds[i]) {
466 break;
467 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800468 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700469
470 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800471}
472
473std::string PrettyDuration(uint64_t nano_duration) {
474 if (nano_duration == 0) {
475 return "0";
476 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700477 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
478 }
479}
480
481TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
482 const uint64_t one_sec = 1000 * 1000 * 1000;
483 const uint64_t one_ms = 1000 * 1000;
484 const uint64_t one_us = 1000;
485 if (nano_duration >= one_sec) {
486 return kTimeUnitSecond;
487 } else if (nano_duration >= one_ms) {
488 return kTimeUnitMillisecond;
489 } else if (nano_duration >= one_us) {
490 return kTimeUnitMicrosecond;
491 } else {
492 return kTimeUnitNanosecond;
493 }
494}
495
496uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
497 const uint64_t one_sec = 1000 * 1000 * 1000;
498 const uint64_t one_ms = 1000 * 1000;
499 const uint64_t one_us = 1000;
500
501 switch (time_unit) {
502 case kTimeUnitSecond:
503 return one_sec;
504 case kTimeUnitMillisecond:
505 return one_ms;
506 case kTimeUnitMicrosecond:
507 return one_us;
508 case kTimeUnitNanosecond:
509 return 1;
510 }
511 return 0;
512}
513
514std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
515 const char* unit = NULL;
516 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
517 uint32_t zero_fill = 1;
518 switch (time_unit) {
519 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800520 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800521 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700522 break;
523 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800524 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800525 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700526 break;
527 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800528 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800529 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700530 break;
531 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800532 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800533 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700534 break;
535 }
536
537 uint64_t whole_part = nano_duration / divisor;
538 uint64_t fractional_part = nano_duration % divisor;
539 if (fractional_part == 0) {
540 return StringPrintf("%llu%s", whole_part, unit);
541 } else {
542 while ((fractional_part % 1000) == 0) {
543 zero_fill -= 3;
544 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800545 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700546 if (zero_fill == 3) {
547 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
548 } else if (zero_fill == 6) {
549 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800550 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700551 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800552 }
553 }
554}
555
Elliott Hughes82914b62012-04-09 15:56:29 -0700556std::string PrintableString(const std::string& utf) {
557 std::string result;
558 result += '"';
559 const char* p = utf.c_str();
560 size_t char_count = CountModifiedUtf8Chars(p);
561 for (size_t i = 0; i < char_count; ++i) {
562 uint16_t ch = GetUtf16FromUtf8(&p);
563 if (ch == '\\') {
564 result += "\\\\";
565 } else if (ch == '\n') {
566 result += "\\n";
567 } else if (ch == '\r') {
568 result += "\\r";
569 } else if (ch == '\t') {
570 result += "\\t";
571 } else if (NeedsEscaping(ch)) {
572 StringAppendF(&result, "\\u%04x", ch);
573 } else {
574 result += ch;
575 }
576 }
577 result += '"';
578 return result;
579}
580
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800581// 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 -0700582std::string MangleForJni(const std::string& s) {
583 std::string result;
584 size_t char_count = CountModifiedUtf8Chars(s.c_str());
585 const char* cp = &s[0];
586 for (size_t i = 0; i < char_count; ++i) {
587 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800588 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
589 result.push_back(ch);
590 } else if (ch == '.' || ch == '/') {
591 result += "_";
592 } else if (ch == '_') {
593 result += "_1";
594 } else if (ch == ';') {
595 result += "_2";
596 } else if (ch == '[') {
597 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700598 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800599 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700600 }
601 }
602 return result;
603}
604
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700605std::string DotToDescriptor(const char* class_name) {
606 std::string descriptor(class_name);
607 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
608 if (descriptor.length() > 0 && descriptor[0] != '[') {
609 descriptor = "L" + descriptor + ";";
610 }
611 return descriptor;
612}
613
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800614std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800615 size_t length = strlen(descriptor);
616 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
617 std::string result(descriptor + 1, length - 2);
618 std::replace(result.begin(), result.end(), '/', '.');
619 return result;
620 }
621 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800622}
623
624std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800625 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800626 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
627 std::string result(descriptor + 1, length - 2);
628 return result;
629 }
630 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700631}
632
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800633std::string JniShortName(const mirror::AbstractMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800634 MethodHelper mh(m);
635 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700636 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700637 CHECK_EQ(class_name[0], 'L') << class_name;
638 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700639 class_name.erase(0, 1);
640 class_name.erase(class_name.size() - 1, 1);
641
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800642 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700643
644 std::string short_name;
645 short_name += "Java_";
646 short_name += MangleForJni(class_name);
647 short_name += "_";
648 short_name += MangleForJni(method_name);
649 return short_name;
650}
651
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800652std::string JniLongName(const mirror::AbstractMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700653 std::string long_name;
654 long_name += JniShortName(m);
655 long_name += "__";
656
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800657 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700658 signature.erase(0, 1);
659 signature.erase(signature.begin() + signature.find(')'), signature.end());
660
661 long_name += MangleForJni(signature);
662
663 return long_name;
664}
665
jeffhao10037c82012-01-23 15:06:23 -0800666// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700667uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
668 0x00000000, // 00..1f low control characters; nothing valid
669 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
670 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
671 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
672};
673
jeffhao10037c82012-01-23 15:06:23 -0800674// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
675bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700676 /*
677 * It's a multibyte encoded character. Decode it and analyze. We
678 * accept anything that isn't (a) an improperly encoded low value,
679 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
680 * control character, or (e) a high space, layout, or special
681 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
682 * U+fff0..U+ffff). This is all specified in the dex format
683 * document.
684 */
685
686 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
687
688 // Perform follow-up tests based on the high 8 bits.
689 switch (utf16 >> 8) {
690 case 0x00:
691 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
692 return (utf16 > 0x00a0);
693 case 0xd8:
694 case 0xd9:
695 case 0xda:
696 case 0xdb:
697 // It's a leading surrogate. Check to see that a trailing
698 // surrogate follows.
699 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
700 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
701 case 0xdc:
702 case 0xdd:
703 case 0xde:
704 case 0xdf:
705 // It's a trailing surrogate, which is not valid at this point.
706 return false;
707 case 0x20:
708 case 0xff:
709 // It's in the range that has spaces, controls, and specials.
710 switch (utf16 & 0xfff8) {
711 case 0x2000:
712 case 0x2008:
713 case 0x2028:
714 case 0xfff0:
715 case 0xfff8:
716 return false;
717 }
718 break;
719 }
720 return true;
721}
722
723/* Return whether the pointed-at modified-UTF-8 encoded character is
724 * valid as part of a member name, updating the pointer to point past
725 * the consumed character. This will consume two encoded UTF-16 code
726 * points if the character is encoded as a surrogate pair. Also, if
727 * this function returns false, then the given pointer may only have
728 * been partially advanced.
729 */
jeffhao10037c82012-01-23 15:06:23 -0800730bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700731 uint8_t c = (uint8_t) **pUtf8Ptr;
732 if (c <= 0x7f) {
733 // It's low-ascii, so check the table.
734 uint32_t wordIdx = c >> 5;
735 uint32_t bitIdx = c & 0x1f;
736 (*pUtf8Ptr)++;
737 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
738 }
739
740 // It's a multibyte encoded character. Call a non-inline function
741 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800742 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
743}
744
745bool IsValidMemberName(const char* s) {
746 bool angle_name = false;
747
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700748 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800749 case '\0':
750 // The empty string is not a valid name.
751 return false;
752 case '<':
753 angle_name = true;
754 s++;
755 break;
756 }
757
758 while (true) {
759 switch (*s) {
760 case '\0':
761 return !angle_name;
762 case '>':
763 return angle_name && s[1] == '\0';
764 }
765
766 if (!IsValidPartOfMemberNameUtf8(&s)) {
767 return false;
768 }
769 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700770}
771
Elliott Hughes906e6852011-10-28 14:52:10 -0700772enum ClassNameType { kName, kDescriptor };
773bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700774 int arrayCount = 0;
775 while (*s == '[') {
776 arrayCount++;
777 s++;
778 }
779
780 if (arrayCount > 255) {
781 // Arrays may have no more than 255 dimensions.
782 return false;
783 }
784
785 if (arrayCount != 0) {
786 /*
787 * If we're looking at an array of some sort, then it doesn't
788 * matter if what is being asked for is a class name; the
789 * format looks the same as a type descriptor in that case, so
790 * treat it as such.
791 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700792 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700793 }
794
Elliott Hughes906e6852011-10-28 14:52:10 -0700795 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700796 /*
797 * We are looking for a descriptor. Either validate it as a
798 * single-character primitive type, or continue on to check the
799 * embedded class name (bracketed by "L" and ";").
800 */
801 switch (*(s++)) {
802 case 'B':
803 case 'C':
804 case 'D':
805 case 'F':
806 case 'I':
807 case 'J':
808 case 'S':
809 case 'Z':
810 // These are all single-character descriptors for primitive types.
811 return (*s == '\0');
812 case 'V':
813 // Non-array void is valid, but you can't have an array of void.
814 return (arrayCount == 0) && (*s == '\0');
815 case 'L':
816 // Class name: Break out and continue below.
817 break;
818 default:
819 // Oddball descriptor character.
820 return false;
821 }
822 }
823
824 /*
825 * We just consumed the 'L' that introduces a class name as part
826 * of a type descriptor, or we are looking for an unadorned class
827 * name.
828 */
829
830 bool sepOrFirst = true; // first character or just encountered a separator.
831 for (;;) {
832 uint8_t c = (uint8_t) *s;
833 switch (c) {
834 case '\0':
835 /*
836 * Premature end for a type descriptor, but valid for
837 * a class name as long as we haven't encountered an
838 * empty component (including the degenerate case of
839 * the empty string "").
840 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700841 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700842 case ';':
843 /*
844 * Invalid character for a class name, but the
845 * legitimate end of a type descriptor. In the latter
846 * case, make sure that this is the end of the string
847 * and that it doesn't end with an empty component
848 * (including the degenerate case of "L;").
849 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700850 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700851 case '/':
852 case '.':
853 if (c != separator) {
854 // The wrong separator character.
855 return false;
856 }
857 if (sepOrFirst) {
858 // Separator at start or two separators in a row.
859 return false;
860 }
861 sepOrFirst = true;
862 s++;
863 break;
864 default:
jeffhao10037c82012-01-23 15:06:23 -0800865 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700866 return false;
867 }
868 sepOrFirst = false;
869 break;
870 }
871 }
872}
873
Elliott Hughes906e6852011-10-28 14:52:10 -0700874bool IsValidBinaryClassName(const char* s) {
875 return IsValidClassName(s, kName, '.');
876}
877
878bool IsValidJniClassName(const char* s) {
879 return IsValidClassName(s, kName, '/');
880}
881
882bool IsValidDescriptor(const char* s) {
883 return IsValidClassName(s, kDescriptor, '/');
884}
885
Elliott Hughes48436bb2012-02-07 15:23:28 -0800886void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700887 const char* p = s.data();
888 const char* end = p + s.size();
889 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800890 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700891 ++p;
892 } else {
893 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800894 while (++p != end && *p != separator) {
895 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700896 }
897 result.push_back(std::string(start, p - start));
898 }
899 }
900}
901
Elliott Hughes48436bb2012-02-07 15:23:28 -0800902template <typename StringT>
903std::string Join(std::vector<StringT>& strings, char separator) {
904 if (strings.empty()) {
905 return "";
906 }
907
908 std::string result(strings[0]);
909 for (size_t i = 1; i < strings.size(); ++i) {
910 result += separator;
911 result += strings[i];
912 }
913 return result;
914}
915
916// Explicit instantiations.
917template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
918template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
919template std::string Join<char*>(std::vector<char*>& strings, char separator);
920
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800921bool StartsWith(const std::string& s, const char* prefix) {
922 return s.compare(0, strlen(prefix), prefix) == 0;
923}
924
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700925bool EndsWith(const std::string& s, const char* suffix) {
926 size_t suffix_length = strlen(suffix);
927 size_t string_length = s.size();
928 if (suffix_length > string_length) {
929 return false;
930 }
931 size_t offset = string_length - suffix_length;
932 return s.compare(offset, suffix_length, suffix) == 0;
933}
934
Elliott Hughes22869a92012-03-27 14:08:24 -0700935void SetThreadName(const char* thread_name) {
936 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800937
Elliott Hughesdcc24742011-09-07 14:02:44 -0700938 int hasAt = 0;
939 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700940 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700941 while (*s) {
942 if (*s == '.') {
943 hasDot = 1;
944 } else if (*s == '@') {
945 hasAt = 1;
946 }
947 s++;
948 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700949 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700950 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700951 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700952 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700953 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700954 }
955#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700956 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700957 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
958 strncpy(buf, s, sizeof(buf)-1);
959 buf[sizeof(buf)-1] = '\0';
960 errno = pthread_setname_np(pthread_self(), buf);
961 if (errno != 0) {
962 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
963 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700964#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700965 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700966#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700967 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700968#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700969 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700970#endif
971}
972
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700973void GetTaskStats(pid_t tid, char& state, int& utime, int& stime, int& task_cpu) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700974 utime = stime = task_cpu = 0;
975 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700976 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700977 return;
978 }
979 // Skip the command, which may contain spaces.
980 stats = stats.substr(stats.find(')') + 2);
981 // Extract the three fields we care about.
982 std::vector<std::string> fields;
983 Split(stats, ' ', fields);
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700984 state = fields[0][0];
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700985 utime = strtoull(fields[11].c_str(), NULL, 10);
986 stime = strtoull(fields[12].c_str(), NULL, 10);
987 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
988}
989
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700990std::string GetSchedulerGroupName(pid_t tid) {
991 // /proc/<pid>/cgroup looks like this:
992 // 2:devices:/
993 // 1:cpuacct,cpu:/
994 // We want the third field from the line whose second field contains the "cpu" token.
995 std::string cgroup_file;
996 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
997 return "";
998 }
999 std::vector<std::string> cgroup_lines;
1000 Split(cgroup_file, '\n', cgroup_lines);
1001 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1002 std::vector<std::string> cgroup_fields;
1003 Split(cgroup_lines[i], ':', cgroup_fields);
1004 std::vector<std::string> cgroups;
1005 Split(cgroup_fields[1], ',', cgroups);
1006 for (size_t i = 0; i < cgroups.size(); ++i) {
1007 if (cgroups[i] == "cpu") {
1008 return cgroup_fields[2].substr(1); // Skip the leading slash.
1009 }
1010 }
1011 }
1012 return "";
1013}
1014
Elliott Hughes46e251b2012-05-22 15:10:45 -07001015static const char* CleanMapName(const backtrace_symbol_t* symbol) {
1016 const char* map_name = symbol->map_name;
1017 if (map_name == NULL) {
1018 map_name = "???";
1019 }
1020 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1021 // into "libartd.so".
1022 const char* last_slash = strrchr(map_name, '/');
1023 if (last_slash != NULL) {
1024 map_name = last_slash + 1;
1025 }
1026 return map_name;
1027}
1028
1029static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
1030 std::string& symbol_name, uint32_t& pc_offset) {
1031 symbol_table_t* symbol_table = NULL;
1032 if (symbol->map_name != NULL) {
1033 symbol_table = load_symbol_table(symbol->map_name);
1034 }
1035 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -07001036 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001037 if (symbol_table != NULL) {
1038 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
1039 if (elf_symbol == NULL) {
1040 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -07001041 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001042 }
1043 }
1044 if (elf_symbol != NULL) {
1045 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
1046 if (demangled_symbol_name != NULL) {
1047 symbol_name = demangled_symbol_name;
1048 } else {
1049 symbol_name = elf_symbol->name;
1050 }
Elliott Hughes95aff772012-06-12 17:44:15 -07001051
1052 // TODO: is it a libcorkscrew bug that we have to do this?
1053 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001054 } else {
1055 symbol_name = "???";
1056 }
1057 free_symbol_table(symbol_table);
1058}
1059
1060void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001061 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1062 flush_my_map_info_list();
1063
Elliott Hughes46e251b2012-05-22 15:10:45 -07001064 const size_t MAX_DEPTH = 32;
1065 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001066 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
1067 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001068 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001069 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001070 return;
1071 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001072 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001073 return;
1074 }
1075
1076 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1077 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1078
1079 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1080 const backtrace_frame_t* frame = &frames[i];
1081 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1082
1083 // We produce output like this:
1084 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1085
1086 std::string symbol_name;
1087 uint32_t pc_offset = 0;
1088 if (symbol->demangled_name != NULL) {
1089 symbol_name = symbol->demangled_name;
1090 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1091 } else if (symbol->symbol_name != NULL) {
1092 symbol_name = symbol->symbol_name;
1093 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1094 } else {
1095 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1096 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1097 }
1098
1099 os << prefix;
1100 if (include_count) {
1101 os << StringPrintf("#%02zd ", i);
1102 }
1103 os << symbol_name;
1104 if (pc_offset != 0) {
1105 os << "+" << pc_offset;
1106 }
1107 os << StringPrintf(" [%p] (%s)\n",
1108 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1109 }
1110
1111 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1112}
1113
Elliott Hughes058a6de2012-05-24 19:13:02 -07001114#if defined(__APPLE__)
1115
1116// TODO: is there any way to get the kernel stack on Mac OS?
1117void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1118
1119#else
1120
Elliott Hughes46e251b2012-05-22 15:10:45 -07001121void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001122 if (tid == GetTid()) {
1123 // There's no point showing that we're reading our stack out of /proc!
1124 return;
1125 }
1126
Elliott Hughes46e251b2012-05-22 15:10:45 -07001127 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1128 std::string kernel_stack;
1129 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001130 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001131 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001132 }
1133
1134 std::vector<std::string> kernel_stack_frames;
1135 Split(kernel_stack, '\n', kernel_stack_frames);
1136 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1137 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1138 kernel_stack_frames.pop_back();
1139 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1140 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1141 const char* text = kernel_stack_frames[i].c_str();
1142 const char* close_bracket = strchr(text, ']');
1143 if (close_bracket != NULL) {
1144 text = close_bracket + 2;
1145 }
1146 os << prefix;
1147 if (include_count) {
1148 os << StringPrintf("#%02zd ", i);
1149 }
1150 os << text << "\n";
1151 }
1152}
1153
1154#endif
1155
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001156const char* GetAndroidRoot() {
1157 const char* android_root = getenv("ANDROID_ROOT");
1158 if (android_root == NULL) {
1159 if (OS::DirectoryExists("/system")) {
1160 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001161 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001162 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1163 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001164 }
1165 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001166 if (!OS::DirectoryExists(android_root)) {
1167 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001168 return "";
1169 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001170 return android_root;
1171}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001172
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001173const char* GetAndroidData() {
1174 const char* android_data = getenv("ANDROID_DATA");
1175 if (android_data == NULL) {
1176 if (OS::DirectoryExists("/data")) {
1177 android_data = "/data";
1178 } else {
1179 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1180 return "";
1181 }
1182 }
1183 if (!OS::DirectoryExists(android_data)) {
1184 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1185 return "";
1186 }
1187 return android_data;
1188}
1189
Shih-wei Liao795e3302012-04-21 00:20:57 -07001190std::string GetArtCacheOrDie(const char* android_data) {
1191 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001192
1193 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001194 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001195 int result = mkdir(art_cache.c_str(), 0700);
1196 if (result != 0) {
1197 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1198 return "";
1199 }
1200 } else {
1201 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1202 return "";
1203 }
1204 }
1205 return art_cache;
1206}
1207
jeffhao262bf462011-10-20 18:36:32 -07001208std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001209 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001210 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001211 std::string cache_file(location, 1); // skip leading slash
1212 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1213 return art_cache + "/" + cache_file;
1214}
1215
jeffhao262bf462011-10-20 18:36:32 -07001216bool IsValidZipFilename(const std::string& filename) {
1217 if (filename.size() < 4) {
1218 return false;
1219 }
1220 std::string suffix(filename.substr(filename.size() - 4));
1221 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1222}
1223
1224bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001225 return EndsWith(filename, ".dex");
1226}
1227
1228bool IsValidOatFilename(const std::string& filename) {
1229 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001230}
1231
Elliott Hughes42ee1422011-09-06 12:33:32 -07001232} // namespace art