blob: b97239fd18a9186076673664486d50401981e4bc [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 Rogersa6724902013-09-23 09:23:37 -070037#include "utf-inl.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
Brian Carlstrom29212012013-09-12 22:18:30 -070082void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070083#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070084 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070085 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) {
Brian Carlstrom29212012013-09-12 22:18:30 -070091 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070092 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070093 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070094 }
95#else
96 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070097 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -070098 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070099 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
Elliott Hughes0512f022012-03-15 22:10:52 -0700167uint64_t ThreadCpuNanoTime() {
168#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700169 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700170 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
171 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
172#else
173 UNIMPLEMENTED(WARNING);
174 return -1;
175#endif
176}
177
Ian Rogers56edc432013-01-18 16:51:51 -0800178void NanoSleep(uint64_t ns) {
179 timespec tm;
180 tm.tv_sec = 0;
181 tm.tv_nsec = ns;
182 nanosleep(&tm, NULL);
183}
184
Brian Carlstrombcc29262012-11-02 11:36:03 -0700185void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
186 int64_t endSec;
187
188 if (absolute) {
189#if !defined(__APPLE__)
190 clock_gettime(clock, ts);
191#else
192 UNUSED(clock);
193 timeval tv;
194 gettimeofday(&tv, NULL);
195 ts->tv_sec = tv.tv_sec;
196 ts->tv_nsec = tv.tv_usec * 1000;
197#endif
198 } else {
199 ts->tv_sec = 0;
200 ts->tv_nsec = 0;
201 }
202 endSec = ts->tv_sec + ms / 1000;
203 if (UNLIKELY(endSec >= 0x7fffffff)) {
204 std::ostringstream ss;
205 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
206 endSec = 0x7ffffffe;
207 }
208 ts->tv_sec = endSec;
209 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
210
211 // Catch rollover.
212 if (ts->tv_nsec >= 1000000000L) {
213 ts->tv_sec++;
214 ts->tv_nsec -= 1000000000L;
215 }
216}
217
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800218std::string PrettyDescriptor(const mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700219 if (java_descriptor == NULL) {
220 return "null";
221 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700222 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
223}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700224
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800225std::string PrettyDescriptor(const mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800226 if (klass == NULL) {
227 return "null";
228 }
229 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800230}
231
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700232std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700233 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700234 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700235 size_t dim = 0;
236 while (*c == '[') {
237 dim++;
238 c++;
239 }
240
241 // Reference or primitive?
242 if (*c == 'L') {
243 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700244 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700245 } else {
246 // "[[B" -> "byte[][]".
247 // To make life easier, we make primitives look like unqualified
248 // reference types.
249 switch (*c) {
250 case 'B': c = "byte;"; break;
251 case 'C': c = "char;"; break;
252 case 'D': c = "double;"; break;
253 case 'F': c = "float;"; break;
254 case 'I': c = "int;"; break;
255 case 'J': c = "long;"; break;
256 case 'S': c = "short;"; break;
257 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700258 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700259 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700260 }
261 }
262
263 // At this point, 'c' is a string of the form "fully/qualified/Type;"
264 // or "primitive;". Rewrite the type with '.' instead of '/':
265 std::string result;
266 const char* p = c;
267 while (*p != ';') {
268 char ch = *p++;
269 if (ch == '/') {
270 ch = '.';
271 }
272 result.push_back(ch);
273 }
274 // ...and replace the semicolon with 'dim' "[]" pairs:
275 while (dim--) {
276 result += "[]";
277 }
278 return result;
279}
280
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700281std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800282 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700283 return PrettyDescriptor(descriptor_string);
284}
285
Brian Carlstromea46f952013-07-30 01:26:50 -0700286std::string PrettyField(const mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700287 if (f == NULL) {
288 return "null";
289 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800290 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700291 std::string result;
292 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800293 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700294 result += ' ';
295 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800296 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700297 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800298 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700299 return result;
300}
301
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700302std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800303 if (field_idx >= dex_file.NumFieldIds()) {
304 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
305 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700306 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
307 std::string result;
308 if (with_type) {
309 result += dex_file.GetFieldTypeDescriptor(field_id);
310 result += ' ';
311 }
312 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
313 result += '.';
314 result += dex_file.GetFieldName(field_id);
315 return result;
316}
317
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700318std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800319 if (type_idx >= dex_file.NumTypeIds()) {
320 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
321 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700322 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700323 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700324}
325
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700326std::string PrettyArguments(const char* signature) {
327 std::string result;
328 result += '(';
329 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700330 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700331 while (*signature != ')') {
332 size_t argument_length = 0;
333 while (signature[argument_length] == '[') {
334 ++argument_length;
335 }
336 if (signature[argument_length] == 'L') {
337 argument_length = (strchr(signature, ';') - signature + 1);
338 } else {
339 ++argument_length;
340 }
341 std::string argument_descriptor(signature, argument_length);
342 result += PrettyDescriptor(argument_descriptor);
343 if (signature[argument_length] != ')') {
344 result += ", ";
345 }
346 signature += argument_length;
347 }
348 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700349 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700350 result += ')';
351 return result;
352}
353
354std::string PrettyReturnType(const char* signature) {
355 const char* return_type = strchr(signature, ')');
356 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700357 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700358 return PrettyDescriptor(return_type);
359}
360
Brian Carlstromea46f952013-07-30 01:26:50 -0700361std::string PrettyMethod(const mirror::ArtMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700362 if (m == NULL) {
363 return "null";
364 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800365 MethodHelper mh(m);
366 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700367 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800368 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700369 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700370 const Signature signature = mh.GetSignature();
371 std::string sig_as_string(signature.ToString());
372 if (signature == Signature::NoSignature()) {
373 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700374 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700375 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
376 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700377 }
378 return result;
379}
380
Ian Rogers0571d352011-11-03 19:51:38 -0700381std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800382 if (method_idx >= dex_file.NumMethodIds()) {
383 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
384 }
Ian Rogers0571d352011-11-03 19:51:38 -0700385 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
386 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
387 result += '.';
388 result += dex_file.GetMethodName(method_id);
389 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700390 const Signature signature = dex_file.GetMethodSignature(method_id);
391 std::string sig_as_string(signature.ToString());
392 if (signature == Signature::NoSignature()) {
393 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700394 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700395 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
396 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700397 }
398 return result;
399}
400
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800401std::string PrettyTypeOf(const mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700402 if (obj == NULL) {
403 return "null";
404 }
405 if (obj->GetClass() == NULL) {
406 return "(raw)";
407 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800408 ClassHelper kh(obj->GetClass());
409 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700410 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800411 kh.ChangeClass(obj->AsClass());
412 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700413 }
414 return result;
415}
416
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800417std::string PrettyClass(const mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700418 if (c == NULL) {
419 return "null";
420 }
421 std::string result;
422 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800423 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700424 result += ">";
425 return result;
426}
427
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800428std::string PrettyClassAndClassLoader(const mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700429 if (c == NULL) {
430 return "null";
431 }
432 std::string result;
433 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800434 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700435 result += ",";
436 result += PrettyTypeOf(c->GetClassLoader());
437 // TODO: add an identifying hash value for the loader
438 result += ">";
439 return result;
440}
441
Elliott Hughesc967f782012-04-16 10:23:15 -0700442std::string PrettySize(size_t byte_count) {
443 // The byte thresholds at which we display amounts. A byte count is displayed
444 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
445 static const size_t kUnitThresholds[] = {
446 0, // B up to...
447 3*1024, // KB up to...
448 2*1024*1024, // MB up to...
449 1024*1024*1024 // GB from here.
450 };
451 static const size_t kBytesPerUnit[] = { 1, KB, MB, GB };
452 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
453
454 int i = arraysize(kUnitThresholds);
455 while (--i > 0) {
456 if (byte_count >= kUnitThresholds[i]) {
457 break;
458 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800459 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700460
461 return StringPrintf("%zd%s", byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800462}
463
464std::string PrettyDuration(uint64_t nano_duration) {
465 if (nano_duration == 0) {
466 return "0";
467 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700468 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
469 }
470}
471
472TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
473 const uint64_t one_sec = 1000 * 1000 * 1000;
474 const uint64_t one_ms = 1000 * 1000;
475 const uint64_t one_us = 1000;
476 if (nano_duration >= one_sec) {
477 return kTimeUnitSecond;
478 } else if (nano_duration >= one_ms) {
479 return kTimeUnitMillisecond;
480 } else if (nano_duration >= one_us) {
481 return kTimeUnitMicrosecond;
482 } else {
483 return kTimeUnitNanosecond;
484 }
485}
486
487uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
488 const uint64_t one_sec = 1000 * 1000 * 1000;
489 const uint64_t one_ms = 1000 * 1000;
490 const uint64_t one_us = 1000;
491
492 switch (time_unit) {
493 case kTimeUnitSecond:
494 return one_sec;
495 case kTimeUnitMillisecond:
496 return one_ms;
497 case kTimeUnitMicrosecond:
498 return one_us;
499 case kTimeUnitNanosecond:
500 return 1;
501 }
502 return 0;
503}
504
505std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
506 const char* unit = NULL;
507 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
508 uint32_t zero_fill = 1;
509 switch (time_unit) {
510 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800511 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800512 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700513 break;
514 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800515 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800516 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700517 break;
518 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800519 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800520 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700521 break;
522 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800523 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800524 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700525 break;
526 }
527
528 uint64_t whole_part = nano_duration / divisor;
529 uint64_t fractional_part = nano_duration % divisor;
530 if (fractional_part == 0) {
531 return StringPrintf("%llu%s", whole_part, unit);
532 } else {
533 while ((fractional_part % 1000) == 0) {
534 zero_fill -= 3;
535 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800536 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700537 if (zero_fill == 3) {
538 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
539 } else if (zero_fill == 6) {
540 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800541 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700542 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800543 }
544 }
545}
546
Elliott Hughes82914b62012-04-09 15:56:29 -0700547std::string PrintableString(const std::string& utf) {
548 std::string result;
549 result += '"';
550 const char* p = utf.c_str();
551 size_t char_count = CountModifiedUtf8Chars(p);
552 for (size_t i = 0; i < char_count; ++i) {
553 uint16_t ch = GetUtf16FromUtf8(&p);
554 if (ch == '\\') {
555 result += "\\\\";
556 } else if (ch == '\n') {
557 result += "\\n";
558 } else if (ch == '\r') {
559 result += "\\r";
560 } else if (ch == '\t') {
561 result += "\\t";
562 } else if (NeedsEscaping(ch)) {
563 StringAppendF(&result, "\\u%04x", ch);
564 } else {
565 result += ch;
566 }
567 }
568 result += '"';
569 return result;
570}
571
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800572// 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 -0700573std::string MangleForJni(const std::string& s) {
574 std::string result;
575 size_t char_count = CountModifiedUtf8Chars(s.c_str());
576 const char* cp = &s[0];
577 for (size_t i = 0; i < char_count; ++i) {
578 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800579 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
580 result.push_back(ch);
581 } else if (ch == '.' || ch == '/') {
582 result += "_";
583 } else if (ch == '_') {
584 result += "_1";
585 } else if (ch == ';') {
586 result += "_2";
587 } else if (ch == '[') {
588 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700589 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800590 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700591 }
592 }
593 return result;
594}
595
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700596std::string DotToDescriptor(const char* class_name) {
597 std::string descriptor(class_name);
598 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
599 if (descriptor.length() > 0 && descriptor[0] != '[') {
600 descriptor = "L" + descriptor + ";";
601 }
602 return descriptor;
603}
604
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800605std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800606 size_t length = strlen(descriptor);
607 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
608 std::string result(descriptor + 1, length - 2);
609 std::replace(result.begin(), result.end(), '/', '.');
610 return result;
611 }
612 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800613}
614
615std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800616 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800617 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
618 std::string result(descriptor + 1, length - 2);
619 return result;
620 }
621 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700622}
623
Brian Carlstromea46f952013-07-30 01:26:50 -0700624std::string JniShortName(const mirror::ArtMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800625 MethodHelper mh(m);
626 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700627 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700628 CHECK_EQ(class_name[0], 'L') << class_name;
629 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700630 class_name.erase(0, 1);
631 class_name.erase(class_name.size() - 1, 1);
632
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800633 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700634
635 std::string short_name;
636 short_name += "Java_";
637 short_name += MangleForJni(class_name);
638 short_name += "_";
639 short_name += MangleForJni(method_name);
640 return short_name;
641}
642
Brian Carlstromea46f952013-07-30 01:26:50 -0700643std::string JniLongName(const mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700644 std::string long_name;
645 long_name += JniShortName(m);
646 long_name += "__";
647
Ian Rogersd91d6d62013-09-25 20:26:14 -0700648 std::string signature(MethodHelper(m).GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700649 signature.erase(0, 1);
650 signature.erase(signature.begin() + signature.find(')'), signature.end());
651
652 long_name += MangleForJni(signature);
653
654 return long_name;
655}
656
jeffhao10037c82012-01-23 15:06:23 -0800657// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700658uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700659 0x00000000, // 00..1f low control characters; nothing valid
660 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
661 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
662 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700663};
664
jeffhao10037c82012-01-23 15:06:23 -0800665// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
666bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700667 /*
668 * It's a multibyte encoded character. Decode it and analyze. We
669 * accept anything that isn't (a) an improperly encoded low value,
670 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
671 * control character, or (e) a high space, layout, or special
672 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
673 * U+fff0..U+ffff). This is all specified in the dex format
674 * document.
675 */
676
677 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
678
679 // Perform follow-up tests based on the high 8 bits.
680 switch (utf16 >> 8) {
681 case 0x00:
682 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
683 return (utf16 > 0x00a0);
684 case 0xd8:
685 case 0xd9:
686 case 0xda:
687 case 0xdb:
688 // It's a leading surrogate. Check to see that a trailing
689 // surrogate follows.
690 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
691 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
692 case 0xdc:
693 case 0xdd:
694 case 0xde:
695 case 0xdf:
696 // It's a trailing surrogate, which is not valid at this point.
697 return false;
698 case 0x20:
699 case 0xff:
700 // It's in the range that has spaces, controls, and specials.
701 switch (utf16 & 0xfff8) {
702 case 0x2000:
703 case 0x2008:
704 case 0x2028:
705 case 0xfff0:
706 case 0xfff8:
707 return false;
708 }
709 break;
710 }
711 return true;
712}
713
714/* Return whether the pointed-at modified-UTF-8 encoded character is
715 * valid as part of a member name, updating the pointer to point past
716 * the consumed character. This will consume two encoded UTF-16 code
717 * points if the character is encoded as a surrogate pair. Also, if
718 * this function returns false, then the given pointer may only have
719 * been partially advanced.
720 */
jeffhao10037c82012-01-23 15:06:23 -0800721bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700722 uint8_t c = (uint8_t) **pUtf8Ptr;
723 if (c <= 0x7f) {
724 // It's low-ascii, so check the table.
725 uint32_t wordIdx = c >> 5;
726 uint32_t bitIdx = c & 0x1f;
727 (*pUtf8Ptr)++;
728 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
729 }
730
731 // It's a multibyte encoded character. Call a non-inline function
732 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800733 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
734}
735
736bool IsValidMemberName(const char* s) {
737 bool angle_name = false;
738
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700739 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800740 case '\0':
741 // The empty string is not a valid name.
742 return false;
743 case '<':
744 angle_name = true;
745 s++;
746 break;
747 }
748
749 while (true) {
750 switch (*s) {
751 case '\0':
752 return !angle_name;
753 case '>':
754 return angle_name && s[1] == '\0';
755 }
756
757 if (!IsValidPartOfMemberNameUtf8(&s)) {
758 return false;
759 }
760 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700761}
762
Elliott Hughes906e6852011-10-28 14:52:10 -0700763enum ClassNameType { kName, kDescriptor };
764bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700765 int arrayCount = 0;
766 while (*s == '[') {
767 arrayCount++;
768 s++;
769 }
770
771 if (arrayCount > 255) {
772 // Arrays may have no more than 255 dimensions.
773 return false;
774 }
775
776 if (arrayCount != 0) {
777 /*
778 * If we're looking at an array of some sort, then it doesn't
779 * matter if what is being asked for is a class name; the
780 * format looks the same as a type descriptor in that case, so
781 * treat it as such.
782 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700783 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700784 }
785
Elliott Hughes906e6852011-10-28 14:52:10 -0700786 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700787 /*
788 * We are looking for a descriptor. Either validate it as a
789 * single-character primitive type, or continue on to check the
790 * embedded class name (bracketed by "L" and ";").
791 */
792 switch (*(s++)) {
793 case 'B':
794 case 'C':
795 case 'D':
796 case 'F':
797 case 'I':
798 case 'J':
799 case 'S':
800 case 'Z':
801 // These are all single-character descriptors for primitive types.
802 return (*s == '\0');
803 case 'V':
804 // Non-array void is valid, but you can't have an array of void.
805 return (arrayCount == 0) && (*s == '\0');
806 case 'L':
807 // Class name: Break out and continue below.
808 break;
809 default:
810 // Oddball descriptor character.
811 return false;
812 }
813 }
814
815 /*
816 * We just consumed the 'L' that introduces a class name as part
817 * of a type descriptor, or we are looking for an unadorned class
818 * name.
819 */
820
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700821 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700822 for (;;) {
823 uint8_t c = (uint8_t) *s;
824 switch (c) {
825 case '\0':
826 /*
827 * Premature end for a type descriptor, but valid for
828 * a class name as long as we haven't encountered an
829 * empty component (including the degenerate case of
830 * the empty string "").
831 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700832 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700833 case ';':
834 /*
835 * Invalid character for a class name, but the
836 * legitimate end of a type descriptor. In the latter
837 * case, make sure that this is the end of the string
838 * and that it doesn't end with an empty component
839 * (including the degenerate case of "L;").
840 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700841 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700842 case '/':
843 case '.':
844 if (c != separator) {
845 // The wrong separator character.
846 return false;
847 }
848 if (sepOrFirst) {
849 // Separator at start or two separators in a row.
850 return false;
851 }
852 sepOrFirst = true;
853 s++;
854 break;
855 default:
jeffhao10037c82012-01-23 15:06:23 -0800856 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700857 return false;
858 }
859 sepOrFirst = false;
860 break;
861 }
862 }
863}
864
Elliott Hughes906e6852011-10-28 14:52:10 -0700865bool IsValidBinaryClassName(const char* s) {
866 return IsValidClassName(s, kName, '.');
867}
868
869bool IsValidJniClassName(const char* s) {
870 return IsValidClassName(s, kName, '/');
871}
872
873bool IsValidDescriptor(const char* s) {
874 return IsValidClassName(s, kDescriptor, '/');
875}
876
Elliott Hughes48436bb2012-02-07 15:23:28 -0800877void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700878 const char* p = s.data();
879 const char* end = p + s.size();
880 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800881 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700882 ++p;
883 } else {
884 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800885 while (++p != end && *p != separator) {
886 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700887 }
888 result.push_back(std::string(start, p - start));
889 }
890 }
891}
892
Elliott Hughes48436bb2012-02-07 15:23:28 -0800893template <typename StringT>
894std::string Join(std::vector<StringT>& strings, char separator) {
895 if (strings.empty()) {
896 return "";
897 }
898
899 std::string result(strings[0]);
900 for (size_t i = 1; i < strings.size(); ++i) {
901 result += separator;
902 result += strings[i];
903 }
904 return result;
905}
906
907// Explicit instantiations.
908template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
909template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
910template std::string Join<char*>(std::vector<char*>& strings, char separator);
911
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800912bool StartsWith(const std::string& s, const char* prefix) {
913 return s.compare(0, strlen(prefix), prefix) == 0;
914}
915
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700916bool EndsWith(const std::string& s, const char* suffix) {
917 size_t suffix_length = strlen(suffix);
918 size_t string_length = s.size();
919 if (suffix_length > string_length) {
920 return false;
921 }
922 size_t offset = string_length - suffix_length;
923 return s.compare(offset, suffix_length, suffix) == 0;
924}
925
Elliott Hughes22869a92012-03-27 14:08:24 -0700926void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700927 int hasAt = 0;
928 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700929 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700930 while (*s) {
931 if (*s == '.') {
932 hasDot = 1;
933 } else if (*s == '@') {
934 hasAt = 1;
935 }
936 s++;
937 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700938 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700939 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700940 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700941 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700942 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700943 }
944#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700945 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700946 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
947 strncpy(buf, s, sizeof(buf)-1);
948 buf[sizeof(buf)-1] = '\0';
949 errno = pthread_setname_np(pthread_self(), buf);
950 if (errno != 0) {
951 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
952 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700953#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700954 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700955#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700956 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700957#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700958 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700959#endif
960}
961
Brian Carlstrom29212012013-09-12 22:18:30 -0700962void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
963 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700964 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700965 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700966 return;
967 }
968 // Skip the command, which may contain spaces.
969 stats = stats.substr(stats.find(')') + 2);
970 // Extract the three fields we care about.
971 std::vector<std::string> fields;
972 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700973 *state = fields[0][0];
974 *utime = strtoull(fields[11].c_str(), NULL, 10);
975 *stime = strtoull(fields[12].c_str(), NULL, 10);
976 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700977}
978
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700979std::string GetSchedulerGroupName(pid_t tid) {
980 // /proc/<pid>/cgroup looks like this:
981 // 2:devices:/
982 // 1:cpuacct,cpu:/
983 // We want the third field from the line whose second field contains the "cpu" token.
984 std::string cgroup_file;
985 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
986 return "";
987 }
988 std::vector<std::string> cgroup_lines;
989 Split(cgroup_file, '\n', cgroup_lines);
990 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
991 std::vector<std::string> cgroup_fields;
992 Split(cgroup_lines[i], ':', cgroup_fields);
993 std::vector<std::string> cgroups;
994 Split(cgroup_fields[1], ',', cgroups);
995 for (size_t i = 0; i < cgroups.size(); ++i) {
996 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700997 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700998 }
999 }
1000 }
1001 return "";
1002}
1003
Elliott Hughes46e251b2012-05-22 15:10:45 -07001004static const char* CleanMapName(const backtrace_symbol_t* symbol) {
1005 const char* map_name = symbol->map_name;
1006 if (map_name == NULL) {
1007 map_name = "???";
1008 }
1009 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1010 // into "libartd.so".
1011 const char* last_slash = strrchr(map_name, '/');
1012 if (last_slash != NULL) {
1013 map_name = last_slash + 1;
1014 }
1015 return map_name;
1016}
1017
1018static void FindSymbolInElf(const backtrace_frame_t* frame, const backtrace_symbol_t* symbol,
1019 std::string& symbol_name, uint32_t& pc_offset) {
1020 symbol_table_t* symbol_table = NULL;
1021 if (symbol->map_name != NULL) {
1022 symbol_table = load_symbol_table(symbol->map_name);
1023 }
1024 const symbol_t* elf_symbol = NULL;
Elliott Hughes95aff772012-06-12 17:44:15 -07001025 bool was_relative = true;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001026 if (symbol_table != NULL) {
1027 elf_symbol = find_symbol(symbol_table, symbol->relative_pc);
1028 if (elf_symbol == NULL) {
1029 elf_symbol = find_symbol(symbol_table, frame->absolute_pc);
Elliott Hughes95aff772012-06-12 17:44:15 -07001030 was_relative = false;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001031 }
1032 }
1033 if (elf_symbol != NULL) {
1034 const char* demangled_symbol_name = demangle_symbol_name(elf_symbol->name);
1035 if (demangled_symbol_name != NULL) {
1036 symbol_name = demangled_symbol_name;
1037 } else {
1038 symbol_name = elf_symbol->name;
1039 }
Elliott Hughes95aff772012-06-12 17:44:15 -07001040
1041 // TODO: is it a libcorkscrew bug that we have to do this?
1042 pc_offset = (was_relative ? symbol->relative_pc : frame->absolute_pc) - elf_symbol->start;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001043 } else {
1044 symbol_name = "???";
1045 }
1046 free_symbol_table(symbol_table);
1047}
1048
1049void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes02fb9f72012-06-13 22:22:33 -07001050 // Ensure libcorkscrew doesn't use a stale cache of /proc/self/maps.
1051 flush_my_map_info_list();
1052
Elliott Hughes46e251b2012-05-22 15:10:45 -07001053 const size_t MAX_DEPTH = 32;
1054 UniquePtr<backtrace_frame_t[]> frames(new backtrace_frame_t[MAX_DEPTH]);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001055 size_t ignore_count = 2; // Don't include unwind_backtrace_thread or DumpNativeStack.
Elliott Hughes5db7ea02012-06-14 13:33:49 -07001056 ssize_t frame_count = unwind_backtrace_thread(tid, frames.get(), ignore_count, MAX_DEPTH);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001057 if (frame_count == -1) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001058 os << prefix << "(unwind_backtrace_thread failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001059 return;
1060 } else if (frame_count == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001061 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001062 return;
1063 }
1064
1065 UniquePtr<backtrace_symbol_t[]> backtrace_symbols(new backtrace_symbol_t[frame_count]);
1066 get_backtrace_symbols(frames.get(), frame_count, backtrace_symbols.get());
1067
1068 for (size_t i = 0; i < static_cast<size_t>(frame_count); ++i) {
1069 const backtrace_frame_t* frame = &frames[i];
1070 const backtrace_symbol_t* symbol = &backtrace_symbols[i];
1071
1072 // We produce output like this:
1073 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libcorkscrew.so)
1074
1075 std::string symbol_name;
1076 uint32_t pc_offset = 0;
1077 if (symbol->demangled_name != NULL) {
1078 symbol_name = symbol->demangled_name;
1079 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1080 } else if (symbol->symbol_name != NULL) {
1081 symbol_name = symbol->symbol_name;
1082 pc_offset = symbol->relative_pc - symbol->relative_symbol_addr;
1083 } else {
1084 // dladdr(3) didn't find a symbol; maybe it's static? Look in the ELF file...
1085 FindSymbolInElf(frame, symbol, symbol_name, pc_offset);
1086 }
1087
1088 os << prefix;
1089 if (include_count) {
1090 os << StringPrintf("#%02zd ", i);
1091 }
1092 os << symbol_name;
1093 if (pc_offset != 0) {
1094 os << "+" << pc_offset;
1095 }
1096 os << StringPrintf(" [%p] (%s)\n",
1097 reinterpret_cast<void*>(frame->absolute_pc), CleanMapName(symbol));
1098 }
1099
1100 free_backtrace_symbols(backtrace_symbols.get(), frame_count);
1101}
1102
Elliott Hughes058a6de2012-05-24 19:13:02 -07001103#if defined(__APPLE__)
1104
1105// TODO: is there any way to get the kernel stack on Mac OS?
1106void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1107
1108#else
1109
Elliott Hughes46e251b2012-05-22 15:10:45 -07001110void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001111 if (tid == GetTid()) {
1112 // There's no point showing that we're reading our stack out of /proc!
1113 return;
1114 }
1115
Elliott Hughes46e251b2012-05-22 15:10:45 -07001116 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1117 std::string kernel_stack;
1118 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001119 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001120 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001121 }
1122
1123 std::vector<std::string> kernel_stack_frames;
1124 Split(kernel_stack, '\n', kernel_stack_frames);
1125 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1126 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1127 kernel_stack_frames.pop_back();
1128 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1129 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1130 const char* text = kernel_stack_frames[i].c_str();
1131 const char* close_bracket = strchr(text, ']');
1132 if (close_bracket != NULL) {
1133 text = close_bracket + 2;
1134 }
1135 os << prefix;
1136 if (include_count) {
1137 os << StringPrintf("#%02zd ", i);
1138 }
1139 os << text << "\n";
1140 }
1141}
1142
1143#endif
1144
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001145const char* GetAndroidRoot() {
1146 const char* android_root = getenv("ANDROID_ROOT");
1147 if (android_root == NULL) {
1148 if (OS::DirectoryExists("/system")) {
1149 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001150 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001151 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1152 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001153 }
1154 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001155 if (!OS::DirectoryExists(android_root)) {
1156 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001157 return "";
1158 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001159 return android_root;
1160}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001161
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001162const char* GetAndroidData() {
1163 const char* android_data = getenv("ANDROID_DATA");
1164 if (android_data == NULL) {
1165 if (OS::DirectoryExists("/data")) {
1166 android_data = "/data";
1167 } else {
1168 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1169 return "";
1170 }
1171 }
1172 if (!OS::DirectoryExists(android_data)) {
1173 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1174 return "";
1175 }
1176 return android_data;
1177}
1178
Brian Carlstrom7675e162013-06-10 16:18:04 -07001179std::string GetDalvikCacheOrDie(const char* android_data) {
1180 std::string dalvik_cache(StringPrintf("%s/dalvik-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001181
Brian Carlstrom7675e162013-06-10 16:18:04 -07001182 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1183 if (StartsWith(dalvik_cache, "/tmp/")) {
1184 int result = mkdir(dalvik_cache.c_str(), 0700);
Brian Carlstroma9f19782011-10-13 00:14:47 -07001185 if (result != 0) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001186 LOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001187 return "";
1188 }
1189 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001190 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001191 return "";
1192 }
1193 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001194 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001195}
1196
Brian Carlstrom7675e162013-06-10 16:18:04 -07001197std::string GetDalvikCacheFilenameOrDie(const std::string& location) {
1198 std::string dalvik_cache(GetDalvikCacheOrDie(GetAndroidData()));
Ian Rogerse6060102013-05-16 12:01:04 -07001199 if (location[0] != '/') {
1200 LOG(FATAL) << "Expected path in location to be absolute: "<< location;
1201 }
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001202 std::string cache_file(location, 1); // skip leading slash
Anwar Ghuloumcaacdf32013-09-19 17:29:21 -07001203 if (!IsValidDexFilename(location) && !IsValidImageFilename(location)) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001204 cache_file += "/";
1205 cache_file += DexFile::kClassesDex;
1206 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001207 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Brian Carlstrom7675e162013-06-10 16:18:04 -07001208 return dalvik_cache + "/" + cache_file;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001209}
1210
jeffhao262bf462011-10-20 18:36:32 -07001211bool IsValidZipFilename(const std::string& filename) {
1212 if (filename.size() < 4) {
1213 return false;
1214 }
1215 std::string suffix(filename.substr(filename.size() - 4));
1216 return (suffix == ".zip" || suffix == ".jar" || suffix == ".apk");
1217}
1218
1219bool IsValidDexFilename(const std::string& filename) {
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001220 return EndsWith(filename, ".dex");
1221}
1222
Anwar Ghuloumcaacdf32013-09-19 17:29:21 -07001223bool IsValidImageFilename(const std::string& filename) {
1224 return EndsWith(filename, ".art");
1225}
1226
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001227bool IsValidOatFilename(const std::string& filename) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001228 return (EndsWith(filename, ".odex") ||
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001229 EndsWith(filename, ".dex") ||
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001230 EndsWith(filename, ".oat") ||
1231 EndsWith(filename, DexFile::kClassesDex));
jeffhao262bf462011-10-20 18:36:32 -07001232}
1233
Elliott Hughes42ee1422011-09-06 12:33:32 -07001234} // namespace art