blob: 71e502df298d2e74f12004c06f76bae69bad4d9d [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 Hughes92b3b562011-09-08 16:32:26 -070019#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070020#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070021#include <sys/syscall.h>
22#include <sys/types.h>
23#include <unistd.h>
24
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include "UniquePtr.h"
Elliott Hughes76160052012-12-12 16:31:20 -080026#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080028#include "mirror/abstract_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "mirror/class_loader.h"
31#include "mirror/field.h"
32#include "mirror/field-inl.h"
33#include "mirror/object-inl.h"
34#include "mirror/object_array-inl.h"
35#include "mirror/string.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080036#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070037#include "os.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "utf.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070039
Elliott Hughesad6c9c32012-01-19 17:39:12 -080040#if !defined(HAVE_POSIX_CLOCKS)
41#include <sys/time.h>
42#endif
43
Elliott Hughesdcc24742011-09-07 14:02:44 -070044#if defined(HAVE_PRCTL)
45#include <sys/prctl.h>
46#endif
47
Elliott Hughes4ae722a2012-03-13 11:08:51 -070048#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070049#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070050#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070051#endif
52
Brian Carlstrom7934ac22013-07-26 10:54:15 -070053#include <corkscrew/backtrace.h> // For DumpNativeStack.
54#include <corkscrew/demangle.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070055
Elliott Hughes058a6de2012-05-24 19:13:02 -070056#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080057#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080058#endif
59
Elliott Hughes11e45072011-08-16 17:40:46 -070060namespace art {
61
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080062pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070063#if defined(__APPLE__)
64 uint64_t owner;
65 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
66 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080067#else
68 // Neither bionic nor glibc exposes gettid(2).
69 return syscall(__NR_gettid);
70#endif
71}
72
Elliott Hughes289be852012-06-12 13:57:20 -070073std::string GetThreadName(pid_t tid) {
74 std::string result;
75 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070076 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070077 } else {
78 result = "<unknown>";
79 }
80 return result;
81}
82
Ian Rogers120f1c72012-09-28 17:17:10 -070083void GetThreadStack(pthread_t thread, void*& stack_base, size_t& stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070084#if defined(__APPLE__)
Ian Rogers120f1c72012-09-28 17:17:10 -070085 stack_size = pthread_get_stacksize_np(thread);
86 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070087
88 // Check whether stack_addr is the base or end of the stack.
89 // (On Mac OS 10.7, it's the end.)
90 int stack_variable;
91 if (stack_addr > &stack_variable) {
92 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
93 } else {
94 stack_base = stack_addr;
95 }
96#else
97 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070098 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070099 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
100 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
101#endif
102}
103
Elliott Hughesd92bec42011-09-02 17:04:36 -0700104bool ReadFileToString(const std::string& file_name, std::string* result) {
Elliott Hughes76160052012-12-12 16:31:20 -0800105 UniquePtr<File> file(new File);
106 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700107 return false;
108 }
buzbeec143c552011-08-20 17:38:58 -0700109
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700110 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700111 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800112 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700113 if (n == -1) {
114 return false;
buzbeec143c552011-08-20 17:38:58 -0700115 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700116 if (n == 0) {
117 return true;
118 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700119 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700120 }
buzbeec143c552011-08-20 17:38:58 -0700121}
122
Elliott Hughese27955c2011-08-26 15:21:24 -0700123std::string GetIsoDate() {
124 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700125 tm tmbuf;
126 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700127 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
128 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
129 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
130}
131
Elliott Hughes7162ad92011-10-27 14:08:42 -0700132uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800133#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700134 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135 clock_gettime(CLOCK_MONOTONIC, &now);
136 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800137#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700138 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800139 gettimeofday(&now, NULL);
140 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
141#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700142}
143
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800144uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800145#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700146 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147 clock_gettime(CLOCK_MONOTONIC, &now);
148 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800149#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700150 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800151 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700152 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800153#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800154}
155
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700156uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800157#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700158 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159 clock_gettime(CLOCK_MONOTONIC, &now);
160 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800161#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700162 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800163 gettimeofday(&now, NULL);
164 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
165#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700166}
167
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800168uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800169#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700170 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800171 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
172 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800173#else
174 UNIMPLEMENTED(WARNING);
175 return -1;
176#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800177}
178
Elliott Hughes0512f022012-03-15 22:10:52 -0700179uint64_t ThreadCpuNanoTime() {
180#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700181 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700182 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
183 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
184#else
185 UNIMPLEMENTED(WARNING);
186 return -1;
187#endif
188}
189
Ian Rogers56edc432013-01-18 16:51:51 -0800190void NanoSleep(uint64_t ns) {
191 timespec tm;
192 tm.tv_sec = 0;
193 tm.tv_nsec = ns;
194 nanosleep(&tm, NULL);
195}
196
Brian Carlstrombcc29262012-11-02 11:36:03 -0700197void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
198 int64_t endSec;
199
200 if (absolute) {
201#if !defined(__APPLE__)
202 clock_gettime(clock, ts);
203#else
204 UNUSED(clock);
205 timeval tv;
206 gettimeofday(&tv, NULL);
207 ts->tv_sec = tv.tv_sec;
208 ts->tv_nsec = tv.tv_usec * 1000;
209#endif
210 } else {
211 ts->tv_sec = 0;
212 ts->tv_nsec = 0;
213 }
214 endSec = ts->tv_sec + ms / 1000;
215 if (UNLIKELY(endSec >= 0x7fffffff)) {
216 std::ostringstream ss;
217 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
218 endSec = 0x7ffffffe;
219 }
220 ts->tv_sec = endSec;
221 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
222
223 // Catch rollover.
224 if (ts->tv_nsec >= 1000000000L) {
225 ts->tv_sec++;
226 ts->tv_nsec -= 1000000000L;
227 }
228}
229
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800230std::string PrettyDescriptor(const mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700231 if (java_descriptor == NULL) {
232 return "null";
233 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700234 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
235}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700236
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800237std::string PrettyDescriptor(const mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800238 if (klass == NULL) {
239 return "null";
240 }
241 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800242}
243
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700244std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700245 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700246 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700247 size_t dim = 0;
248 while (*c == '[') {
249 dim++;
250 c++;
251 }
252
253 // Reference or primitive?
254 if (*c == 'L') {
255 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700256 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700257 } else {
258 // "[[B" -> "byte[][]".
259 // To make life easier, we make primitives look like unqualified
260 // reference types.
261 switch (*c) {
262 case 'B': c = "byte;"; break;
263 case 'C': c = "char;"; break;
264 case 'D': c = "double;"; break;
265 case 'F': c = "float;"; break;
266 case 'I': c = "int;"; break;
267 case 'J': c = "long;"; break;
268 case 'S': c = "short;"; break;
269 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700270 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700271 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700272 }
273 }
274
275 // At this point, 'c' is a string of the form "fully/qualified/Type;"
276 // or "primitive;". Rewrite the type with '.' instead of '/':
277 std::string result;
278 const char* p = c;
279 while (*p != ';') {
280 char ch = *p++;
281 if (ch == '/') {
282 ch = '.';
283 }
284 result.push_back(ch);
285 }
286 // ...and replace the semicolon with 'dim' "[]" pairs:
287 while (dim--) {
288 result += "[]";
289 }
290 return result;
291}
292
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700293std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800294 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700295 return PrettyDescriptor(descriptor_string);
296}
297
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800298std::string PrettyField(const mirror::Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700299 if (f == NULL) {
300 return "null";
301 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800302 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700303 std::string result;
304 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800305 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700306 result += ' ';
307 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800308 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700309 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800310 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700311 return result;
312}
313
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700314std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800315 if (field_idx >= dex_file.NumFieldIds()) {
316 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
317 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700318 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
319 std::string result;
320 if (with_type) {
321 result += dex_file.GetFieldTypeDescriptor(field_id);
322 result += ' ';
323 }
324 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
325 result += '.';
326 result += dex_file.GetFieldName(field_id);
327 return result;
328}
329
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700330std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800331 if (type_idx >= dex_file.NumTypeIds()) {
332 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
333 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700334 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700335 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700336}
337
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700338std::string PrettyArguments(const char* signature) {
339 std::string result;
340 result += '(';
341 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700342 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700343 while (*signature != ')') {
344 size_t argument_length = 0;
345 while (signature[argument_length] == '[') {
346 ++argument_length;
347 }
348 if (signature[argument_length] == 'L') {
349 argument_length = (strchr(signature, ';') - signature + 1);
350 } else {
351 ++argument_length;
352 }
353 std::string argument_descriptor(signature, argument_length);
354 result += PrettyDescriptor(argument_descriptor);
355 if (signature[argument_length] != ')') {
356 result += ", ";
357 }
358 signature += argument_length;
359 }
360 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700361 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700362 result += ')';
363 return result;
364}
365
366std::string PrettyReturnType(const char* signature) {
367 const char* return_type = strchr(signature, ')');
368 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700369 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700370 return PrettyDescriptor(return_type);
371}
372
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800373std::string PrettyMethod(const mirror::AbstractMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700374 if (m == NULL) {
375 return "null";
376 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800377 MethodHelper mh(m);
378 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700379 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800380 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700381 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700382 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700383 if (signature == "<no signature>") {
384 return result + signature;
385 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700386 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700387 }
388 return result;
389}
390
Ian Rogers0571d352011-11-03 19:51:38 -0700391std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800392 if (method_idx >= dex_file.NumMethodIds()) {
393 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
394 }
Ian Rogers0571d352011-11-03 19:51:38 -0700395 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
396 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
397 result += '.';
398 result += dex_file.GetMethodName(method_id);
399 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700400 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700401 if (signature == "<no signature>") {
402 return result + signature;
403 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700404 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700405 }
406 return result;
407}
408
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800409std::string PrettyTypeOf(const mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700410 if (obj == NULL) {
411 return "null";
412 }
413 if (obj->GetClass() == NULL) {
414 return "(raw)";
415 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800416 ClassHelper kh(obj->GetClass());
417 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700418 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800419 kh.ChangeClass(obj->AsClass());
420 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700421 }
422 return result;
423}
424
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800425std::string PrettyClass(const mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700426 if (c == NULL) {
427 return "null";
428 }
429 std::string result;
430 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800431 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700432 result += ">";
433 return result;
434}
435
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800436std::string PrettyClassAndClassLoader(const mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700437 if (c == NULL) {
438 return "null";
439 }
440 std::string result;
441 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800442 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700443 result += ",";
444 result += PrettyTypeOf(c->GetClassLoader());
445 // TODO: add an identifying hash value for the loader
446 result += ">";
447 return result;
448}
449
Elliott Hughesc967f782012-04-16 10:23:15 -0700450std::string PrettySize(size_t byte_count) {
451 // The byte thresholds at which we display amounts. A byte count is displayed
452 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
453 static const size_t kUnitThresholds[] = {
454 0, // B up to...
455 3*1024, // KB up to...
456 2*1024*1024, // MB up to...
457 1024*1024*1024 // GB from here.
458 };
459 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
460 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
461
462 int i = arraysize(kUnitThresholds);
463 while (--i > 0) {
464 if (byte_count >= kUnitThresholds[i]) {
465 break;
466 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800467 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700468
469 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800470}
471
472std::string PrettyDuration(uint64_t nano_duration) {
473 if (nano_duration == 0) {
474 return "0";
475 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700476 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
477 }
478}
479
480TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
481 const uint64_t one_sec = 1000 * 1000 * 1000;
482 const uint64_t one_ms = 1000 * 1000;
483 const uint64_t one_us = 1000;
484 if (nano_duration >= one_sec) {
485 return kTimeUnitSecond;
486 } else if (nano_duration >= one_ms) {
487 return kTimeUnitMillisecond;
488 } else if (nano_duration >= one_us) {
489 return kTimeUnitMicrosecond;
490 } else {
491 return kTimeUnitNanosecond;
492 }
493}
494
495uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
496 const uint64_t one_sec = 1000 * 1000 * 1000;
497 const uint64_t one_ms = 1000 * 1000;
498 const uint64_t one_us = 1000;
499
500 switch (time_unit) {
501 case kTimeUnitSecond:
502 return one_sec;
503 case kTimeUnitMillisecond:
504 return one_ms;
505 case kTimeUnitMicrosecond:
506 return one_us;
507 case kTimeUnitNanosecond:
508 return 1;
509 }
510 return 0;
511}
512
513std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
514 const char* unit = NULL;
515 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
516 uint32_t zero_fill = 1;
517 switch (time_unit) {
518 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800519 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800520 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700521 break;
522 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800523 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800524 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700525 break;
526 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800527 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800528 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700529 break;
530 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800531 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800532 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700533 break;
534 }
535
536 uint64_t whole_part = nano_duration / divisor;
537 uint64_t fractional_part = nano_duration % divisor;
538 if (fractional_part == 0) {
539 return StringPrintf("%llu%s", whole_part, unit);
540 } else {
541 while ((fractional_part % 1000) == 0) {
542 zero_fill -= 3;
543 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800544 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700545 if (zero_fill == 3) {
546 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
547 } else if (zero_fill == 6) {
548 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800549 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700550 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800551 }
552 }
553}
554
Elliott Hughes82914b62012-04-09 15:56:29 -0700555std::string PrintableString(const std::string& utf) {
556 std::string result;
557 result += '"';
558 const char* p = utf.c_str();
559 size_t char_count = CountModifiedUtf8Chars(p);
560 for (size_t i = 0; i < char_count; ++i) {
561 uint16_t ch = GetUtf16FromUtf8(&p);
562 if (ch == '\\') {
563 result += "\\\\";
564 } else if (ch == '\n') {
565 result += "\\n";
566 } else if (ch == '\r') {
567 result += "\\r";
568 } else if (ch == '\t') {
569 result += "\\t";
570 } else if (NeedsEscaping(ch)) {
571 StringAppendF(&result, "\\u%04x", ch);
572 } else {
573 result += ch;
574 }
575 }
576 result += '"';
577 return result;
578}
579
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800580// 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 -0700581std::string MangleForJni(const std::string& s) {
582 std::string result;
583 size_t char_count = CountModifiedUtf8Chars(s.c_str());
584 const char* cp = &s[0];
585 for (size_t i = 0; i < char_count; ++i) {
586 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800587 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
588 result.push_back(ch);
589 } else if (ch == '.' || ch == '/') {
590 result += "_";
591 } else if (ch == '_') {
592 result += "_1";
593 } else if (ch == ';') {
594 result += "_2";
595 } else if (ch == '[') {
596 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700597 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800598 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700599 }
600 }
601 return result;
602}
603
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700604std::string DotToDescriptor(const char* class_name) {
605 std::string descriptor(class_name);
606 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
607 if (descriptor.length() > 0 && descriptor[0] != '[') {
608 descriptor = "L" + descriptor + ";";
609 }
610 return descriptor;
611}
612
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800613std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800614 size_t length = strlen(descriptor);
615 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
616 std::string result(descriptor + 1, length - 2);
617 std::replace(result.begin(), result.end(), '/', '.');
618 return result;
619 }
620 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800621}
622
623std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800624 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800625 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
626 std::string result(descriptor + 1, length - 2);
627 return result;
628 }
629 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700630}
631
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800632std::string JniShortName(const mirror::AbstractMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800633 MethodHelper mh(m);
634 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700635 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700636 CHECK_EQ(class_name[0], 'L') << class_name;
637 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700638 class_name.erase(0, 1);
639 class_name.erase(class_name.size() - 1, 1);
640
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800641 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700642
643 std::string short_name;
644 short_name += "Java_";
645 short_name += MangleForJni(class_name);
646 short_name += "_";
647 short_name += MangleForJni(method_name);
648 return short_name;
649}
650
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800651std::string JniLongName(const mirror::AbstractMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700652 std::string long_name;
653 long_name += JniShortName(m);
654 long_name += "__";
655
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800656 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700657 signature.erase(0, 1);
658 signature.erase(signature.begin() + signature.find(')'), signature.end());
659
660 long_name += MangleForJni(signature);
661
662 return long_name;
663}
664
jeffhao10037c82012-01-23 15:06:23 -0800665// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700666uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700667 0x00000000, // 00..1f low control characters; nothing valid
668 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
669 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
670 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700671};
672
jeffhao10037c82012-01-23 15:06:23 -0800673// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
674bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700675 /*
676 * It's a multibyte encoded character. Decode it and analyze. We
677 * accept anything that isn't (a) an improperly encoded low value,
678 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
679 * control character, or (e) a high space, layout, or special
680 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
681 * U+fff0..U+ffff). This is all specified in the dex format
682 * document.
683 */
684
685 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
686
687 // Perform follow-up tests based on the high 8 bits.
688 switch (utf16 >> 8) {
689 case 0x00:
690 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
691 return (utf16 > 0x00a0);
692 case 0xd8:
693 case 0xd9:
694 case 0xda:
695 case 0xdb:
696 // It's a leading surrogate. Check to see that a trailing
697 // surrogate follows.
698 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
699 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
700 case 0xdc:
701 case 0xdd:
702 case 0xde:
703 case 0xdf:
704 // It's a trailing surrogate, which is not valid at this point.
705 return false;
706 case 0x20:
707 case 0xff:
708 // It's in the range that has spaces, controls, and specials.
709 switch (utf16 & 0xfff8) {
710 case 0x2000:
711 case 0x2008:
712 case 0x2028:
713 case 0xfff0:
714 case 0xfff8:
715 return false;
716 }
717 break;
718 }
719 return true;
720}
721
722/* Return whether the pointed-at modified-UTF-8 encoded character is
723 * valid as part of a member name, updating the pointer to point past
724 * the consumed character. This will consume two encoded UTF-16 code
725 * points if the character is encoded as a surrogate pair. Also, if
726 * this function returns false, then the given pointer may only have
727 * been partially advanced.
728 */
jeffhao10037c82012-01-23 15:06:23 -0800729bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700730 uint8_t c = (uint8_t) **pUtf8Ptr;
731 if (c <= 0x7f) {
732 // It's low-ascii, so check the table.
733 uint32_t wordIdx = c >> 5;
734 uint32_t bitIdx = c & 0x1f;
735 (*pUtf8Ptr)++;
736 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
737 }
738
739 // It's a multibyte encoded character. Call a non-inline function
740 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800741 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
742}
743
744bool IsValidMemberName(const char* s) {
745 bool angle_name = false;
746
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700747 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800748 case '\0':
749 // The empty string is not a valid name.
750 return false;
751 case '<':
752 angle_name = true;
753 s++;
754 break;
755 }
756
757 while (true) {
758 switch (*s) {
759 case '\0':
760 return !angle_name;
761 case '>':
762 return angle_name && s[1] == '\0';
763 }
764
765 if (!IsValidPartOfMemberNameUtf8(&s)) {
766 return false;
767 }
768 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700769}
770
Elliott Hughes906e6852011-10-28 14:52:10 -0700771enum ClassNameType { kName, kDescriptor };
772bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700773 int arrayCount = 0;
774 while (*s == '[') {
775 arrayCount++;
776 s++;
777 }
778
779 if (arrayCount > 255) {
780 // Arrays may have no more than 255 dimensions.
781 return false;
782 }
783
784 if (arrayCount != 0) {
785 /*
786 * If we're looking at an array of some sort, then it doesn't
787 * matter if what is being asked for is a class name; the
788 * format looks the same as a type descriptor in that case, so
789 * treat it as such.
790 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700791 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700792 }
793
Elliott Hughes906e6852011-10-28 14:52:10 -0700794 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700795 /*
796 * We are looking for a descriptor. Either validate it as a
797 * single-character primitive type, or continue on to check the
798 * embedded class name (bracketed by "L" and ";").
799 */
800 switch (*(s++)) {
801 case 'B':
802 case 'C':
803 case 'D':
804 case 'F':
805 case 'I':
806 case 'J':
807 case 'S':
808 case 'Z':
809 // These are all single-character descriptors for primitive types.
810 return (*s == '\0');
811 case 'V':
812 // Non-array void is valid, but you can't have an array of void.
813 return (arrayCount == 0) && (*s == '\0');
814 case 'L':
815 // Class name: Break out and continue below.
816 break;
817 default:
818 // Oddball descriptor character.
819 return false;
820 }
821 }
822
823 /*
824 * We just consumed the 'L' that introduces a class name as part
825 * of a type descriptor, or we are looking for an unadorned class
826 * name.
827 */
828
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700829 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700830 for (;;) {
831 uint8_t c = (uint8_t) *s;
832 switch (c) {
833 case '\0':
834 /*
835 * Premature end for a type descriptor, but valid for
836 * a class name as long as we haven't encountered an
837 * empty component (including the degenerate case of
838 * the empty string "").
839 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700840 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700841 case ';':
842 /*
843 * Invalid character for a class name, but the
844 * legitimate end of a type descriptor. In the latter
845 * case, make sure that this is the end of the string
846 * and that it doesn't end with an empty component
847 * (including the degenerate case of "L;").
848 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700849 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700850 case '/':
851 case '.':
852 if (c != separator) {
853 // The wrong separator character.
854 return false;
855 }
856 if (sepOrFirst) {
857 // Separator at start or two separators in a row.
858 return false;
859 }
860 sepOrFirst = true;
861 s++;
862 break;
863 default:
jeffhao10037c82012-01-23 15:06:23 -0800864 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700865 return false;
866 }
867 sepOrFirst = false;
868 break;
869 }
870 }
871}
872
Elliott Hughes906e6852011-10-28 14:52:10 -0700873bool IsValidBinaryClassName(const char* s) {
874 return IsValidClassName(s, kName, '.');
875}
876
877bool IsValidJniClassName(const char* s) {
878 return IsValidClassName(s, kName, '/');
879}
880
881bool IsValidDescriptor(const char* s) {
882 return IsValidClassName(s, kDescriptor, '/');
883}
884
Elliott Hughes48436bb2012-02-07 15:23:28 -0800885void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700886 const char* p = s.data();
887 const char* end = p + s.size();
888 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800889 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700890 ++p;
891 } else {
892 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800893 while (++p != end && *p != separator) {
894 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700895 }
896 result.push_back(std::string(start, p - start));
897 }
898 }
899}
900
Elliott Hughes48436bb2012-02-07 15:23:28 -0800901template <typename StringT>
902std::string Join(std::vector<StringT>& strings, char separator) {
903 if (strings.empty()) {
904 return "";
905 }
906
907 std::string result(strings[0]);
908 for (size_t i = 1; i < strings.size(); ++i) {
909 result += separator;
910 result += strings[i];
911 }
912 return result;
913}
914
915// Explicit instantiations.
916template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
917template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
918template std::string Join<char*>(std::vector<char*>& strings, char separator);
919
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800920bool StartsWith(const std::string& s, const char* prefix) {
921 return s.compare(0, strlen(prefix), prefix) == 0;
922}
923
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700924bool EndsWith(const std::string& s, const char* suffix) {
925 size_t suffix_length = strlen(suffix);
926 size_t string_length = s.size();
927 if (suffix_length > string_length) {
928 return false;
929 }
930 size_t offset = string_length - suffix_length;
931 return s.compare(offset, suffix_length, suffix) == 0;
932}
933
Elliott Hughes22869a92012-03-27 14:08:24 -0700934void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700935 int hasAt = 0;
936 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700937 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700938 while (*s) {
939 if (*s == '.') {
940 hasDot = 1;
941 } else if (*s == '@') {
942 hasAt = 1;
943 }
944 s++;
945 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700946 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700947 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700948 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700949 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700950 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700951 }
952#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700953 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700954 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
955 strncpy(buf, s, sizeof(buf)-1);
956 buf[sizeof(buf)-1] = '\0';
957 errno = pthread_setname_np(pthread_self(), buf);
958 if (errno != 0) {
959 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
960 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700961#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700962 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700963#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700964 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700965#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700966 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700967#endif
968}
969
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700970void GetTaskStats(pid_t tid, char& state, int& utime, int& stime, int& task_cpu) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700971 utime = stime = task_cpu = 0;
972 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700973 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700974 return;
975 }
976 // Skip the command, which may contain spaces.
977 stats = stats.substr(stats.find(')') + 2);
978 // Extract the three fields we care about.
979 std::vector<std::string> fields;
980 Split(stats, ' ', fields);
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700981 state = fields[0][0];
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700982 utime = strtoull(fields[11].c_str(), NULL, 10);
983 stime = strtoull(fields[12].c_str(), NULL, 10);
984 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
985}
986
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700987std::string GetSchedulerGroupName(pid_t tid) {
988 // /proc/<pid>/cgroup looks like this:
989 // 2:devices:/
990 // 1:cpuacct,cpu:/
991 // We want the third field from the line whose second field contains the "cpu" token.
992 std::string cgroup_file;
993 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
994 return "";
995 }
996 std::vector<std::string> cgroup_lines;
997 Split(cgroup_file, '\n', cgroup_lines);
998 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
999 std::vector<std::string> cgroup_fields;
1000 Split(cgroup_lines[i], ':', cgroup_fields);
1001 std::vector<std::string> cgroups;
1002 Split(cgroup_fields[1], ',', cgroups);
1003 for (size_t i = 0; i < cgroups.size(); ++i) {
1004 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001005 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001006 }
1007 }
1008 }
1009 return "";
1010}
1011
Elliott Hughes46e251b2012-05-22 15:10:45 -07001012static const char* CleanMapName(const backtrace_symbol_t* symbol) {
1013 const char* map_name = symbol->map_name;
1014 if (map_name == NULL) {
1015 map_name = "???";
1016 }
1017 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1018 // into "libartd.so".
1019 const char* last_slash = strrchr(map_name, '/');
1020 if (last_slash != NULL) {
1021 map_name = last_slash + 1;
1022 }
1023 return map_name;
1024}
1025
1026static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
1027 std::string& symbol_name, uint32_t& pc_offset) {
1028 symbol_table_t* symbol_table = NULL;
1029 if (symbol->map_name != NULL) {
1030 symbol_table = load_symbol_table(symbol->map_name);
1031 }
1032 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -07001033 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001034 if (symbol_table != NULL) {
1035 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
1036 if (elf_symbol == NULL) {
1037 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -07001038 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001039 }
1040 }
1041 if (elf_symbol != NULL) {
1042 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
1043 if (demangled_symbol_name != NULL) {
1044 symbol_name = demangled_symbol_name;
1045 } else {
1046 symbol_name = elf_symbol->name;
1047 }
Elliott Hughes95aff772012-06-12 17:44:15 -07001048
1049 // TODO: is it a libcorkscrew bug that we have to do this?
1050 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001051 } else {
1052 symbol_name = "???";
1053 }
1054 free_symbol_table(symbol_table);
1055}
1056
1057void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001058 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1059 flush_my_map_info_list();
1060
Elliott Hughes46e251b2012-05-22 15:10:45 -07001061 const size_t MAX_DEPTH = 32;
1062 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001063 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001064 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001065 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001066 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001067 return;
1068 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001069 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001070 return;
1071 }
1072
1073 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1074 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1075
1076 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1077 const backtrace_frame_t* frame = &frames[i];
1078 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1079
1080 // We produce output like this:
1081 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1082
1083 std::string symbol_name;
1084 uint32_t pc_offset = 0;
1085 if (symbol->demangled_name != NULL) {
1086 symbol_name = symbol->demangled_name;
1087 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1088 } else if (symbol->symbol_name != NULL) {
1089 symbol_name = symbol->symbol_name;
1090 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1091 } else {
1092 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1093 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1094 }
1095
1096 os << prefix;
1097 if (include_count) {
1098 os << StringPrintf("#%02zd ", i);
1099 }
1100 os << symbol_name;
1101 if (pc_offset != 0) {
1102 os << "+" << pc_offset;
1103 }
1104 os << StringPrintf(" [%p] (%s)\n",
1105 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1106 }
1107
1108 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1109}
1110
Elliott Hughes058a6de2012-05-24 19:13:02 -07001111#if defined(__APPLE__)
1112
1113// TODO: is there any way to get the kernel stack on Mac OS?
1114void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1115
1116#else
1117
Elliott Hughes46e251b2012-05-22 15:10:45 -07001118void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001119 if (tid == GetTid()) {
1120 // There's no point showing that we're reading our stack out of /proc!
1121 return;
1122 }
1123
Elliott Hughes46e251b2012-05-22 15:10:45 -07001124 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1125 std::string kernel_stack;
1126 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001127 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001128 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001129 }
1130
1131 std::vector<std::string> kernel_stack_frames;
1132 Split(kernel_stack, '\n', kernel_stack_frames);
1133 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1134 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1135 kernel_stack_frames.pop_back();
1136 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1137 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1138 const char* text = kernel_stack_frames[i].c_str();
1139 const char* close_bracket = strchr(text, ']');
1140 if (close_bracket != NULL) {
1141 text = close_bracket + 2;
1142 }
1143 os << prefix;
1144 if (include_count) {
1145 os << StringPrintf("#%02zd ", i);
1146 }
1147 os << text << "\n";
1148 }
1149}
1150
1151#endif
1152
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001153const char* GetAndroidRoot() {
1154 const char* android_root = getenv("ANDROID_ROOT");
1155 if (android_root == NULL) {
1156 if (OS::DirectoryExists("/system")) {
1157 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001158 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001159 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1160 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001161 }
1162 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001163 if (!OS::DirectoryExists(android_root)) {
1164 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001165 return "";
1166 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001167 return android_root;
1168}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001169
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001170const char* GetAndroidData() {
1171 const char* android_data = getenv("ANDROID_DATA");
1172 if (android_data == NULL) {
1173 if (OS::DirectoryExists("/data")) {
1174 android_data = "/data";
1175 } else {
1176 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1177 return "";
1178 }
1179 }
1180 if (!OS::DirectoryExists(android_data)) {
1181 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1182 return "";
1183 }
1184 return android_data;
1185}
1186
Brian Carlstrom7675e162013-06-10 16:18:04 -07001187std::string GetDalvikCacheOrDie(const char* android_data) {
1188 std::string dalvik_cache(StringPrintf("%s/dalvik-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001189
Brian Carlstrom7675e162013-06-10 16:18:04 -07001190 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1191 if (StartsWith(dalvik_cache, "/tmp/")) {
1192 int result = mkdir(dalvik_cache.c_str(), 0700);
Brian Carlstroma9f19782011-10-13 00:14:47 -07001193 if (result != 0) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001194 LOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001195 return "";
1196 }
1197 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001198 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001199 return "";
1200 }
1201 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001202 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001203}
1204
Brian Carlstrom7675e162013-06-10 16:18:04 -07001205std::string GetDalvikCacheFilenameOrDie(const std::string& location) {
1206 std::string dalvik_cache(GetDalvikCacheOrDie(GetAndroidData()));
Ian Rogerse6060102013-05-16 12:01:04 -07001207 if (location[0] != '/') {
1208 LOG(FATAL) << "Expected path in location to be absolute: "<< location;
1209 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001210 std::string cache_file(location, 1); // skip leading slash
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001211 if (!IsValidDexFilename(location)) {
1212 cache_file += "/";
1213 cache_file += DexFile::kClassesDex;
1214 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001215 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Brian Carlstrom7675e162013-06-10 16:18:04 -07001216 return dalvik_cache + "/" + cache_file;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001217}
1218
jeffhao262bf462011-10-20 18:36:32 -07001219bool IsValidZipFilename(const std::string& filename) {
1220 if (filename.size() < 4) {
1221 return false;
1222 }
1223 std::string suffix(filename.substr(filename.size() - 4));
1224 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1225}
1226
1227bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001228 return EndsWith(filename, ".dex");
1229}
1230
1231bool IsValidOatFilename(const std::string& filename) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001232 return (EndsWith(filename, ".odex") ||
1233 EndsWith(filename, ".oat") ||
1234 EndsWith(filename, DexFile::kClassesDex));
jeffhao262bf462011-10-20 18:36:32 -07001235}
1236
Elliott Hughes42ee1422011-09-06 12:33:32 -07001237} // namespace art