blob: e2231c21546a0e523f5f23abf2c1369447fdfa0e [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 Rogersd81871c2011-10-03 13:57:23 -070028#include "class_loader.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070029#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070031#include "os.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070032
Elliott Hughesad6c9c32012-01-19 17:39:12 -080033#if !defined(HAVE_POSIX_CLOCKS)
34#include <sys/time.h>
35#endif
36
Elliott Hughesdcc24742011-09-07 14:02:44 -070037#if defined(HAVE_PRCTL)
38#include <sys/prctl.h>
39#endif
40
Elliott Hughes4ae722a2012-03-13 11:08:51 -070041#if defined(__APPLE__)
Elliott Hughesb08e8a32012-04-02 10:51:41 -070042#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070043#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070044#endif
45
Elliott Hughes46e251b2012-05-22 15:10:45 -070046#include <corkscrew/backtrace.h> // For DumpNativeStack.
47#include <corkscrew/demangle.h> // For DumpNativeStack.
48
Elliott Hughes058a6de2012-05-24 19:13:02 -070049#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080050#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080051#endif
52
Elliott Hughes11e45072011-08-16 17:40:46 -070053namespace art {
54
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080055pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070056#if defined(__APPLE__)
57 uint64_t owner;
58 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
59 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080060#else
61 // Neither bionic nor glibc exposes gettid(2).
62 return syscall(__NR_gettid);
63#endif
64}
65
Elliott Hughes289be852012-06-12 13:57:20 -070066std::string GetThreadName(pid_t tid) {
67 std::string result;
68 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
69 result.resize(result.size() - 1); // Lose the trailing '\n'.
70 } else {
71 result = "<unknown>";
72 }
73 return result;
74}
75
Ian Rogers120f1c72012-09-28 17:17:10 -070076void GetThreadStack(pthread_t thread, void*& stack_base, size_t& stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070077#if defined(__APPLE__)
Ian Rogers120f1c72012-09-28 17:17:10 -070078 stack_size = pthread_get_stacksize_np(thread);
79 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070080
81 // Check whether stack_addr is the base or end of the stack.
82 // (On Mac OS 10.7, it's the end.)
83 int stack_variable;
84 if (stack_addr > &stack_variable) {
85 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
86 } else {
87 stack_base = stack_addr;
88 }
89#else
90 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070091 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070092 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
93 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
94#endif
95}
96
Elliott Hughesd92bec42011-09-02 17:04:36 -070097bool ReadFileToString(const std::string& file_name, std::string* result) {
Elliott Hughes76160052012-12-12 16:31:20 -080098 UniquePtr<File> file(new File);
99 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700100 return false;
101 }
buzbeec143c552011-08-20 17:38:58 -0700102
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700103 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700104 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800105 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700106 if (n == -1) {
107 return false;
buzbeec143c552011-08-20 17:38:58 -0700108 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700109 if (n == 0) {
110 return true;
111 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700112 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700113 }
buzbeec143c552011-08-20 17:38:58 -0700114}
115
Elliott Hughese27955c2011-08-26 15:21:24 -0700116std::string GetIsoDate() {
117 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700118 tm tmbuf;
119 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700120 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
121 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
122 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
123}
124
Elliott Hughes7162ad92011-10-27 14:08:42 -0700125uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800126#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700127 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700128 clock_gettime(CLOCK_MONOTONIC, &now);
129 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800130#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700131 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800132 gettimeofday(&now, NULL);
133 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
134#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135}
136
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800137uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700139 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800140 clock_gettime(CLOCK_MONOTONIC, &now);
141 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700143 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800144 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700145 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800146#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147}
148
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700149uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700151 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700152 clock_gettime(CLOCK_MONOTONIC, &now);
153 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700155 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156 gettimeofday(&now, NULL);
157 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
158#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159}
160
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800161uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700163 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800164 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
165 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800166#else
167 UNIMPLEMENTED(WARNING);
168 return -1;
169#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800170}
171
Elliott Hughes0512f022012-03-15 22:10:52 -0700172uint64_t ThreadCpuNanoTime() {
173#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700174 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700175 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
176 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
177#else
178 UNIMPLEMENTED(WARNING);
179 return -1;
180#endif
181}
182
Ian Rogers56edc432013-01-18 16:51:51 -0800183void NanoSleep(uint64_t ns) {
184 timespec tm;
185 tm.tv_sec = 0;
186 tm.tv_nsec = ns;
187 nanosleep(&tm, NULL);
188}
189
Brian Carlstrombcc29262012-11-02 11:36:03 -0700190void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
191 int64_t endSec;
192
193 if (absolute) {
194#if !defined(__APPLE__)
195 clock_gettime(clock, ts);
196#else
197 UNUSED(clock);
198 timeval tv;
199 gettimeofday(&tv, NULL);
200 ts->tv_sec = tv.tv_sec;
201 ts->tv_nsec = tv.tv_usec * 1000;
202#endif
203 } else {
204 ts->tv_sec = 0;
205 ts->tv_nsec = 0;
206 }
207 endSec = ts->tv_sec + ms / 1000;
208 if (UNLIKELY(endSec >= 0x7fffffff)) {
209 std::ostringstream ss;
210 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
211 endSec = 0x7ffffffe;
212 }
213 ts->tv_sec = endSec;
214 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
215
216 // Catch rollover.
217 if (ts->tv_nsec >= 1000000000L) {
218 ts->tv_sec++;
219 ts->tv_nsec -= 1000000000L;
220 }
221}
222
Elliott Hughes5174fe62011-08-23 15:12:35 -0700223std::string PrettyDescriptor(const String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700224 if (java_descriptor == NULL) {
225 return "null";
226 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700227 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
228}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700229
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800230std::string PrettyDescriptor(const Class* klass) {
231 if (klass == NULL) {
232 return "null";
233 }
234 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800235}
236
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700237std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700238 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700239 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700240 size_t dim = 0;
241 while (*c == '[') {
242 dim++;
243 c++;
244 }
245
246 // Reference or primitive?
247 if (*c == 'L') {
248 // "[[La/b/C;" -> "a.b.C[][]".
249 c++; // Skip the 'L'.
250 } else {
251 // "[[B" -> "byte[][]".
252 // To make life easier, we make primitives look like unqualified
253 // reference types.
254 switch (*c) {
255 case 'B': c = "byte;"; break;
256 case 'C': c = "char;"; break;
257 case 'D': c = "double;"; break;
258 case 'F': c = "float;"; break;
259 case 'I': c = "int;"; break;
260 case 'J': c = "long;"; break;
261 case 'S': c = "short;"; break;
262 case 'Z': c = "boolean;"; break;
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700263 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700264 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700265 }
266 }
267
268 // At this point, 'c' is a string of the form "fully/qualified/Type;"
269 // or "primitive;". Rewrite the type with '.' instead of '/':
270 std::string result;
271 const char* p = c;
272 while (*p != ';') {
273 char ch = *p++;
274 if (ch == '/') {
275 ch = '.';
276 }
277 result.push_back(ch);
278 }
279 // ...and replace the semicolon with 'dim' "[]" pairs:
280 while (dim--) {
281 result += "[]";
282 }
283 return result;
284}
285
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700286std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800287 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700288 return PrettyDescriptor(descriptor_string);
289}
290
Elliott Hughes54e7df12011-09-16 11:47:04 -0700291std::string PrettyField(const Field* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700292 if (f == NULL) {
293 return "null";
294 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800295 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700296 std::string result;
297 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800298 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700299 result += ' ';
300 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800301 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700302 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800303 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700304 return result;
305}
306
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700307std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
308 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
309 std::string result;
310 if (with_type) {
311 result += dex_file.GetFieldTypeDescriptor(field_id);
312 result += ' ';
313 }
314 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
315 result += '.';
316 result += dex_file.GetFieldName(field_id);
317 return result;
318}
319
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700320std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
321 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700322 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700323}
324
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700325std::string PrettyArguments(const char* signature) {
326 std::string result;
327 result += '(';
328 CHECK_EQ(*signature, '(');
329 ++signature; // Skip the '('.
330 while (*signature != ')') {
331 size_t argument_length = 0;
332 while (signature[argument_length] == '[') {
333 ++argument_length;
334 }
335 if (signature[argument_length] == 'L') {
336 argument_length = (strchr(signature, ';') - signature + 1);
337 } else {
338 ++argument_length;
339 }
340 std::string argument_descriptor(signature, argument_length);
341 result += PrettyDescriptor(argument_descriptor);
342 if (signature[argument_length] != ')') {
343 result += ", ";
344 }
345 signature += argument_length;
346 }
347 CHECK_EQ(*signature, ')');
348 ++signature; // Skip the ')'.
349 result += ')';
350 return result;
351}
352
353std::string PrettyReturnType(const char* signature) {
354 const char* return_type = strchr(signature, ')');
355 CHECK(return_type != NULL);
356 ++return_type; // Skip ')'.
357 return PrettyDescriptor(return_type);
358}
359
Mathieu Chartier66f19252012-09-18 08:57:04 -0700360std::string PrettyMethod(const AbstractMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700361 if (m == NULL) {
362 return "null";
363 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800364 MethodHelper mh(m);
365 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700366 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800367 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700368 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700369 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700370 if (signature == "<no signature>") {
371 return result + signature;
372 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700373 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700374 }
375 return result;
376}
377
Ian Rogers0571d352011-11-03 19:51:38 -0700378std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
379 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
380 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
381 result += '.';
382 result += dex_file.GetMethodName(method_id);
383 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700384 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700385 if (signature == "<no signature>") {
386 return result + signature;
387 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700388 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700389 }
390 return result;
391}
392
Elliott Hughes54e7df12011-09-16 11:47:04 -0700393std::string PrettyTypeOf(const Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700394 if (obj == NULL) {
395 return "null";
396 }
397 if (obj->GetClass() == NULL) {
398 return "(raw)";
399 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800400 ClassHelper kh(obj->GetClass());
401 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700402 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800403 kh.ChangeClass(obj->AsClass());
404 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700405 }
406 return result;
407}
408
Elliott Hughes54e7df12011-09-16 11:47:04 -0700409std::string PrettyClass(const Class* c) {
410 if (c == NULL) {
411 return "null";
412 }
413 std::string result;
414 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800415 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700416 result += ">";
417 return result;
418}
419
Ian Rogersd81871c2011-10-03 13:57:23 -0700420std::string PrettyClassAndClassLoader(const Class* c) {
421 if (c == NULL) {
422 return "null";
423 }
424 std::string result;
425 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800426 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700427 result += ",";
428 result += PrettyTypeOf(c->GetClassLoader());
429 // TODO: add an identifying hash value for the loader
430 result += ">";
431 return result;
432}
433
Elliott Hughesc967f782012-04-16 10:23:15 -0700434std::string PrettySize(size_t byte_count) {
435 // The byte thresholds at which we display amounts. A byte count is displayed
436 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
437 static const size_t kUnitThresholds[] = {
438 0, // B up to...
439 3*1024, // KB up to...
440 2*1024*1024, // MB up to...
441 1024*1024*1024 // GB from here.
442 };
443 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
444 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
445
446 int i = arraysize(kUnitThresholds);
447 while (--i > 0) {
448 if (byte_count >= kUnitThresholds[i]) {
449 break;
450 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800451 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700452
453 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800454}
455
456std::string PrettyDuration(uint64_t nano_duration) {
457 if (nano_duration == 0) {
458 return "0";
459 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700460 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
461 }
462}
463
464TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
465 const uint64_t one_sec = 1000 * 1000 * 1000;
466 const uint64_t one_ms = 1000 * 1000;
467 const uint64_t one_us = 1000;
468 if (nano_duration >= one_sec) {
469 return kTimeUnitSecond;
470 } else if (nano_duration >= one_ms) {
471 return kTimeUnitMillisecond;
472 } else if (nano_duration >= one_us) {
473 return kTimeUnitMicrosecond;
474 } else {
475 return kTimeUnitNanosecond;
476 }
477}
478
479uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
480 const uint64_t one_sec = 1000 * 1000 * 1000;
481 const uint64_t one_ms = 1000 * 1000;
482 const uint64_t one_us = 1000;
483
484 switch (time_unit) {
485 case kTimeUnitSecond:
486 return one_sec;
487 case kTimeUnitMillisecond:
488 return one_ms;
489 case kTimeUnitMicrosecond:
490 return one_us;
491 case kTimeUnitNanosecond:
492 return 1;
493 }
494 return 0;
495}
496
497std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
498 const char* unit = NULL;
499 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
500 uint32_t zero_fill = 1;
501 switch (time_unit) {
502 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800503 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800504 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700505 break;
506 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800507 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800508 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700509 break;
510 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800511 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800512 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700513 break;
514 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800515 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800516 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700517 break;
518 }
519
520 uint64_t whole_part = nano_duration / divisor;
521 uint64_t fractional_part = nano_duration % divisor;
522 if (fractional_part == 0) {
523 return StringPrintf("%llu%s", whole_part, unit);
524 } else {
525 while ((fractional_part % 1000) == 0) {
526 zero_fill -= 3;
527 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800528 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700529 if (zero_fill == 3) {
530 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
531 } else if (zero_fill == 6) {
532 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800533 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700534 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800535 }
536 }
537}
538
Elliott Hughes82914b62012-04-09 15:56:29 -0700539std::string PrintableString(const std::string& utf) {
540 std::string result;
541 result += '"';
542 const char* p = utf.c_str();
543 size_t char_count = CountModifiedUtf8Chars(p);
544 for (size_t i = 0; i < char_count; ++i) {
545 uint16_t ch = GetUtf16FromUtf8(&p);
546 if (ch == '\\') {
547 result += "\\\\";
548 } else if (ch == '\n') {
549 result += "\\n";
550 } else if (ch == '\r') {
551 result += "\\r";
552 } else if (ch == '\t') {
553 result += "\\t";
554 } else if (NeedsEscaping(ch)) {
555 StringAppendF(&result, "\\u%04x", ch);
556 } else {
557 result += ch;
558 }
559 }
560 result += '"';
561 return result;
562}
563
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800564// 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 -0700565std::string MangleForJni(const std::string& s) {
566 std::string result;
567 size_t char_count = CountModifiedUtf8Chars(s.c_str());
568 const char* cp = &s[0];
569 for (size_t i = 0; i < char_count; ++i) {
570 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800571 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
572 result.push_back(ch);
573 } else if (ch == '.' || ch == '/') {
574 result += "_";
575 } else if (ch == '_') {
576 result += "_1";
577 } else if (ch == ';') {
578 result += "_2";
579 } else if (ch == '[') {
580 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700581 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800582 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700583 }
584 }
585 return result;
586}
587
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700588std::string DotToDescriptor(const char* class_name) {
589 std::string descriptor(class_name);
590 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
591 if (descriptor.length() > 0 && descriptor[0] != '[') {
592 descriptor = "L" + descriptor + ";";
593 }
594 return descriptor;
595}
596
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800597std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800598 size_t length = strlen(descriptor);
599 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
600 std::string result(descriptor + 1, length - 2);
601 std::replace(result.begin(), result.end(), '/', '.');
602 return result;
603 }
604 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800605}
606
607std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800608 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800609 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
610 std::string result(descriptor + 1, length - 2);
611 return result;
612 }
613 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700614}
615
Mathieu Chartier66f19252012-09-18 08:57:04 -0700616std::string JniShortName(const AbstractMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800617 MethodHelper mh(m);
618 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700619 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700620 CHECK_EQ(class_name[0], 'L') << class_name;
621 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700622 class_name.erase(0, 1);
623 class_name.erase(class_name.size() - 1, 1);
624
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800625 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700626
627 std::string short_name;
628 short_name += "Java_";
629 short_name += MangleForJni(class_name);
630 short_name += "_";
631 short_name += MangleForJni(method_name);
632 return short_name;
633}
634
Mathieu Chartier66f19252012-09-18 08:57:04 -0700635std::string JniLongName(const AbstractMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700636 std::string long_name;
637 long_name += JniShortName(m);
638 long_name += "__";
639
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800640 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700641 signature.erase(0, 1);
642 signature.erase(signature.begin() + signature.find(')'), signature.end());
643
644 long_name += MangleForJni(signature);
645
646 return long_name;
647}
648
jeffhao10037c82012-01-23 15:06:23 -0800649// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700650uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
651 0x00000000, // 00..1f low control characters; nothing valid
652 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
653 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
654 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
655};
656
jeffhao10037c82012-01-23 15:06:23 -0800657// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
658bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700659 /*
660 * It's a multibyte encoded character. Decode it and analyze. We
661 * accept anything that isn't (a) an improperly encoded low value,
662 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
663 * control character, or (e) a high space, layout, or special
664 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
665 * U+fff0..U+ffff). This is all specified in the dex format
666 * document.
667 */
668
669 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
670
671 // Perform follow-up tests based on the high 8 bits.
672 switch (utf16 >> 8) {
673 case 0x00:
674 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
675 return (utf16 > 0x00a0);
676 case 0xd8:
677 case 0xd9:
678 case 0xda:
679 case 0xdb:
680 // It's a leading surrogate. Check to see that a trailing
681 // surrogate follows.
682 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
683 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
684 case 0xdc:
685 case 0xdd:
686 case 0xde:
687 case 0xdf:
688 // It's a trailing surrogate, which is not valid at this point.
689 return false;
690 case 0x20:
691 case 0xff:
692 // It's in the range that has spaces, controls, and specials.
693 switch (utf16 & 0xfff8) {
694 case 0x2000:
695 case 0x2008:
696 case 0x2028:
697 case 0xfff0:
698 case 0xfff8:
699 return false;
700 }
701 break;
702 }
703 return true;
704}
705
706/* Return whether the pointed-at modified-UTF-8 encoded character is
707 * valid as part of a member name, updating the pointer to point past
708 * the consumed character. This will consume two encoded UTF-16 code
709 * points if the character is encoded as a surrogate pair. Also, if
710 * this function returns false, then the given pointer may only have
711 * been partially advanced.
712 */
jeffhao10037c82012-01-23 15:06:23 -0800713bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700714 uint8_t c = (uint8_t) **pUtf8Ptr;
715 if (c <= 0x7f) {
716 // It's low-ascii, so check the table.
717 uint32_t wordIdx = c >> 5;
718 uint32_t bitIdx = c & 0x1f;
719 (*pUtf8Ptr)++;
720 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
721 }
722
723 // It's a multibyte encoded character. Call a non-inline function
724 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800725 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
726}
727
728bool IsValidMemberName(const char* s) {
729 bool angle_name = false;
730
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700731 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800732 case '\0':
733 // The empty string is not a valid name.
734 return false;
735 case '<':
736 angle_name = true;
737 s++;
738 break;
739 }
740
741 while (true) {
742 switch (*s) {
743 case '\0':
744 return !angle_name;
745 case '>':
746 return angle_name && s[1] == '\0';
747 }
748
749 if (!IsValidPartOfMemberNameUtf8(&s)) {
750 return false;
751 }
752 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700753}
754
Elliott Hughes906e6852011-10-28 14:52:10 -0700755enum ClassNameType { kName, kDescriptor };
756bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700757 int arrayCount = 0;
758 while (*s == '[') {
759 arrayCount++;
760 s++;
761 }
762
763 if (arrayCount > 255) {
764 // Arrays may have no more than 255 dimensions.
765 return false;
766 }
767
768 if (arrayCount != 0) {
769 /*
770 * If we're looking at an array of some sort, then it doesn't
771 * matter if what is being asked for is a class name; the
772 * format looks the same as a type descriptor in that case, so
773 * treat it as such.
774 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700775 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700776 }
777
Elliott Hughes906e6852011-10-28 14:52:10 -0700778 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700779 /*
780 * We are looking for a descriptor. Either validate it as a
781 * single-character primitive type, or continue on to check the
782 * embedded class name (bracketed by "L" and ";").
783 */
784 switch (*(s++)) {
785 case 'B':
786 case 'C':
787 case 'D':
788 case 'F':
789 case 'I':
790 case 'J':
791 case 'S':
792 case 'Z':
793 // These are all single-character descriptors for primitive types.
794 return (*s == '\0');
795 case 'V':
796 // Non-array void is valid, but you can't have an array of void.
797 return (arrayCount == 0) && (*s == '\0');
798 case 'L':
799 // Class name: Break out and continue below.
800 break;
801 default:
802 // Oddball descriptor character.
803 return false;
804 }
805 }
806
807 /*
808 * We just consumed the 'L' that introduces a class name as part
809 * of a type descriptor, or we are looking for an unadorned class
810 * name.
811 */
812
813 bool sepOrFirst = true; // first character or just encountered a separator.
814 for (;;) {
815 uint8_t c = (uint8_t) *s;
816 switch (c) {
817 case '\0':
818 /*
819 * Premature end for a type descriptor, but valid for
820 * a class name as long as we haven't encountered an
821 * empty component (including the degenerate case of
822 * the empty string "").
823 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700824 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700825 case ';':
826 /*
827 * Invalid character for a class name, but the
828 * legitimate end of a type descriptor. In the latter
829 * case, make sure that this is the end of the string
830 * and that it doesn't end with an empty component
831 * (including the degenerate case of "L;").
832 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700833 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700834 case '/':
835 case '.':
836 if (c != separator) {
837 // The wrong separator character.
838 return false;
839 }
840 if (sepOrFirst) {
841 // Separator at start or two separators in a row.
842 return false;
843 }
844 sepOrFirst = true;
845 s++;
846 break;
847 default:
jeffhao10037c82012-01-23 15:06:23 -0800848 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700849 return false;
850 }
851 sepOrFirst = false;
852 break;
853 }
854 }
855}
856
Elliott Hughes906e6852011-10-28 14:52:10 -0700857bool IsValidBinaryClassName(const char* s) {
858 return IsValidClassName(s, kName, '.');
859}
860
861bool IsValidJniClassName(const char* s) {
862 return IsValidClassName(s, kName, '/');
863}
864
865bool IsValidDescriptor(const char* s) {
866 return IsValidClassName(s, kDescriptor, '/');
867}
868
Elliott Hughes48436bb2012-02-07 15:23:28 -0800869void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700870 const char* p = s.data();
871 const char* end = p + s.size();
872 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800873 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700874 ++p;
875 } else {
876 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800877 while (++p != end && *p != separator) {
878 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700879 }
880 result.push_back(std::string(start, p - start));
881 }
882 }
883}
884
Elliott Hughes48436bb2012-02-07 15:23:28 -0800885template <typename StringT>
886std::string Join(std::vector<StringT>& strings, char separator) {
887 if (strings.empty()) {
888 return "";
889 }
890
891 std::string result(strings[0]);
892 for (size_t i = 1; i < strings.size(); ++i) {
893 result += separator;
894 result += strings[i];
895 }
896 return result;
897}
898
899// Explicit instantiations.
900template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
901template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
902template std::string Join<char*>(std::vector<char*>& strings, char separator);
903
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800904bool StartsWith(const std::string& s, const char* prefix) {
905 return s.compare(0, strlen(prefix), prefix) == 0;
906}
907
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700908bool EndsWith(const std::string& s, const char* suffix) {
909 size_t suffix_length = strlen(suffix);
910 size_t string_length = s.size();
911 if (suffix_length > string_length) {
912 return false;
913 }
914 size_t offset = string_length - suffix_length;
915 return s.compare(offset, suffix_length, suffix) == 0;
916}
917
Elliott Hughes22869a92012-03-27 14:08:24 -0700918void SetThreadName(const char* thread_name) {
919 ANNOTATE_THREAD_NAME(thread_name); // For tsan.
Elliott Hughes06e3ad42012-02-07 14:51:57 -0800920
Elliott Hughesdcc24742011-09-07 14:02:44 -0700921 int hasAt = 0;
922 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700923 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700924 while (*s) {
925 if (*s == '.') {
926 hasDot = 1;
927 } else if (*s == '@') {
928 hasAt = 1;
929 }
930 s++;
931 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700932 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700933 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700934 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700935 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700936 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700937 }
938#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700939 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700940 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
941 strncpy(buf, s, sizeof(buf)-1);
942 buf[sizeof(buf)-1] = '\0';
943 errno = pthread_setname_np(pthread_self(), buf);
944 if (errno != 0) {
945 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
946 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700947#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700948 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700949#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700950 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700951#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700952 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700953#endif
954}
955
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700956void GetTaskStats(pid_t tid, char& state, int& utime, int& stime, int& task_cpu) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700957 utime = stime = task_cpu = 0;
958 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700959 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700960 return;
961 }
962 // Skip the command, which may contain spaces.
963 stats = stats.substr(stats.find(')') + 2);
964 // Extract the three fields we care about.
965 std::vector<std::string> fields;
966 Split(stats, ' ', fields);
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700967 state = fields[0][0];
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700968 utime = strtoull(fields[11].c_str(), NULL, 10);
969 stime = strtoull(fields[12].c_str(), NULL, 10);
970 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
971}
972
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700973std::string GetSchedulerGroupName(pid_t tid) {
974 // /proc/<pid>/cgroup looks like this:
975 // 2:devices:/
976 // 1:cpuacct,cpu:/
977 // We want the third field from the line whose second field contains the "cpu" token.
978 std::string cgroup_file;
979 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
980 return "";
981 }
982 std::vector<std::string> cgroup_lines;
983 Split(cgroup_file, '\n', cgroup_lines);
984 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
985 std::vector<std::string> cgroup_fields;
986 Split(cgroup_lines[i], ':', cgroup_fields);
987 std::vector<std::string> cgroups;
988 Split(cgroup_fields[1], ',', cgroups);
989 for (size_t i = 0; i < cgroups.size(); ++i) {
990 if (cgroups[i] == "cpu") {
991 return cgroup_fields[2].substr(1); // Skip the leading slash.
992 }
993 }
994 }
995 return "";
996}
997
Elliott Hughes46e251b2012-05-22 15:10:45 -0700998static const char* CleanMapName(const backtrace_symbol_t* symbol) {
999 const char* map_name = symbol->map_name;
1000 if (map_name == NULL) {
1001 map_name = "???";
1002 }
1003 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1004 // into "libartd.so".
1005 const char* last_slash = strrchr(map_name, '/');
1006 if (last_slash != NULL) {
1007 map_name = last_slash + 1;
1008 }
1009 return map_name;
1010}
1011
1012static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
1013 std::string& symbol_name, uint32_t& pc_offset) {
1014 symbol_table_t* symbol_table = NULL;
1015 if (symbol->map_name != NULL) {
1016 symbol_table = load_symbol_table(symbol->map_name);
1017 }
1018 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -07001019 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001020 if (symbol_table != NULL) {
1021 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
1022 if (elf_symbol == NULL) {
1023 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -07001024 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001025 }
1026 }
1027 if (elf_symbol != NULL) {
1028 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
1029 if (demangled_symbol_name != NULL) {
1030 symbol_name = demangled_symbol_name;
1031 } else {
1032 symbol_name = elf_symbol->name;
1033 }
Elliott Hughes95aff772012-06-12 17:44:15 -07001034
1035 // TODO: is it a libcorkscrew bug that we have to do this?
1036 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001037 } else {
1038 symbol_name = "???";
1039 }
1040 free_symbol_table(symbol_table);
1041}
1042
1043void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001044 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1045 flush_my_map_info_list();
1046
Elliott Hughes46e251b2012-05-22 15:10:45 -07001047 const size_t MAX_DEPTH = 32;
1048 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001049 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
1050 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001051 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001052 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001053 return;
1054 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001055 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001056 return;
1057 }
1058
1059 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1060 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1061
1062 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1063 const backtrace_frame_t* frame = &frames[i];
1064 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1065
1066 // We produce output like this:
1067 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1068
1069 std::string symbol_name;
1070 uint32_t pc_offset = 0;
1071 if (symbol->demangled_name != NULL) {
1072 symbol_name = symbol->demangled_name;
1073 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1074 } else if (symbol->symbol_name != NULL) {
1075 symbol_name = symbol->symbol_name;
1076 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1077 } else {
1078 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1079 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1080 }
1081
1082 os << prefix;
1083 if (include_count) {
1084 os << StringPrintf("#%02zd ", i);
1085 }
1086 os << symbol_name;
1087 if (pc_offset != 0) {
1088 os << "+" << pc_offset;
1089 }
1090 os << StringPrintf(" [%p] (%s)\n",
1091 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1092 }
1093
1094 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1095}
1096
Elliott Hughes058a6de2012-05-24 19:13:02 -07001097#if defined(__APPLE__)
1098
1099// TODO: is there any way to get the kernel stack on Mac OS?
1100void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1101
1102#else
1103
Elliott Hughes46e251b2012-05-22 15:10:45 -07001104void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001105 if (tid == GetTid()) {
1106 // There's no point showing that we're reading our stack out of /proc!
1107 return;
1108 }
1109
Elliott Hughes46e251b2012-05-22 15:10:45 -07001110 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1111 std::string kernel_stack;
1112 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001113 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001114 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001115 }
1116
1117 std::vector<std::string> kernel_stack_frames;
1118 Split(kernel_stack, '\n', kernel_stack_frames);
1119 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1120 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1121 kernel_stack_frames.pop_back();
1122 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1123 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1124 const char* text = kernel_stack_frames[i].c_str();
1125 const char* close_bracket = strchr(text, ']');
1126 if (close_bracket != NULL) {
1127 text = close_bracket + 2;
1128 }
1129 os << prefix;
1130 if (include_count) {
1131 os << StringPrintf("#%02zd ", i);
1132 }
1133 os << text << "\n";
1134 }
1135}
1136
1137#endif
1138
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001139const char* GetAndroidRoot() {
1140 const char* android_root = getenv("ANDROID_ROOT");
1141 if (android_root == NULL) {
1142 if (OS::DirectoryExists("/system")) {
1143 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001144 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001145 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1146 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001147 }
1148 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001149 if (!OS::DirectoryExists(android_root)) {
1150 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001151 return "";
1152 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001153 return android_root;
1154}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001155
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001156const char* GetAndroidData() {
1157 const char* android_data = getenv("ANDROID_DATA");
1158 if (android_data == NULL) {
1159 if (OS::DirectoryExists("/data")) {
1160 android_data = "/data";
1161 } else {
1162 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1163 return "";
1164 }
1165 }
1166 if (!OS::DirectoryExists(android_data)) {
1167 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1168 return "";
1169 }
1170 return android_data;
1171}
1172
Shih-wei Liao795e3302012-04-21 00:20:57 -07001173std::string GetArtCacheOrDie(const char* android_data) {
1174 std::string art_cache(StringPrintf("%s/art-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001175
1176 if (!OS::DirectoryExists(art_cache.c_str())) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -08001177 if (StartsWith(art_cache, "/tmp/")) {
Brian Carlstroma9f19782011-10-13 00:14:47 -07001178 int result = mkdir(art_cache.c_str(), 0700);
1179 if (result != 0) {
1180 LOG(FATAL) << "Failed to create art-cache directory " << art_cache;
1181 return "";
1182 }
1183 } else {
1184 LOG(FATAL) << "Failed to find art-cache directory " << art_cache;
1185 return "";
1186 }
1187 }
1188 return art_cache;
1189}
1190
jeffhao262bf462011-10-20 18:36:32 -07001191std::string GetArtCacheFilenameOrDie(const std::string& location) {
Shih-wei Liao795e3302012-04-21 00:20:57 -07001192 std::string art_cache(GetArtCacheOrDie(GetAndroidData()));
Elliott Hughesc308a5d2012-02-16 17:12:06 -08001193 CHECK_EQ(location[0], '/') << location;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001194 std::string cache_file(location, 1); // skip leading slash
1195 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1196 return art_cache + "/" + cache_file;
1197}
1198
jeffhao262bf462011-10-20 18:36:32 -07001199bool IsValidZipFilename(const std::string& filename) {
1200 if (filename.size() < 4) {
1201 return false;
1202 }
1203 std::string suffix(filename.substr(filename.size() - 4));
1204 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1205}
1206
1207bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001208 return EndsWith(filename, ".dex");
1209}
1210
1211bool IsValidOatFilename(const std::string& filename) {
1212 return EndsWith(filename, ".oat");
jeffhao262bf462011-10-20 18:36:32 -07001213}
1214
Elliott Hughes42ee1422011-09-06 12:33:32 -07001215} // namespace art