blob: 6b93da835d1bd15a767abc60187469d333c774da [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 Rogers2dd0e2c2013-01-24 12:42:14 -080028#include "mirror/abstract_method-inl.h"
29#include "mirror/class.h"
30#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__)
Elliott Hughesb08e8a32012-04-02 10:51:41 -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
Elliott Hughes46e251b2012-05-22 15:10:45 -070053#include <corkscrew/backtrace.h> // For DumpNativeStack.
54#include <corkscrew/demangle.h> // For DumpNativeStack.
55
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)) {
76 result.resize(result.size() - 1); // Lose the trailing '\n'.
77 } 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[][]".
256 c++; // Skip the 'L'.
257 } 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;
Elliott Hughes9058f2b2012-03-22 18:06:48 -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) {
315 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
316 std::string result;
317 if (with_type) {
318 result += dex_file.GetFieldTypeDescriptor(field_id);
319 result += ' ';
320 }
321 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
322 result += '.';
323 result += dex_file.GetFieldName(field_id);
324 return result;
325}
326
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700327std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
328 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700329 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700330}
331
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700332std::string PrettyArguments(const char* signature) {
333 std::string result;
334 result += '(';
335 CHECK_EQ(*signature, '(');
336 ++signature; // Skip the '('.
337 while (*signature != ')') {
338 size_t argument_length = 0;
339 while (signature[argument_length] == '[') {
340 ++argument_length;
341 }
342 if (signature[argument_length] == 'L') {
343 argument_length = (strchr(signature, ';') - signature + 1);
344 } else {
345 ++argument_length;
346 }
347 std::string argument_descriptor(signature, argument_length);
348 result += PrettyDescriptor(argument_descriptor);
349 if (signature[argument_length] != ')') {
350 result += ", ";
351 }
352 signature += argument_length;
353 }
354 CHECK_EQ(*signature, ')');
355 ++signature; // Skip the ')'.
356 result += ')';
357 return result;
358}
359
360std::string PrettyReturnType(const char* signature) {
361 const char* return_type = strchr(signature, ')');
362 CHECK(return_type != NULL);
363 ++return_type; // Skip ')'.
364 return PrettyDescriptor(return_type);
365}
366
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800367std::string PrettyMethod(const mirror::AbstractMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700368 if (m == NULL) {
369 return "null";
370 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800371 MethodHelper mh(m);
372 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700373 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800374 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700375 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700376 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700377 if (signature == "<no signature>") {
378 return result + signature;
379 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700380 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700381 }
382 return result;
383}
384
Ian Rogers0571d352011-11-03 19:51:38 -0700385std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
386 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
387 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
388 result += '.';
389 result += dex_file.GetMethodName(method_id);
390 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700391 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700392 if (signature == "<no signature>") {
393 return result + signature;
394 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700395 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700396 }
397 return result;
398}
399
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800400std::string PrettyTypeOf(const mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700401 if (obj == NULL) {
402 return "null";
403 }
404 if (obj->GetClass() == NULL) {
405 return "(raw)";
406 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800407 ClassHelper kh(obj->GetClass());
408 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700409 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800410 kh.ChangeClass(obj->AsClass());
411 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700412 }
413 return result;
414}
415
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800416std::string PrettyClass(const mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700417 if (c == NULL) {
418 return "null";
419 }
420 std::string result;
421 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800422 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700423 result += ">";
424 return result;
425}
426
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800427std::string PrettyClassAndClassLoader(const mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700428 if (c == NULL) {
429 return "null";
430 }
431 std::string result;
432 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800433 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700434 result += ",";
435 result += PrettyTypeOf(c->GetClassLoader());
436 // TODO: add an identifying hash value for the loader
437 result += ">";
438 return result;
439}
440
Elliott Hughesc967f782012-04-16 10:23:15 -0700441std::string PrettySize(size_t byte_count) {
442 // The byte thresholds at which we display amounts. A byte count is displayed
443 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
444 static const size_t kUnitThresholds[] = {
445 0, // B up to...
446 3*1024, // KB up to...
447 2*1024*1024, // MB up to...
448 1024*1024*1024 // GB from here.
449 };
450 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
451 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
452
453 int i = arraysize(kUnitThresholds);
454 while (--i > 0) {
455 if (byte_count >= kUnitThresholds[i]) {
456 break;
457 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800458 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700459
460 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800461}
462
463std::string PrettyDuration(uint64_t nano_duration) {
464 if (nano_duration == 0) {
465 return "0";
466 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700467 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
468 }
469}
470
471TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
472 const uint64_t one_sec = 1000 * 1000 * 1000;
473 const uint64_t one_ms = 1000 * 1000;
474 const uint64_t one_us = 1000;
475 if (nano_duration >= one_sec) {
476 return kTimeUnitSecond;
477 } else if (nano_duration >= one_ms) {
478 return kTimeUnitMillisecond;
479 } else if (nano_duration >= one_us) {
480 return kTimeUnitMicrosecond;
481 } else {
482 return kTimeUnitNanosecond;
483 }
484}
485
486uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
487 const uint64_t one_sec = 1000 * 1000 * 1000;
488 const uint64_t one_ms = 1000 * 1000;
489 const uint64_t one_us = 1000;
490
491 switch (time_unit) {
492 case kTimeUnitSecond:
493 return one_sec;
494 case kTimeUnitMillisecond:
495 return one_ms;
496 case kTimeUnitMicrosecond:
497 return one_us;
498 case kTimeUnitNanosecond:
499 return 1;
500 }
501 return 0;
502}
503
504std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
505 const char* unit = NULL;
506 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
507 uint32_t zero_fill = 1;
508 switch (time_unit) {
509 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800510 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800511 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700512 break;
513 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800514 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800515 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700516 break;
517 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800518 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800519 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700520 break;
521 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800522 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800523 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700524 break;
525 }
526
527 uint64_t whole_part = nano_duration / divisor;
528 uint64_t fractional_part = nano_duration % divisor;
529 if (fractional_part == 0) {
530 return StringPrintf("%llu%s", whole_part, unit);
531 } else {
532 while ((fractional_part % 1000) == 0) {
533 zero_fill -= 3;
534 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800535 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700536 if (zero_fill == 3) {
537 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
538 } else if (zero_fill == 6) {
539 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800540 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700541 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800542 }
543 }
544}
545
Elliott Hughes82914b62012-04-09 15:56:29 -0700546std::string PrintableString(const std::string& utf) {
547 std::string result;
548 result += '"';
549 const char* p = utf.c_str();
550 size_t char_count = CountModifiedUtf8Chars(p);
551 for (size_t i = 0; i < char_count; ++i) {
552 uint16_t ch = GetUtf16FromUtf8(&p);
553 if (ch == '\\') {
554 result += "\\\\";
555 } else if (ch == '\n') {
556 result += "\\n";
557 } else if (ch == '\r') {
558 result += "\\r";
559 } else if (ch == '\t') {
560 result += "\\t";
561 } else if (NeedsEscaping(ch)) {
562 StringAppendF(&result, "\\u%04x", ch);
563 } else {
564 result += ch;
565 }
566 }
567 result += '"';
568 return result;
569}
570
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800571// 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 -0700572std::string MangleForJni(const std::string& s) {
573 std::string result;
574 size_t char_count = CountModifiedUtf8Chars(s.c_str());
575 const char* cp = &s[0];
576 for (size_t i = 0; i < char_count; ++i) {
577 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800578 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
579 result.push_back(ch);
580 } else if (ch == '.' || ch == '/') {
581 result += "_";
582 } else if (ch == '_') {
583 result += "_1";
584 } else if (ch == ';') {
585 result += "_2";
586 } else if (ch == '[') {
587 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700588 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800589 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700590 }
591 }
592 return result;
593}
594
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700595std::string DotToDescriptor(const char* class_name) {
596 std::string descriptor(class_name);
597 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
598 if (descriptor.length() > 0 && descriptor[0] != '[') {
599 descriptor = "L" + descriptor + ";";
600 }
601 return descriptor;
602}
603
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800604std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800605 size_t length = strlen(descriptor);
606 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
607 std::string result(descriptor + 1, length - 2);
608 std::replace(result.begin(), result.end(), '/', '.');
609 return result;
610 }
611 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800612}
613
614std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800615 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800616 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
617 std::string result(descriptor + 1, length - 2);
618 return result;
619 }
620 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700621}
622
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800623std::string JniShortName(const mirror::AbstractMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800624 MethodHelper mh(m);
625 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700626 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700627 CHECK_EQ(class_name[0], 'L') << class_name;
628 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700629 class_name.erase(0, 1);
630 class_name.erase(class_name.size() - 1, 1);
631
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800632 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700633
634 std::string short_name;
635 short_name += "Java_";
636 short_name += MangleForJni(class_name);
637 short_name += "_";
638 short_name += MangleForJni(method_name);
639 return short_name;
640}
641
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800642std::string JniLongName(const mirror::AbstractMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700643 std::string long_name;
644 long_name += JniShortName(m);
645 long_name += "__";
646
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800647 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700648 signature.erase(0, 1);
649 signature.erase(signature.begin() + signature.find(')'), signature.end());
650
651 long_name += MangleForJni(signature);
652
653 return long_name;
654}
655
jeffhao10037c82012-01-23 15:06:23 -0800656// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700657uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
658 0x00000000, // 00..1f low control characters; nothing valid
659 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
660 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
661 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
662};
663
jeffhao10037c82012-01-23 15:06:23 -0800664// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
665bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700666 /*
667 * It's a multibyte encoded character. Decode it and analyze. We
668 * accept anything that isn't (a) an improperly encoded low value,
669 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
670 * control character, or (e) a high space, layout, or special
671 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
672 * U+fff0..U+ffff). This is all specified in the dex format
673 * document.
674 */
675
676 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
677
678 // Perform follow-up tests based on the high 8 bits.
679 switch (utf16 >> 8) {
680 case 0x00:
681 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
682 return (utf16 > 0x00a0);
683 case 0xd8:
684 case 0xd9:
685 case 0xda:
686 case 0xdb:
687 // It's a leading surrogate. Check to see that a trailing
688 // surrogate follows.
689 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
690 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
691 case 0xdc:
692 case 0xdd:
693 case 0xde:
694 case 0xdf:
695 // It's a trailing surrogate, which is not valid at this point.
696 return false;
697 case 0x20:
698 case 0xff:
699 // It's in the range that has spaces, controls, and specials.
700 switch (utf16 & 0xfff8) {
701 case 0x2000:
702 case 0x2008:
703 case 0x2028:
704 case 0xfff0:
705 case 0xfff8:
706 return false;
707 }
708 break;
709 }
710 return true;
711}
712
713/* Return whether the pointed-at modified-UTF-8 encoded character is
714 * valid as part of a member name, updating the pointer to point past
715 * the consumed character. This will consume two encoded UTF-16 code
716 * points if the character is encoded as a surrogate pair. Also, if
717 * this function returns false, then the given pointer may only have
718 * been partially advanced.
719 */
jeffhao10037c82012-01-23 15:06:23 -0800720bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700721 uint8_t c = (uint8_t) **pUtf8Ptr;
722 if (c <= 0x7f) {
723 // It's low-ascii, so check the table.
724 uint32_t wordIdx = c >> 5;
725 uint32_t bitIdx = c & 0x1f;
726 (*pUtf8Ptr)++;
727 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
728 }
729
730 // It's a multibyte encoded character. Call a non-inline function
731 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800732 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
733}
734
735bool IsValidMemberName(const char* s) {
736 bool angle_name = false;
737
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700738 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800739 case '\0':
740 // The empty string is not a valid name.
741 return false;
742 case '<':
743 angle_name = true;
744 s++;
745 break;
746 }
747
748 while (true) {
749 switch (*s) {
750 case '\0':
751 return !angle_name;
752 case '>':
753 return angle_name && s[1] == '\0';
754 }
755
756 if (!IsValidPartOfMemberNameUtf8(&s)) {
757 return false;
758 }
759 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700760}
761
Elliott Hughes906e6852011-10-28 14:52:10 -0700762enum ClassNameType { kName, kDescriptor };
763bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700764 int arrayCount = 0;
765 while (*s == '[') {
766 arrayCount++;
767 s++;
768 }
769
770 if (arrayCount > 255) {
771 // Arrays may have no more than 255 dimensions.
772 return false;
773 }
774
775 if (arrayCount != 0) {
776 /*
777 * If we're looking at an array of some sort, then it doesn't
778 * matter if what is being asked for is a class name; the
779 * format looks the same as a type descriptor in that case, so
780 * treat it as such.
781 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700782 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700783 }
784
Elliott Hughes906e6852011-10-28 14:52:10 -0700785 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700786 /*
787 * We are looking for a descriptor. Either validate it as a
788 * single-character primitive type, or continue on to check the
789 * embedded class name (bracketed by "L" and ";").
790 */
791 switch (*(s++)) {
792 case 'B':
793 case 'C':
794 case 'D':
795 case 'F':
796 case 'I':
797 case 'J':
798 case 'S':
799 case 'Z':
800 // These are all single-character descriptors for primitive types.
801 return (*s == '\0');
802 case 'V':
803 // Non-array void is valid, but you can't have an array of void.
804 return (arrayCount == 0) && (*s == '\0');
805 case 'L':
806 // Class name: Break out and continue below.
807 break;
808 default:
809 // Oddball descriptor character.
810 return false;
811 }
812 }
813
814 /*
815 * We just consumed the 'L' that introduces a class name as part
816 * of a type descriptor, or we are looking for an unadorned class
817 * name.
818 */
819
820 bool sepOrFirst = true; // first character or just encountered a separator.
821 for (;;) {
822 uint8_t c = (uint8_t) *s;
823 switch (c) {
824 case '\0':
825 /*
826 * Premature end for a type descriptor, but valid for
827 * a class name as long as we haven't encountered an
828 * empty component (including the degenerate case of
829 * the empty string "").
830 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700831 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700832 case ';':
833 /*
834 * Invalid character for a class name, but the
835 * legitimate end of a type descriptor. In the latter
836 * case, make sure that this is the end of the string
837 * and that it doesn't end with an empty component
838 * (including the degenerate case of "L;").
839 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700840 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700841 case '/':
842 case '.':
843 if (c != separator) {
844 // The wrong separator character.
845 return false;
846 }
847 if (sepOrFirst) {
848 // Separator at start or two separators in a row.
849 return false;
850 }
851 sepOrFirst = true;
852 s++;
853 break;
854 default:
jeffhao10037c82012-01-23 15:06:23 -0800855 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700856 return false;
857 }
858 sepOrFirst = false;
859 break;
860 }
861 }
862}
863
Elliott Hughes906e6852011-10-28 14:52:10 -0700864bool IsValidBinaryClassName(const char* s) {
865 return IsValidClassName(s, kName, '.');
866}
867
868bool IsValidJniClassName(const char* s) {
869 return IsValidClassName(s, kName, '/');
870}
871
872bool IsValidDescriptor(const char* s) {
873 return IsValidClassName(s, kDescriptor, '/');
874}
875
Elliott Hughes48436bb2012-02-07 15:23:28 -0800876void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700877 const char* p = s.data();
878 const char* end = p + s.size();
879 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800880 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700881 ++p;
882 } else {
883 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800884 while (++p != end && *p != separator) {
885 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700886 }
887 result.push_back(std::string(start, p - start));
888 }
889 }
890}
891
Elliott Hughes48436bb2012-02-07 15:23:28 -0800892template <typename StringT>
893std::string Join(std::vector<StringT>& strings, char separator) {
894 if (strings.empty()) {
895 return "";
896 }
897
898 std::string result(strings[0]);
899 for (size_t i = 1; i < strings.size(); ++i) {
900 result += separator;
901 result += strings[i];
902 }
903 return result;
904}
905
906// Explicit instantiations.
907template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
908template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
909template std::string Join<char*>(std::vector<char*>& strings, char separator);
910
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800911bool StartsWith(const std::string& s, const char* prefix) {
912 return s.compare(0, strlen(prefix), prefix) == 0;
913}
914
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700915bool EndsWith(const std::string& s, const char* suffix) {
916 size_t suffix_length = strlen(suffix);
917 size_t string_length = s.size();
918 if (suffix_length > string_length) {
919 return false;
920 }
921 size_t offset = string_length - suffix_length;
922 return s.compare(offset, suffix_length, suffix) == 0;
923}
924
Elliott Hughes22869a92012-03-27 14:08:24 -0700925void SetThreadName(const char* thread_name) {
926 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800927
Elliott Hughesdcc24742011-09-07 14:02:44 -0700928 int hasAt = 0;
929 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700930 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700931 while (*s) {
932 if (*s == '.') {
933 hasDot = 1;
934 } else if (*s == '@') {
935 hasAt = 1;
936 }
937 s++;
938 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700939 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700940 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700941 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700942 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700943 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700944 }
945#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700946 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700947 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
948 strncpy(buf, s, sizeof(buf)-1);
949 buf[sizeof(buf)-1] = '\0';
950 errno = pthread_setname_np(pthread_self(), buf);
951 if (errno != 0) {
952 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
953 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700954#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700955 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700956#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700957 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700958#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700959 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700960#endif
961}
962
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700963void GetTaskStats(pid_t tid, char& state, int& utime, int& stime, int& task_cpu) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700964 utime = stime = task_cpu = 0;
965 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700966 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700967 return;
968 }
969 // Skip the command, which may contain spaces.
970 stats = stats.substr(stats.find(')') + 2);
971 // Extract the three fields we care about.
972 std::vector<std::string> fields;
973 Split(stats, ' ', fields);
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700974 state = fields[0][0];
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700975 utime = strtoull(fields[11].c_str(), NULL, 10);
976 stime = strtoull(fields[12].c_str(), NULL, 10);
977 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
978}
979
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700980std::string GetSchedulerGroupName(pid_t tid) {
981 // /proc/<pid>/cgroup looks like this:
982 // 2:devices:/
983 // 1:cpuacct,cpu:/
984 // We want the third field from the line whose second field contains the "cpu" token.
985 std::string cgroup_file;
986 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
987 return "";
988 }
989 std::vector<std::string> cgroup_lines;
990 Split(cgroup_file, '\n', cgroup_lines);
991 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
992 std::vector<std::string> cgroup_fields;
993 Split(cgroup_lines[i], ':', cgroup_fields);
994 std::vector<std::string> cgroups;
995 Split(cgroup_fields[1], ',', cgroups);
996 for (size_t i = 0; i < cgroups.size(); ++i) {
997 if (cgroups[i] == "cpu") {
998 return cgroup_fields[2].substr(1); // Skip the leading slash.
999 }
1000 }
1001 }
1002 return "";
1003}
1004
Elliott Hughes46e251b2012-05-22 15:10:45 -07001005static const char* CleanMapName(const backtrace_symbol_t* symbol) {
1006 const char* map_name = symbol->map_name;
1007 if (map_name == NULL) {
1008 map_name = "???";
1009 }
1010 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1011 // into "libartd.so".
1012 const char* last_slash = strrchr(map_name, '/');
1013 if (last_slash != NULL) {
1014 map_name = last_slash + 1;
1015 }
1016 return map_name;
1017}
1018
1019static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
1020 std::string& symbol_name, uint32_t& pc_offset) {
1021 symbol_table_t* symbol_table = NULL;
1022 if (symbol->map_name != NULL) {
1023 symbol_table = load_symbol_table(symbol->map_name);
1024 }
1025 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -07001026 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001027 if (symbol_table != NULL) {
1028 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
1029 if (elf_symbol == NULL) {
1030 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -07001031 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001032 }
1033 }
1034 if (elf_symbol != NULL) {
1035 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
1036 if (demangled_symbol_name != NULL) {
1037 symbol_name = demangled_symbol_name;
1038 } else {
1039 symbol_name = elf_symbol->name;
1040 }
Elliott Hughes95aff772012-06-12 17:44:15 -07001041
1042 // TODO: is it a libcorkscrew bug that we have to do this?
1043 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001044 } else {
1045 symbol_name = "???";
1046 }
1047 free_symbol_table(symbol_table);
1048}
1049
1050void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001051 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1052 flush_my_map_info_list();
1053
Elliott Hughes46e251b2012-05-22 15:10:45 -07001054 const size_t MAX_DEPTH = 32;
1055 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001056 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
1057 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001058 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001059 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001060 return;
1061 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001062 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001063 return;
1064 }
1065
1066 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1067 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1068
1069 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1070 const backtrace_frame_t* frame = &frames[i];
1071 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1072
1073 // We produce output like this:
1074 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1075
1076 std::string symbol_name;
1077 uint32_t pc_offset = 0;
1078 if (symbol->demangled_name != NULL) {
1079 symbol_name = symbol->demangled_name;
1080 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1081 } else if (symbol->symbol_name != NULL) {
1082 symbol_name = symbol->symbol_name;
1083 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1084 } else {
1085 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1086 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1087 }
1088
1089 os << prefix;
1090 if (include_count) {
1091 os << StringPrintf("#%02zd ", i);
1092 }
1093 os << symbol_name;
1094 if (pc_offset != 0) {
1095 os << "+" << pc_offset;
1096 }
1097 os << StringPrintf(" [%p] (%s)\n",
1098 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1099 }
1100
1101 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1102}
1103
Elliott Hughes058a6de2012-05-24 19:13:02 -07001104#if defined(__APPLE__)
1105
1106// TODO: is there any way to get the kernel stack on Mac OS?
1107void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1108
1109#else
1110
Elliott Hughes46e251b2012-05-22 15:10:45 -07001111void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001112 if (tid == GetTid()) {
1113 // There's no point showing that we're reading our stack out of /proc!
1114 return;
1115 }
1116
Elliott Hughes46e251b2012-05-22 15:10:45 -07001117 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1118 std::string kernel_stack;
1119 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001120 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001121 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001122 }
1123
1124 std::vector<std::string> kernel_stack_frames;
1125 Split(kernel_stack, '\n', kernel_stack_frames);
1126 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1127 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1128 kernel_stack_frames.pop_back();
1129 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1130 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1131 const char* text = kernel_stack_frames[i].c_str();
1132 const char* close_bracket = strchr(text, ']');
1133 if (close_bracket != NULL) {
1134 text = close_bracket + 2;
1135 }
1136 os << prefix;
1137 if (include_count) {
1138 os << StringPrintf("#%02zd ", i);
1139 }
1140 os << text << "\n";
1141 }
1142}
1143
1144#endif
1145
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001146const char* GetAndroidRoot() {
1147 const char* android_root = getenv("ANDROID_ROOT");
1148 if (android_root == NULL) {
1149 if (OS::DirectoryExists("/system")) {
1150 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001151 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001152 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1153 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001154 }
1155 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001156 if (!OS::DirectoryExists(android_root)) {
1157 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001158 return "";
1159 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001160 return android_root;
1161}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001162
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001163const char* GetAndroidData() {
1164 const char* android_data = getenv("ANDROID_DATA");
1165 if (android_data == NULL) {
1166 if (OS::DirectoryExists("/data")) {
1167 android_data = "/data";
1168 } else {
1169 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1170 return "";
1171 }
1172 }
1173 if (!OS::DirectoryExists(android_data)) {
1174 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1175 return "";
1176 }
1177 return android_data;
1178}
1179
Shih-wei Liao795e3302012-04-21 00:20:57 -07001180std::string GetArtCacheOrDie(const char* android_data) {
1181 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001182
1183 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001184 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001185 int result = mkdir(art_cache.c_str(), 0700);
1186 if (result != 0) {
1187 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1188 return "";
1189 }
1190 } else {
1191 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1192 return "";
1193 }
1194 }
1195 return art_cache;
1196}
1197
jeffhao262bf462011-10-20 18:36:32 -07001198std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001199 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001200 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001201 std::string cache_file(location, 1); // skip leading slash
1202 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1203 return art_cache + "/" + cache_file;
1204}
1205
jeffhao262bf462011-10-20 18:36:32 -07001206bool IsValidZipFilename(const std::string& filename) {
1207 if (filename.size() < 4) {
1208 return false;
1209 }
1210 std::string suffix(filename.substr(filename.size() - 4));
1211 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1212}
1213
1214bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001215 return EndsWith(filename, ".dex");
1216}
1217
1218bool IsValidOatFilename(const std::string& filename) {
1219 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001220}
1221
Elliott Hughes42ee1422011-09-06 12:33:32 -07001222} // namespace art