blob: 6856bb76de8ea6ed9a7c09f1275d12cf843e83a5 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Elliott Hughes11e45072011-08-16 17:40:46 -070016
Elliott Hughes42ee1422011-09-06 12:33:32 -070017#include "utils.h"
18
Elliott Hughes92b3b562011-09-08 16:32:26 -070019#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070020#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070021#include <sys/syscall.h>
22#include <sys/types.h>
23#include <unistd.h>
24
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include "UniquePtr.h"
Elliott Hughes76160052012-12-12 16:31:20 -080026#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070028#include "mirror/art_field-inl.h"
29#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "mirror/object-inl.h"
33#include "mirror/object_array-inl.h"
34#include "mirror/string.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080035#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070036#include "os.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080037#include "utf.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070038
Elliott Hughesad6c9c32012-01-19 17:39:12 -080039#if !defined(HAVE_POSIX_CLOCKS)
40#include <sys/time.h>
41#endif
42
Elliott Hughesdcc24742011-09-07 14:02:44 -070043#if defined(HAVE_PRCTL)
44#include <sys/prctl.h>
45#endif
46
Elliott Hughes4ae722a2012-03-13 11:08:51 -070047#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070048#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070049#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070050#endif
51
Brian Carlstrom7934ac22013-07-26 10:54:15 -070052#include <corkscrew/backtrace.h> // For DumpNativeStack.
53#include <corkscrew/demangle.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070054
Elliott Hughes058a6de2012-05-24 19:13:02 -070055#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080056#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080057#endif
58
Elliott Hughes11e45072011-08-16 17:40:46 -070059namespace art {
60
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080061pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070062#if defined(__APPLE__)
63 uint64_t owner;
64 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
65 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080066#else
67 // Neither bionic nor glibc exposes gettid(2).
68 return syscall(__NR_gettid);
69#endif
70}
71
Elliott Hughes289be852012-06-12 13:57:20 -070072std::string GetThreadName(pid_t tid) {
73 std::string result;
74 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070075 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070076 } else {
77 result = "<unknown>";
78 }
79 return result;
80}
81
Ian Rogers120f1c72012-09-28 17:17:10 -070082void GetThreadStack(pthread_t thread, void*& stack_base, size_t& stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070083#if defined(__APPLE__)
Ian Rogers120f1c72012-09-28 17:17:10 -070084 stack_size = pthread_get_stacksize_np(thread);
85 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070086
87 // Check whether stack_addr is the base or end of the stack.
88 // (On Mac OS 10.7, it's the end.)
89 int stack_variable;
90 if (stack_addr > &stack_variable) {
91 stack_base = reinterpret_cast<byte*>(stack_addr) - stack_size;
92 } else {
93 stack_base = stack_addr;
94 }
95#else
96 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070097 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070098 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, &stack_base, &stack_size), __FUNCTION__);
99 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
100#endif
101}
102
Elliott Hughesd92bec42011-09-02 17:04:36 -0700103bool ReadFileToString(const std::string& file_name, std::string* result) {
Elliott Hughes76160052012-12-12 16:31:20 -0800104 UniquePtr<File> file(new File);
105 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700106 return false;
107 }
buzbeec143c552011-08-20 17:38:58 -0700108
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700109 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700110 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800111 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700112 if (n == -1) {
113 return false;
buzbeec143c552011-08-20 17:38:58 -0700114 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700115 if (n == 0) {
116 return true;
117 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700118 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700119 }
buzbeec143c552011-08-20 17:38:58 -0700120}
121
Elliott Hughese27955c2011-08-26 15:21:24 -0700122std::string GetIsoDate() {
123 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700124 tm tmbuf;
125 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700126 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
127 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
128 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
129}
130
Elliott Hughes7162ad92011-10-27 14:08:42 -0700131uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800132#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700133 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700134 clock_gettime(CLOCK_MONOTONIC, &now);
135 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800136#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700137 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800138 gettimeofday(&now, NULL);
139 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
140#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700141}
142
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800143uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800144#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700145 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800146 clock_gettime(CLOCK_MONOTONIC, &now);
147 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800148#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700149 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800150 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700151 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800152#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800153}
154
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700155uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700157 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700158 clock_gettime(CLOCK_MONOTONIC, &now);
159 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800160#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700161 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800162 gettimeofday(&now, NULL);
163 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
164#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700165}
166
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800167uint64_t ThreadCpuMicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800168#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700169 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800170 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
171 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800172#else
173 UNIMPLEMENTED(WARNING);
174 return -1;
175#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800176}
177
Elliott Hughes0512f022012-03-15 22:10:52 -0700178uint64_t ThreadCpuNanoTime() {
179#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700180 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700181 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
182 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
183#else
184 UNIMPLEMENTED(WARNING);
185 return -1;
186#endif
187}
188
Ian Rogers56edc432013-01-18 16:51:51 -0800189void NanoSleep(uint64_t ns) {
190 timespec tm;
191 tm.tv_sec = 0;
192 tm.tv_nsec = ns;
193 nanosleep(&tm, NULL);
194}
195
Brian Carlstrombcc29262012-11-02 11:36:03 -0700196void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
197 int64_t endSec;
198
199 if (absolute) {
200#if !defined(__APPLE__)
201 clock_gettime(clock, ts);
202#else
203 UNUSED(clock);
204 timeval tv;
205 gettimeofday(&tv, NULL);
206 ts->tv_sec = tv.tv_sec;
207 ts->tv_nsec = tv.tv_usec * 1000;
208#endif
209 } else {
210 ts->tv_sec = 0;
211 ts->tv_nsec = 0;
212 }
213 endSec = ts->tv_sec + ms / 1000;
214 if (UNLIKELY(endSec >= 0x7fffffff)) {
215 std::ostringstream ss;
216 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
217 endSec = 0x7ffffffe;
218 }
219 ts->tv_sec = endSec;
220 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
221
222 // Catch rollover.
223 if (ts->tv_nsec >= 1000000000L) {
224 ts->tv_sec++;
225 ts->tv_nsec -= 1000000000L;
226 }
227}
228
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800229std::string PrettyDescriptor(const mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700230 if (java_descriptor == NULL) {
231 return "null";
232 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700233 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
234}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700235
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800236std::string PrettyDescriptor(const mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800237 if (klass == NULL) {
238 return "null";
239 }
240 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800241}
242
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700243std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700244 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700245 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700246 size_t dim = 0;
247 while (*c == '[') {
248 dim++;
249 c++;
250 }
251
252 // Reference or primitive?
253 if (*c == 'L') {
254 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700255 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700256 } else {
257 // "[[B" -> "byte[][]".
258 // To make life easier, we make primitives look like unqualified
259 // reference types.
260 switch (*c) {
261 case 'B': c = "byte;"; break;
262 case 'C': c = "char;"; break;
263 case 'D': c = "double;"; break;
264 case 'F': c = "float;"; break;
265 case 'I': c = "int;"; break;
266 case 'J': c = "long;"; break;
267 case 'S': c = "short;"; break;
268 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700269 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700270 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700271 }
272 }
273
274 // At this point, 'c' is a string of the form "fully/qualified/Type;"
275 // or "primitive;". Rewrite the type with '.' instead of '/':
276 std::string result;
277 const char* p = c;
278 while (*p != ';') {
279 char ch = *p++;
280 if (ch == '/') {
281 ch = '.';
282 }
283 result.push_back(ch);
284 }
285 // ...and replace the semicolon with 'dim' "[]" pairs:
286 while (dim--) {
287 result += "[]";
288 }
289 return result;
290}
291
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700292std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800293 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700294 return PrettyDescriptor(descriptor_string);
295}
296
Brian Carlstromea46f952013-07-30 01:26:50 -0700297std::string PrettyField(const mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700298 if (f == NULL) {
299 return "null";
300 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800301 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700302 std::string result;
303 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800304 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700305 result += ' ';
306 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800307 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700308 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800309 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700310 return result;
311}
312
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700313std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800314 if (field_idx >= dex_file.NumFieldIds()) {
315 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
316 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700317 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
318 std::string result;
319 if (with_type) {
320 result += dex_file.GetFieldTypeDescriptor(field_id);
321 result += ' ';
322 }
323 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
324 result += '.';
325 result += dex_file.GetFieldName(field_id);
326 return result;
327}
328
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700329std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800330 if (type_idx >= dex_file.NumTypeIds()) {
331 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
332 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700333 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700334 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700335}
336
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700337std::string PrettyArguments(const char* signature) {
338 std::string result;
339 result += '(';
340 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700341 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700342 while (*signature != ')') {
343 size_t argument_length = 0;
344 while (signature[argument_length] == '[') {
345 ++argument_length;
346 }
347 if (signature[argument_length] == 'L') {
348 argument_length = (strchr(signature, ';') - signature + 1);
349 } else {
350 ++argument_length;
351 }
352 std::string argument_descriptor(signature, argument_length);
353 result += PrettyDescriptor(argument_descriptor);
354 if (signature[argument_length] != ')') {
355 result += ", ";
356 }
357 signature += argument_length;
358 }
359 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700360 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700361 result += ')';
362 return result;
363}
364
365std::string PrettyReturnType(const char* signature) {
366 const char* return_type = strchr(signature, ')');
367 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700368 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700369 return PrettyDescriptor(return_type);
370}
371
Brian Carlstromea46f952013-07-30 01:26:50 -0700372std::string PrettyMethod(const mirror::ArtMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700373 if (m == NULL) {
374 return "null";
375 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800376 MethodHelper mh(m);
377 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700378 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800379 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700380 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700381 std::string signature(mh.GetSignature());
Elliott Hughesf8c11932012-03-23 19:53:59 -0700382 if (signature == "<no signature>") {
383 return result + signature;
384 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700385 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700386 }
387 return result;
388}
389
Ian Rogers0571d352011-11-03 19:51:38 -0700390std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800391 if (method_idx >= dex_file.NumMethodIds()) {
392 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
393 }
Ian Rogers0571d352011-11-03 19:51:38 -0700394 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
395 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
396 result += '.';
397 result += dex_file.GetMethodName(method_id);
398 if (with_signature) {
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700399 std::string signature(dex_file.GetMethodSignature(method_id));
Elliott Hughesf8c11932012-03-23 19:53:59 -0700400 if (signature == "<no signature>") {
401 return result + signature;
402 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700403 result = PrettyReturnType(signature.c_str()) + " " + result + PrettyArguments(signature.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700404 }
405 return result;
406}
407
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800408std::string PrettyTypeOf(const mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700409 if (obj == NULL) {
410 return "null";
411 }
412 if (obj->GetClass() == NULL) {
413 return "(raw)";
414 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800415 ClassHelper kh(obj->GetClass());
416 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700417 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800418 kh.ChangeClass(obj->AsClass());
419 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700420 }
421 return result;
422}
423
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800424std::string PrettyClass(const mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700425 if (c == NULL) {
426 return "null";
427 }
428 std::string result;
429 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800430 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700431 result += ">";
432 return result;
433}
434
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800435std::string PrettyClassAndClassLoader(const mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700436 if (c == NULL) {
437 return "null";
438 }
439 std::string result;
440 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800441 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700442 result += ",";
443 result += PrettyTypeOf(c->GetClassLoader());
444 // TODO: add an identifying hash value for the loader
445 result += ">";
446 return result;
447}
448
Elliott Hughesc967f782012-04-16 10:23:15 -0700449std::string PrettySize(size_t byte_count) {
450 // The byte thresholds at which we display amounts. A byte count is displayed
451 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
452 static const size_t kUnitThresholds[] = {
453 0, // B up to...
454 3*1024, // KB up to...
455 2*1024*1024, // MB up to...
456 1024*1024*1024 // GB from here.
457 };
458 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
459 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
460
461 int i = arraysize(kUnitThresholds);
462 while (--i > 0) {
463 if (byte_count >= kUnitThresholds[i]) {
464 break;
465 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800466 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700467
468 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800469}
470
471std::string PrettyDuration(uint64_t nano_duration) {
472 if (nano_duration == 0) {
473 return "0";
474 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700475 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
476 }
477}
478
479TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
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 if (nano_duration >= one_sec) {
484 return kTimeUnitSecond;
485 } else if (nano_duration >= one_ms) {
486 return kTimeUnitMillisecond;
487 } else if (nano_duration >= one_us) {
488 return kTimeUnitMicrosecond;
489 } else {
490 return kTimeUnitNanosecond;
491 }
492}
493
494uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
495 const uint64_t one_sec = 1000 * 1000 * 1000;
496 const uint64_t one_ms = 1000 * 1000;
497 const uint64_t one_us = 1000;
498
499 switch (time_unit) {
500 case kTimeUnitSecond:
501 return one_sec;
502 case kTimeUnitMillisecond:
503 return one_ms;
504 case kTimeUnitMicrosecond:
505 return one_us;
506 case kTimeUnitNanosecond:
507 return 1;
508 }
509 return 0;
510}
511
512std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
513 const char* unit = NULL;
514 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
515 uint32_t zero_fill = 1;
516 switch (time_unit) {
517 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800518 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800519 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700520 break;
521 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800522 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800523 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700524 break;
525 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800526 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800527 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700528 break;
529 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800530 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800531 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700532 break;
533 }
534
535 uint64_t whole_part = nano_duration / divisor;
536 uint64_t fractional_part = nano_duration % divisor;
537 if (fractional_part == 0) {
538 return StringPrintf("%llu%s", whole_part, unit);
539 } else {
540 while ((fractional_part % 1000) == 0) {
541 zero_fill -= 3;
542 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800543 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700544 if (zero_fill == 3) {
545 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
546 } else if (zero_fill == 6) {
547 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800548 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700549 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800550 }
551 }
552}
553
Elliott Hughes82914b62012-04-09 15:56:29 -0700554std::string PrintableString(const std::string& utf) {
555 std::string result;
556 result += '"';
557 const char* p = utf.c_str();
558 size_t char_count = CountModifiedUtf8Chars(p);
559 for (size_t i = 0; i < char_count; ++i) {
560 uint16_t ch = GetUtf16FromUtf8(&p);
561 if (ch == '\\') {
562 result += "\\\\";
563 } else if (ch == '\n') {
564 result += "\\n";
565 } else if (ch == '\r') {
566 result += "\\r";
567 } else if (ch == '\t') {
568 result += "\\t";
569 } else if (NeedsEscaping(ch)) {
570 StringAppendF(&result, "\\u%04x", ch);
571 } else {
572 result += ch;
573 }
574 }
575 result += '"';
576 return result;
577}
578
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800579// 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 -0700580std::string MangleForJni(const std::string& s) {
581 std::string result;
582 size_t char_count = CountModifiedUtf8Chars(s.c_str());
583 const char* cp = &s[0];
584 for (size_t i = 0; i < char_count; ++i) {
585 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800586 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
587 result.push_back(ch);
588 } else if (ch == '.' || ch == '/') {
589 result += "_";
590 } else if (ch == '_') {
591 result += "_1";
592 } else if (ch == ';') {
593 result += "_2";
594 } else if (ch == '[') {
595 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700596 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800597 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700598 }
599 }
600 return result;
601}
602
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700603std::string DotToDescriptor(const char* class_name) {
604 std::string descriptor(class_name);
605 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
606 if (descriptor.length() > 0 && descriptor[0] != '[') {
607 descriptor = "L" + descriptor + ";";
608 }
609 return descriptor;
610}
611
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800612std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800613 size_t length = strlen(descriptor);
614 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
615 std::string result(descriptor + 1, length - 2);
616 std::replace(result.begin(), result.end(), '/', '.');
617 return result;
618 }
619 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800620}
621
622std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800623 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800624 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
625 std::string result(descriptor + 1, length - 2);
626 return result;
627 }
628 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700629}
630
Brian Carlstromea46f952013-07-30 01:26:50 -0700631std::string JniShortName(const mirror::ArtMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800632 MethodHelper mh(m);
633 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700634 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700635 CHECK_EQ(class_name[0], 'L') << class_name;
636 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700637 class_name.erase(0, 1);
638 class_name.erase(class_name.size() - 1, 1);
639
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800640 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700641
642 std::string short_name;
643 short_name += "Java_";
644 short_name += MangleForJni(class_name);
645 short_name += "_";
646 short_name += MangleForJni(method_name);
647 return short_name;
648}
649
Brian Carlstromea46f952013-07-30 01:26:50 -0700650std::string JniLongName(const mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700651 std::string long_name;
652 long_name += JniShortName(m);
653 long_name += "__";
654
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800655 std::string signature(MethodHelper(m).GetSignature());
Elliott Hughes79082e32011-08-25 12:07:32 -0700656 signature.erase(0, 1);
657 signature.erase(signature.begin() + signature.find(')'), signature.end());
658
659 long_name += MangleForJni(signature);
660
661 return long_name;
662}
663
jeffhao10037c82012-01-23 15:06:23 -0800664// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700665uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700666 0x00000000, // 00..1f low control characters; nothing valid
667 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
668 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
669 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700670};
671
jeffhao10037c82012-01-23 15:06:23 -0800672// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
673bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700674 /*
675 * It's a multibyte encoded character. Decode it and analyze. We
676 * accept anything that isn't (a) an improperly encoded low value,
677 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
678 * control character, or (e) a high space, layout, or special
679 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
680 * U+fff0..U+ffff). This is all specified in the dex format
681 * document.
682 */
683
684 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
685
686 // Perform follow-up tests based on the high 8 bits.
687 switch (utf16 >> 8) {
688 case 0x00:
689 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
690 return (utf16 > 0x00a0);
691 case 0xd8:
692 case 0xd9:
693 case 0xda:
694 case 0xdb:
695 // It's a leading surrogate. Check to see that a trailing
696 // surrogate follows.
697 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
698 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
699 case 0xdc:
700 case 0xdd:
701 case 0xde:
702 case 0xdf:
703 // It's a trailing surrogate, which is not valid at this point.
704 return false;
705 case 0x20:
706 case 0xff:
707 // It's in the range that has spaces, controls, and specials.
708 switch (utf16 & 0xfff8) {
709 case 0x2000:
710 case 0x2008:
711 case 0x2028:
712 case 0xfff0:
713 case 0xfff8:
714 return false;
715 }
716 break;
717 }
718 return true;
719}
720
721/* Return whether the pointed-at modified-UTF-8 encoded character is
722 * valid as part of a member name, updating the pointer to point past
723 * the consumed character. This will consume two encoded UTF-16 code
724 * points if the character is encoded as a surrogate pair. Also, if
725 * this function returns false, then the given pointer may only have
726 * been partially advanced.
727 */
jeffhao10037c82012-01-23 15:06:23 -0800728bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700729 uint8_t c = (uint8_t) **pUtf8Ptr;
730 if (c <= 0x7f) {
731 // It's low-ascii, so check the table.
732 uint32_t wordIdx = c >> 5;
733 uint32_t bitIdx = c & 0x1f;
734 (*pUtf8Ptr)++;
735 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
736 }
737
738 // It's a multibyte encoded character. Call a non-inline function
739 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800740 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
741}
742
743bool IsValidMemberName(const char* s) {
744 bool angle_name = false;
745
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700746 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800747 case '\0':
748 // The empty string is not a valid name.
749 return false;
750 case '<':
751 angle_name = true;
752 s++;
753 break;
754 }
755
756 while (true) {
757 switch (*s) {
758 case '\0':
759 return !angle_name;
760 case '>':
761 return angle_name && s[1] == '\0';
762 }
763
764 if (!IsValidPartOfMemberNameUtf8(&s)) {
765 return false;
766 }
767 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700768}
769
Elliott Hughes906e6852011-10-28 14:52:10 -0700770enum ClassNameType { kName, kDescriptor };
771bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700772 int arrayCount = 0;
773 while (*s == '[') {
774 arrayCount++;
775 s++;
776 }
777
778 if (arrayCount > 255) {
779 // Arrays may have no more than 255 dimensions.
780 return false;
781 }
782
783 if (arrayCount != 0) {
784 /*
785 * If we're looking at an array of some sort, then it doesn't
786 * matter if what is being asked for is a class name; the
787 * format looks the same as a type descriptor in that case, so
788 * treat it as such.
789 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700790 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700791 }
792
Elliott Hughes906e6852011-10-28 14:52:10 -0700793 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700794 /*
795 * We are looking for a descriptor. Either validate it as a
796 * single-character primitive type, or continue on to check the
797 * embedded class name (bracketed by "L" and ";").
798 */
799 switch (*(s++)) {
800 case 'B':
801 case 'C':
802 case 'D':
803 case 'F':
804 case 'I':
805 case 'J':
806 case 'S':
807 case 'Z':
808 // These are all single-character descriptors for primitive types.
809 return (*s == '\0');
810 case 'V':
811 // Non-array void is valid, but you can't have an array of void.
812 return (arrayCount == 0) && (*s == '\0');
813 case 'L':
814 // Class name: Break out and continue below.
815 break;
816 default:
817 // Oddball descriptor character.
818 return false;
819 }
820 }
821
822 /*
823 * We just consumed the 'L' that introduces a class name as part
824 * of a type descriptor, or we are looking for an unadorned class
825 * name.
826 */
827
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700828 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700829 for (;;) {
830 uint8_t c = (uint8_t) *s;
831 switch (c) {
832 case '\0':
833 /*
834 * Premature end for a type descriptor, but valid for
835 * a class name as long as we haven't encountered an
836 * empty component (including the degenerate case of
837 * the empty string "").
838 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700839 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700840 case ';':
841 /*
842 * Invalid character for a class name, but the
843 * legitimate end of a type descriptor. In the latter
844 * case, make sure that this is the end of the string
845 * and that it doesn't end with an empty component
846 * (including the degenerate case of "L;").
847 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700848 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700849 case '/':
850 case '.':
851 if (c != separator) {
852 // The wrong separator character.
853 return false;
854 }
855 if (sepOrFirst) {
856 // Separator at start or two separators in a row.
857 return false;
858 }
859 sepOrFirst = true;
860 s++;
861 break;
862 default:
jeffhao10037c82012-01-23 15:06:23 -0800863 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700864 return false;
865 }
866 sepOrFirst = false;
867 break;
868 }
869 }
870}
871
Elliott Hughes906e6852011-10-28 14:52:10 -0700872bool IsValidBinaryClassName(const char* s) {
873 return IsValidClassName(s, kName, '.');
874}
875
876bool IsValidJniClassName(const char* s) {
877 return IsValidClassName(s, kName, '/');
878}
879
880bool IsValidDescriptor(const char* s) {
881 return IsValidClassName(s, kDescriptor, '/');
882}
883
Elliott Hughes48436bb2012-02-07 15:23:28 -0800884void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700885 const char* p = s.data();
886 const char* end = p + s.size();
887 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800888 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700889 ++p;
890 } else {
891 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800892 while (++p != end && *p != separator) {
893 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700894 }
895 result.push_back(std::string(start, p - start));
896 }
897 }
898}
899
Elliott Hughes48436bb2012-02-07 15:23:28 -0800900template <typename StringT>
901std::string Join(std::vector<StringT>& strings, char separator) {
902 if (strings.empty()) {
903 return "";
904 }
905
906 std::string result(strings[0]);
907 for (size_t i = 1; i < strings.size(); ++i) {
908 result += separator;
909 result += strings[i];
910 }
911 return result;
912}
913
914// Explicit instantiations.
915template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
916template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
917template std::string Join<char*>(std::vector<char*>& strings, char separator);
918
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800919bool StartsWith(const std::string& s, const char* prefix) {
920 return s.compare(0, strlen(prefix), prefix) == 0;
921}
922
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700923bool EndsWith(const std::string& s, const char* suffix) {
924 size_t suffix_length = strlen(suffix);
925 size_t string_length = s.size();
926 if (suffix_length > string_length) {
927 return false;
928 }
929 size_t offset = string_length - suffix_length;
930 return s.compare(offset, suffix_length, suffix) == 0;
931}
932
Elliott Hughes22869a92012-03-27 14:08:24 -0700933void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700934 int hasAt = 0;
935 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700936 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700937 while (*s) {
938 if (*s == '.') {
939 hasDot = 1;
940 } else if (*s == '@') {
941 hasAt = 1;
942 }
943 s++;
944 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700945 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700946 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700947 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700948 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700949 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700950 }
951#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700952 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700953 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
954 strncpy(buf, s, sizeof(buf)-1);
955 buf[sizeof(buf)-1] = '\0';
956 errno = pthread_setname_np(pthread_self(), buf);
957 if (errno != 0) {
958 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
959 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700960#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700961 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700962#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700963 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700964#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700965 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700966#endif
967}
968
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700969void GetTaskStats(pid_t tid, char& state, int& utime, int& stime, int& task_cpu) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700970 utime = stime = task_cpu = 0;
971 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700972 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700973 return;
974 }
975 // Skip the command, which may contain spaces.
976 stats = stats.substr(stats.find(')') + 2);
977 // Extract the three fields we care about.
978 std::vector<std::string> fields;
979 Split(stats, ' ', fields);
Elliott Hughesba0b9c52012-09-20 11:25:12 -0700980 state = fields[0][0];
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700981 utime = strtoull(fields[11].c_str(), NULL, 10);
982 stime = strtoull(fields[12].c_str(), NULL, 10);
983 task_cpu = strtoull(fields[36].c_str(), NULL, 10);
984}
985
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700986std::string GetSchedulerGroupName(pid_t tid) {
987 // /proc/<pid>/cgroup looks like this:
988 // 2:devices:/
989 // 1:cpuacct,cpu:/
990 // We want the third field from the line whose second field contains the "cpu" token.
991 std::string cgroup_file;
992 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
993 return "";
994 }
995 std::vector<std::string> cgroup_lines;
996 Split(cgroup_file, '\n', cgroup_lines);
997 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
998 std::vector<std::string> cgroup_fields;
999 Split(cgroup_lines[i], ':', cgroup_fields);
1000 std::vector<std::string> cgroups;
1001 Split(cgroup_fields[1], ',', cgroups);
1002 for (size_t i = 0; i < cgroups.size(); ++i) {
1003 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001004 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001005 }
1006 }
1007 }
1008 return "";
1009}
1010
Elliott Hughes46e251b2012-05-22 15:10:45 -07001011static const char* CleanMapName(const backtrace_symbol_t* symbol) {
1012 const char* map_name = symbol->map_name;
1013 if (map_name == NULL) {
1014 map_name = "???";
1015 }
1016 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1017 // into "libartd.so".
1018 const char* last_slash = strrchr(map_name, '/');
1019 if (last_slash != NULL) {
1020 map_name = last_slash + 1;
1021 }
1022 return map_name;
1023}
1024
1025static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
1026 std::string& symbol_name, uint32_t& pc_offset) {
1027 symbol_table_t* symbol_table = NULL;
1028 if (symbol->map_name != NULL) {
1029 symbol_table = load_symbol_table(symbol->map_name);
1030 }
1031 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -07001032 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001033 if (symbol_table != NULL) {
1034 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
1035 if (elf_symbol == NULL) {
1036 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -07001037 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001038 }
1039 }
1040 if (elf_symbol != NULL) {
1041 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
1042 if (demangled_symbol_name != NULL) {
1043 symbol_name = demangled_symbol_name;
1044 } else {
1045 symbol_name = elf_symbol->name;
1046 }
Elliott Hughes95aff772012-06-12 17:44:15 -07001047
1048 // TODO: is it a libcorkscrew bug that we have to do this?
1049 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001050 } else {
1051 symbol_name = "???";
1052 }
1053 free_symbol_table(symbol_table);
1054}
1055
1056void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001057 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1058 flush_my_map_info_list();
1059
Elliott Hughes46e251b2012-05-22 15:10:45 -07001060 const size_t MAX_DEPTH = 32;
1061 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001062 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001063 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001064 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001065 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001066 return;
1067 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001068 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001069 return;
1070 }
1071
1072 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1073 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1074
1075 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1076 const backtrace_frame_t* frame = &frames[i];
1077 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1078
1079 // We produce output like this:
1080 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1081
1082 std::string symbol_name;
1083 uint32_t pc_offset = 0;
1084 if (symbol->demangled_name != NULL) {
1085 symbol_name = symbol->demangled_name;
1086 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1087 } else if (symbol->symbol_name != NULL) {
1088 symbol_name = symbol->symbol_name;
1089 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1090 } else {
1091 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1092 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1093 }
1094
1095 os << prefix;
1096 if (include_count) {
1097 os << StringPrintf("#%02zd ", i);
1098 }
1099 os << symbol_name;
1100 if (pc_offset != 0) {
1101 os << "+" << pc_offset;
1102 }
1103 os << StringPrintf(" [%p] (%s)\n",
1104 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1105 }
1106
1107 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1108}
1109
Elliott Hughes058a6de2012-05-24 19:13:02 -07001110#if defined(__APPLE__)
1111
1112// TODO: is there any way to get the kernel stack on Mac OS?
1113void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1114
1115#else
1116
Elliott Hughes46e251b2012-05-22 15:10:45 -07001117void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001118 if (tid == GetTid()) {
1119 // There's no point showing that we're reading our stack out of /proc!
1120 return;
1121 }
1122
Elliott Hughes46e251b2012-05-22 15:10:45 -07001123 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1124 std::string kernel_stack;
1125 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001126 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001127 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001128 }
1129
1130 std::vector<std::string> kernel_stack_frames;
1131 Split(kernel_stack, '\n', kernel_stack_frames);
1132 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1133 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1134 kernel_stack_frames.pop_back();
1135 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1136 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1137 const char* text = kernel_stack_frames[i].c_str();
1138 const char* close_bracket = strchr(text, ']');
1139 if (close_bracket != NULL) {
1140 text = close_bracket + 2;
1141 }
1142 os << prefix;
1143 if (include_count) {
1144 os << StringPrintf("#%02zd ", i);
1145 }
1146 os << text << "\n";
1147 }
1148}
1149
1150#endif
1151
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001152const char* GetAndroidRoot() {
1153 const char* android_root = getenv("ANDROID_ROOT");
1154 if (android_root == NULL) {
1155 if (OS::DirectoryExists("/system")) {
1156 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001157 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001158 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1159 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001160 }
1161 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001162 if (!OS::DirectoryExists(android_root)) {
1163 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001164 return "";
1165 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001166 return android_root;
1167}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001168
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001169const char* GetAndroidData() {
1170 const char* android_data = getenv("ANDROID_DATA");
1171 if (android_data == NULL) {
1172 if (OS::DirectoryExists("/data")) {
1173 android_data = "/data";
1174 } else {
1175 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1176 return "";
1177 }
1178 }
1179 if (!OS::DirectoryExists(android_data)) {
1180 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1181 return "";
1182 }
1183 return android_data;
1184}
1185
Brian Carlstrom7675e162013-06-10 16:18:04 -07001186std::string GetDalvikCacheOrDie(const char* android_data) {
1187 std::string dalvik_cache(StringPrintf("%s/dalvik-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001188
Brian Carlstrom7675e162013-06-10 16:18:04 -07001189 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1190 if (StartsWith(dalvik_cache, "/tmp/")) {
1191 int result = mkdir(dalvik_cache.c_str(), 0700);
Brian Carlstroma9f19782011-10-13 00:14:47 -07001192 if (result != 0) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001193 LOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001194 return "";
1195 }
1196 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001197 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001198 return "";
1199 }
1200 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001201 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001202}
1203
Brian Carlstrom7675e162013-06-10 16:18:04 -07001204std::string GetDalvikCacheFilenameOrDie(const std::string& location) {
1205 std::string dalvik_cache(GetDalvikCacheOrDie(GetAndroidData()));
Ian Rogerse6060102013-05-16 12:01:04 -07001206 if (location[0] != '/') {
1207 LOG(FATAL) << "Expected path in location to be absolute: "<< location;
1208 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001209 std::string cache_file(location, 1); // skip leading slash
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001210 if (!IsValidDexFilename(location)) {
1211 cache_file += "/";
1212 cache_file += DexFile::kClassesDex;
1213 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001214 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Brian Carlstrom7675e162013-06-10 16:18:04 -07001215 return dalvik_cache + "/" + cache_file;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001216}
1217
jeffhao262bf462011-10-20 18:36:32 -07001218bool IsValidZipFilename(const std::string& filename) {
1219 if (filename.size() < 4) {
1220 return false;
1221 }
1222 std::string suffix(filename.substr(filename.size() - 4));
1223 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1224}
1225
1226bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001227 return EndsWith(filename, ".dex");
1228}
1229
1230bool IsValidOatFilename(const std::string& filename) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001231 return (EndsWith(filename, ".odex") ||
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001232 EndsWith(filename, ".dex") ||
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001233 EndsWith(filename, ".oat") ||
1234 EndsWith(filename, DexFile::kClassesDex));
jeffhao262bf462011-10-20 18:36:32 -07001235}
1236
Elliott Hughes42ee1422011-09-06 12:33:32 -07001237} // namespace art