blob: 950e3f994ece750efce253ed5d286c1f8fc48671 [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
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070052#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070053
Elliott Hughes058a6de2012-05-24 19:13:02 -070054#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080055#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080056#endif
57
Elliott Hughes11e45072011-08-16 17:40:46 -070058namespace art {
59
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080060pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070061#if defined(__APPLE__)
62 uint64_t owner;
63 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
64 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080065#else
66 // Neither bionic nor glibc exposes gettid(2).
67 return syscall(__NR_gettid);
68#endif
69}
70
Elliott Hughes289be852012-06-12 13:57:20 -070071std::string GetThreadName(pid_t tid) {
72 std::string result;
73 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070074 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070075 } else {
76 result = "<unknown>";
77 }
78 return result;
79}
80
Brian Carlstrom29212012013-09-12 22:18:30 -070081void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070082#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070083 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070084 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070085
86 // Check whether stack_addr is the base or end of the stack.
87 // (On Mac OS 10.7, it's the end.)
88 int stack_variable;
89 if (stack_addr > &stack_variable) {
Brian Carlstrom29212012013-09-12 22:18:30 -070090 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070091 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070092 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070093 }
94#else
95 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070096 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -070097 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070098 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
99#endif
100}
101
Elliott Hughesd92bec42011-09-02 17:04:36 -0700102bool ReadFileToString(const std::string& file_name, std::string* result) {
Elliott Hughes76160052012-12-12 16:31:20 -0800103 UniquePtr<File> file(new File);
104 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700105 return false;
106 }
buzbeec143c552011-08-20 17:38:58 -0700107
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700108 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700109 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800110 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700111 if (n == -1) {
112 return false;
buzbeec143c552011-08-20 17:38:58 -0700113 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700114 if (n == 0) {
115 return true;
116 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700117 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700118 }
buzbeec143c552011-08-20 17:38:58 -0700119}
120
Elliott Hughese27955c2011-08-26 15:21:24 -0700121std::string GetIsoDate() {
122 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700123 tm tmbuf;
124 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700125 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
126 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
127 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
128}
129
Elliott Hughes7162ad92011-10-27 14:08:42 -0700130uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800131#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700132 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700133 clock_gettime(CLOCK_MONOTONIC, &now);
134 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800135#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700136 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800137 gettimeofday(&now, NULL);
138 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
139#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700140}
141
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800142uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800143#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700144 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800145 clock_gettime(CLOCK_MONOTONIC, &now);
146 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800147#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700148 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800149 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700150 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800151#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800152}
153
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700154uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800155#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700156 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700157 clock_gettime(CLOCK_MONOTONIC, &now);
158 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800159#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700160 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800161 gettimeofday(&now, NULL);
162 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
163#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700164}
165
Elliott Hughes0512f022012-03-15 22:10:52 -0700166uint64_t ThreadCpuNanoTime() {
167#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700168 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700169 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
170 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
171#else
172 UNIMPLEMENTED(WARNING);
173 return -1;
174#endif
175}
176
Ian Rogers56edc432013-01-18 16:51:51 -0800177void NanoSleep(uint64_t ns) {
178 timespec tm;
179 tm.tv_sec = 0;
180 tm.tv_nsec = ns;
181 nanosleep(&tm, NULL);
182}
183
Brian Carlstrombcc29262012-11-02 11:36:03 -0700184void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
185 int64_t endSec;
186
187 if (absolute) {
188#if !defined(__APPLE__)
189 clock_gettime(clock, ts);
190#else
191 UNUSED(clock);
192 timeval tv;
193 gettimeofday(&tv, NULL);
194 ts->tv_sec = tv.tv_sec;
195 ts->tv_nsec = tv.tv_usec * 1000;
196#endif
197 } else {
198 ts->tv_sec = 0;
199 ts->tv_nsec = 0;
200 }
201 endSec = ts->tv_sec + ms / 1000;
202 if (UNLIKELY(endSec >= 0x7fffffff)) {
203 std::ostringstream ss;
204 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
205 endSec = 0x7ffffffe;
206 }
207 ts->tv_sec = endSec;
208 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
209
210 // Catch rollover.
211 if (ts->tv_nsec >= 1000000000L) {
212 ts->tv_sec++;
213 ts->tv_nsec -= 1000000000L;
214 }
215}
216
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800217std::string PrettyDescriptor(const mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700218 if (java_descriptor == NULL) {
219 return "null";
220 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700221 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
222}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700223
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800224std::string PrettyDescriptor(const mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800225 if (klass == NULL) {
226 return "null";
227 }
228 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800229}
230
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700231std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700232 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700233 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700234 size_t dim = 0;
235 while (*c == '[') {
236 dim++;
237 c++;
238 }
239
240 // Reference or primitive?
241 if (*c == 'L') {
242 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700243 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700244 } else {
245 // "[[B" -> "byte[][]".
246 // To make life easier, we make primitives look like unqualified
247 // reference types.
248 switch (*c) {
249 case 'B': c = "byte;"; break;
250 case 'C': c = "char;"; break;
251 case 'D': c = "double;"; break;
252 case 'F': c = "float;"; break;
253 case 'I': c = "int;"; break;
254 case 'J': c = "long;"; break;
255 case 'S': c = "short;"; break;
256 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700257 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700258 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700259 }
260 }
261
262 // At this point, 'c' is a string of the form "fully/qualified/Type;"
263 // or "primitive;". Rewrite the type with '.' instead of '/':
264 std::string result;
265 const char* p = c;
266 while (*p != ';') {
267 char ch = *p++;
268 if (ch == '/') {
269 ch = '.';
270 }
271 result.push_back(ch);
272 }
273 // ...and replace the semicolon with 'dim' "[]" pairs:
274 while (dim--) {
275 result += "[]";
276 }
277 return result;
278}
279
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700280std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800281 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700282 return PrettyDescriptor(descriptor_string);
283}
284
Brian Carlstromea46f952013-07-30 01:26:50 -0700285std::string PrettyField(const mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700286 if (f == NULL) {
287 return "null";
288 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800289 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700290 std::string result;
291 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800292 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700293 result += ' ';
294 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800295 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700296 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800297 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700298 return result;
299}
300
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700301std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800302 if (field_idx >= dex_file.NumFieldIds()) {
303 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
304 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700305 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
306 std::string result;
307 if (with_type) {
308 result += dex_file.GetFieldTypeDescriptor(field_id);
309 result += ' ';
310 }
311 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
312 result += '.';
313 result += dex_file.GetFieldName(field_id);
314 return result;
315}
316
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700317std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800318 if (type_idx >= dex_file.NumTypeIds()) {
319 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
320 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700321 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700322 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700323}
324
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700325std::string PrettyArguments(const char* signature) {
326 std::string result;
327 result += '(';
328 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700329 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700330 while (*signature != ')') {
331 size_t argument_length = 0;
332 while (signature[argument_length] == '[') {
333 ++argument_length;
334 }
335 if (signature[argument_length] == 'L') {
336 argument_length = (strchr(signature, ';') - signature + 1);
337 } else {
338 ++argument_length;
339 }
340 std::string argument_descriptor(signature, argument_length);
341 result += PrettyDescriptor(argument_descriptor);
342 if (signature[argument_length] != ')') {
343 result += ", ";
344 }
345 signature += argument_length;
346 }
347 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700348 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700349 result += ')';
350 return result;
351}
352
353std::string PrettyReturnType(const char* signature) {
354 const char* return_type = strchr(signature, ')');
355 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700356 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700357 return PrettyDescriptor(return_type);
358}
359
Brian Carlstromea46f952013-07-30 01:26:50 -0700360std::string PrettyMethod(const mirror::ArtMethod* m, bool with_signature) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700361 if (m == NULL) {
362 return "null";
363 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800364 MethodHelper mh(m);
365 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700366 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800367 result += mh.GetName();
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700368 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700369 const Signature signature = mh.GetSignature();
370 std::string sig_as_string(signature.ToString());
371 if (signature == Signature::NoSignature()) {
372 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700373 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700374 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
375 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700376 }
377 return result;
378}
379
Ian Rogers0571d352011-11-03 19:51:38 -0700380std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800381 if (method_idx >= dex_file.NumMethodIds()) {
382 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
383 }
Ian Rogers0571d352011-11-03 19:51:38 -0700384 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
385 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
386 result += '.';
387 result += dex_file.GetMethodName(method_id);
388 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700389 const Signature signature = dex_file.GetMethodSignature(method_id);
390 std::string sig_as_string(signature.ToString());
391 if (signature == Signature::NoSignature()) {
392 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700393 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700394 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
395 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700396 }
397 return result;
398}
399
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800400std::string PrettyTypeOf(const mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700401 if (obj == NULL) {
402 return "null";
403 }
404 if (obj->GetClass() == NULL) {
405 return "(raw)";
406 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800407 ClassHelper kh(obj->GetClass());
408 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700409 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800410 kh.ChangeClass(obj->AsClass());
411 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700412 }
413 return result;
414}
415
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800416std::string PrettyClass(const mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700417 if (c == NULL) {
418 return "null";
419 }
420 std::string result;
421 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800422 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700423 result += ">";
424 return result;
425}
426
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800427std::string PrettyClassAndClassLoader(const mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700428 if (c == NULL) {
429 return "null";
430 }
431 std::string result;
432 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800433 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700434 result += ",";
435 result += PrettyTypeOf(c->GetClassLoader());
436 // TODO: add an identifying hash value for the loader
437 result += ">";
438 return result;
439}
440
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800441std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700442 // The byte thresholds at which we display amounts. A byte count is displayed
443 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
444 static const size_t kUnitThresholds[] = {
445 0, // B up to...
446 3*1024, // KB up to...
447 2*1024*1024, // MB up to...
448 1024*1024*1024 // GB from here.
449 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800450 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700451 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800452 const char* negative_str = "";
453 if (byte_count < 0) {
454 negative_str = "-";
455 byte_count = -byte_count;
456 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700457 int i = arraysize(kUnitThresholds);
458 while (--i > 0) {
459 if (byte_count >= kUnitThresholds[i]) {
460 break;
461 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800462 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800463 return StringPrintf("%s%lld%s", negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800464}
465
466std::string PrettyDuration(uint64_t nano_duration) {
467 if (nano_duration == 0) {
468 return "0";
469 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700470 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
471 }
472}
473
474TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
475 const uint64_t one_sec = 1000 * 1000 * 1000;
476 const uint64_t one_ms = 1000 * 1000;
477 const uint64_t one_us = 1000;
478 if (nano_duration >= one_sec) {
479 return kTimeUnitSecond;
480 } else if (nano_duration >= one_ms) {
481 return kTimeUnitMillisecond;
482 } else if (nano_duration >= one_us) {
483 return kTimeUnitMicrosecond;
484 } else {
485 return kTimeUnitNanosecond;
486 }
487}
488
489uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
490 const uint64_t one_sec = 1000 * 1000 * 1000;
491 const uint64_t one_ms = 1000 * 1000;
492 const uint64_t one_us = 1000;
493
494 switch (time_unit) {
495 case kTimeUnitSecond:
496 return one_sec;
497 case kTimeUnitMillisecond:
498 return one_ms;
499 case kTimeUnitMicrosecond:
500 return one_us;
501 case kTimeUnitNanosecond:
502 return 1;
503 }
504 return 0;
505}
506
507std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
508 const char* unit = NULL;
509 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
510 uint32_t zero_fill = 1;
511 switch (time_unit) {
512 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800513 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800514 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700515 break;
516 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800517 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800518 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700519 break;
520 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800521 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800522 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700523 break;
524 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800525 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800526 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700527 break;
528 }
529
530 uint64_t whole_part = nano_duration / divisor;
531 uint64_t fractional_part = nano_duration % divisor;
532 if (fractional_part == 0) {
533 return StringPrintf("%llu%s", whole_part, unit);
534 } else {
535 while ((fractional_part % 1000) == 0) {
536 zero_fill -= 3;
537 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800538 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700539 if (zero_fill == 3) {
540 return StringPrintf("%llu.%03llu%s", whole_part, fractional_part, unit);
541 } else if (zero_fill == 6) {
542 return StringPrintf("%llu.%06llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800543 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700544 return StringPrintf("%llu.%09llu%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800545 }
546 }
547}
548
Elliott Hughes82914b62012-04-09 15:56:29 -0700549std::string PrintableString(const std::string& utf) {
550 std::string result;
551 result += '"';
552 const char* p = utf.c_str();
553 size_t char_count = CountModifiedUtf8Chars(p);
554 for (size_t i = 0; i < char_count; ++i) {
555 uint16_t ch = GetUtf16FromUtf8(&p);
556 if (ch == '\\') {
557 result += "\\\\";
558 } else if (ch == '\n') {
559 result += "\\n";
560 } else if (ch == '\r') {
561 result += "\\r";
562 } else if (ch == '\t') {
563 result += "\\t";
564 } else if (NeedsEscaping(ch)) {
565 StringAppendF(&result, "\\u%04x", ch);
566 } else {
567 result += ch;
568 }
569 }
570 result += '"';
571 return result;
572}
573
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800574// 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 -0700575std::string MangleForJni(const std::string& s) {
576 std::string result;
577 size_t char_count = CountModifiedUtf8Chars(s.c_str());
578 const char* cp = &s[0];
579 for (size_t i = 0; i < char_count; ++i) {
580 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800581 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
582 result.push_back(ch);
583 } else if (ch == '.' || ch == '/') {
584 result += "_";
585 } else if (ch == '_') {
586 result += "_1";
587 } else if (ch == ';') {
588 result += "_2";
589 } else if (ch == '[') {
590 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700591 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800592 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700593 }
594 }
595 return result;
596}
597
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700598std::string DotToDescriptor(const char* class_name) {
599 std::string descriptor(class_name);
600 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
601 if (descriptor.length() > 0 && descriptor[0] != '[') {
602 descriptor = "L" + descriptor + ";";
603 }
604 return descriptor;
605}
606
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800607std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800608 size_t length = strlen(descriptor);
609 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
610 std::string result(descriptor + 1, length - 2);
611 std::replace(result.begin(), result.end(), '/', '.');
612 return result;
613 }
614 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800615}
616
617std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800618 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800619 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
620 std::string result(descriptor + 1, length - 2);
621 return result;
622 }
623 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700624}
625
Brian Carlstromea46f952013-07-30 01:26:50 -0700626std::string JniShortName(const mirror::ArtMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800627 MethodHelper mh(m);
628 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700629 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700630 CHECK_EQ(class_name[0], 'L') << class_name;
631 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700632 class_name.erase(0, 1);
633 class_name.erase(class_name.size() - 1, 1);
634
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800635 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700636
637 std::string short_name;
638 short_name += "Java_";
639 short_name += MangleForJni(class_name);
640 short_name += "_";
641 short_name += MangleForJni(method_name);
642 return short_name;
643}
644
Brian Carlstromea46f952013-07-30 01:26:50 -0700645std::string JniLongName(const mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700646 std::string long_name;
647 long_name += JniShortName(m);
648 long_name += "__";
649
Ian Rogersd91d6d62013-09-25 20:26:14 -0700650 std::string signature(MethodHelper(m).GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700651 signature.erase(0, 1);
652 signature.erase(signature.begin() + signature.find(')'), signature.end());
653
654 long_name += MangleForJni(signature);
655
656 return long_name;
657}
658
jeffhao10037c82012-01-23 15:06:23 -0800659// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700660uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700661 0x00000000, // 00..1f low control characters; nothing valid
662 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
663 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
664 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700665};
666
jeffhao10037c82012-01-23 15:06:23 -0800667// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
668bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700669 /*
670 * It's a multibyte encoded character. Decode it and analyze. We
671 * accept anything that isn't (a) an improperly encoded low value,
672 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
673 * control character, or (e) a high space, layout, or special
674 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
675 * U+fff0..U+ffff). This is all specified in the dex format
676 * document.
677 */
678
679 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
680
681 // Perform follow-up tests based on the high 8 bits.
682 switch (utf16 >> 8) {
683 case 0x00:
684 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
685 return (utf16 > 0x00a0);
686 case 0xd8:
687 case 0xd9:
688 case 0xda:
689 case 0xdb:
690 // It's a leading surrogate. Check to see that a trailing
691 // surrogate follows.
692 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
693 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
694 case 0xdc:
695 case 0xdd:
696 case 0xde:
697 case 0xdf:
698 // It's a trailing surrogate, which is not valid at this point.
699 return false;
700 case 0x20:
701 case 0xff:
702 // It's in the range that has spaces, controls, and specials.
703 switch (utf16 & 0xfff8) {
704 case 0x2000:
705 case 0x2008:
706 case 0x2028:
707 case 0xfff0:
708 case 0xfff8:
709 return false;
710 }
711 break;
712 }
713 return true;
714}
715
716/* Return whether the pointed-at modified-UTF-8 encoded character is
717 * valid as part of a member name, updating the pointer to point past
718 * the consumed character. This will consume two encoded UTF-16 code
719 * points if the character is encoded as a surrogate pair. Also, if
720 * this function returns false, then the given pointer may only have
721 * been partially advanced.
722 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700723static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700724 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700725 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700726 // It's low-ascii, so check the table.
727 uint32_t wordIdx = c >> 5;
728 uint32_t bitIdx = c & 0x1f;
729 (*pUtf8Ptr)++;
730 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
731 }
732
733 // It's a multibyte encoded character. Call a non-inline function
734 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800735 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
736}
737
738bool IsValidMemberName(const char* s) {
739 bool angle_name = false;
740
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700741 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800742 case '\0':
743 // The empty string is not a valid name.
744 return false;
745 case '<':
746 angle_name = true;
747 s++;
748 break;
749 }
750
751 while (true) {
752 switch (*s) {
753 case '\0':
754 return !angle_name;
755 case '>':
756 return angle_name && s[1] == '\0';
757 }
758
759 if (!IsValidPartOfMemberNameUtf8(&s)) {
760 return false;
761 }
762 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700763}
764
Elliott Hughes906e6852011-10-28 14:52:10 -0700765enum ClassNameType { kName, kDescriptor };
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700766static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700767 int arrayCount = 0;
768 while (*s == '[') {
769 arrayCount++;
770 s++;
771 }
772
773 if (arrayCount > 255) {
774 // Arrays may have no more than 255 dimensions.
775 return false;
776 }
777
778 if (arrayCount != 0) {
779 /*
780 * If we're looking at an array of some sort, then it doesn't
781 * matter if what is being asked for is a class name; the
782 * format looks the same as a type descriptor in that case, so
783 * treat it as such.
784 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700785 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700786 }
787
Elliott Hughes906e6852011-10-28 14:52:10 -0700788 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700789 /*
790 * We are looking for a descriptor. Either validate it as a
791 * single-character primitive type, or continue on to check the
792 * embedded class name (bracketed by "L" and ";").
793 */
794 switch (*(s++)) {
795 case 'B':
796 case 'C':
797 case 'D':
798 case 'F':
799 case 'I':
800 case 'J':
801 case 'S':
802 case 'Z':
803 // These are all single-character descriptors for primitive types.
804 return (*s == '\0');
805 case 'V':
806 // Non-array void is valid, but you can't have an array of void.
807 return (arrayCount == 0) && (*s == '\0');
808 case 'L':
809 // Class name: Break out and continue below.
810 break;
811 default:
812 // Oddball descriptor character.
813 return false;
814 }
815 }
816
817 /*
818 * We just consumed the 'L' that introduces a class name as part
819 * of a type descriptor, or we are looking for an unadorned class
820 * name.
821 */
822
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700823 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700824 for (;;) {
825 uint8_t c = (uint8_t) *s;
826 switch (c) {
827 case '\0':
828 /*
829 * Premature end for a type descriptor, but valid for
830 * a class name as long as we haven't encountered an
831 * empty component (including the degenerate case of
832 * the empty string "").
833 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700834 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700835 case ';':
836 /*
837 * Invalid character for a class name, but the
838 * legitimate end of a type descriptor. In the latter
839 * case, make sure that this is the end of the string
840 * and that it doesn't end with an empty component
841 * (including the degenerate case of "L;").
842 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700843 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700844 case '/':
845 case '.':
846 if (c != separator) {
847 // The wrong separator character.
848 return false;
849 }
850 if (sepOrFirst) {
851 // Separator at start or two separators in a row.
852 return false;
853 }
854 sepOrFirst = true;
855 s++;
856 break;
857 default:
jeffhao10037c82012-01-23 15:06:23 -0800858 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700859 return false;
860 }
861 sepOrFirst = false;
862 break;
863 }
864 }
865}
866
Elliott Hughes906e6852011-10-28 14:52:10 -0700867bool IsValidBinaryClassName(const char* s) {
868 return IsValidClassName(s, kName, '.');
869}
870
871bool IsValidJniClassName(const char* s) {
872 return IsValidClassName(s, kName, '/');
873}
874
875bool IsValidDescriptor(const char* s) {
876 return IsValidClassName(s, kDescriptor, '/');
877}
878
Elliott Hughes48436bb2012-02-07 15:23:28 -0800879void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700880 const char* p = s.data();
881 const char* end = p + s.size();
882 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800883 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700884 ++p;
885 } else {
886 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800887 while (++p != end && *p != separator) {
888 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700889 }
890 result.push_back(std::string(start, p - start));
891 }
892 }
893}
894
Dave Allison70202782013-10-22 17:52:19 -0700895std::string Trim(std::string s) {
896 std::string result;
897 unsigned int start_index = 0;
898 unsigned int end_index = s.size() - 1;
899
900 // Skip initial whitespace.
901 while (start_index < s.size()) {
902 if (!isspace(s[start_index])) {
903 break;
904 }
905 start_index++;
906 }
907
908 // Skip terminating whitespace.
909 while (end_index >= start_index) {
910 if (!isspace(s[end_index])) {
911 break;
912 }
913 end_index--;
914 }
915
916 // All spaces, no beef.
917 if (end_index < start_index) {
918 return "";
919 }
920 // Start_index is the first non-space, end_index is the last one.
921 return s.substr(start_index, end_index - start_index + 1);
922}
923
Elliott Hughes48436bb2012-02-07 15:23:28 -0800924template <typename StringT>
925std::string Join(std::vector<StringT>& strings, char separator) {
926 if (strings.empty()) {
927 return "";
928 }
929
930 std::string result(strings[0]);
931 for (size_t i = 1; i < strings.size(); ++i) {
932 result += separator;
933 result += strings[i];
934 }
935 return result;
936}
937
938// Explicit instantiations.
939template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
940template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
941template std::string Join<char*>(std::vector<char*>& strings, char separator);
942
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800943bool StartsWith(const std::string& s, const char* prefix) {
944 return s.compare(0, strlen(prefix), prefix) == 0;
945}
946
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700947bool EndsWith(const std::string& s, const char* suffix) {
948 size_t suffix_length = strlen(suffix);
949 size_t string_length = s.size();
950 if (suffix_length > string_length) {
951 return false;
952 }
953 size_t offset = string_length - suffix_length;
954 return s.compare(offset, suffix_length, suffix) == 0;
955}
956
Elliott Hughes22869a92012-03-27 14:08:24 -0700957void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700958 int hasAt = 0;
959 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700960 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700961 while (*s) {
962 if (*s == '.') {
963 hasDot = 1;
964 } else if (*s == '@') {
965 hasAt = 1;
966 }
967 s++;
968 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700969 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700970 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700971 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700972 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700973 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700974 }
975#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700976 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700977 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
978 strncpy(buf, s, sizeof(buf)-1);
979 buf[sizeof(buf)-1] = '\0';
980 errno = pthread_setname_np(pthread_self(), buf);
981 if (errno != 0) {
982 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
983 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700984#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700985 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700986#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700987 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700988#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700989 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700990#endif
991}
992
Brian Carlstrom29212012013-09-12 22:18:30 -0700993void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
994 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700995 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700996 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700997 return;
998 }
999 // Skip the command, which may contain spaces.
1000 stats = stats.substr(stats.find(')') + 2);
1001 // Extract the three fields we care about.
1002 std::vector<std::string> fields;
1003 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001004 *state = fields[0][0];
1005 *utime = strtoull(fields[11].c_str(), NULL, 10);
1006 *stime = strtoull(fields[12].c_str(), NULL, 10);
1007 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001008}
1009
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001010std::string GetSchedulerGroupName(pid_t tid) {
1011 // /proc/<pid>/cgroup looks like this:
1012 // 2:devices:/
1013 // 1:cpuacct,cpu:/
1014 // We want the third field from the line whose second field contains the "cpu" token.
1015 std::string cgroup_file;
1016 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1017 return "";
1018 }
1019 std::vector<std::string> cgroup_lines;
1020 Split(cgroup_file, '\n', cgroup_lines);
1021 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1022 std::vector<std::string> cgroup_fields;
1023 Split(cgroup_lines[i], ':', cgroup_fields);
1024 std::vector<std::string> cgroups;
1025 Split(cgroup_fields[1], ',', cgroups);
1026 for (size_t i = 0; i < cgroups.size(); ++i) {
1027 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001028 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001029 }
1030 }
1031 }
1032 return "";
1033}
1034
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001035static const char* CleanMapName(const char* map_name) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001036 if (map_name == NULL) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001037 return "???";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001038 }
1039 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1040 // into "libartd.so".
1041 const char* last_slash = strrchr(map_name, '/');
1042 if (last_slash != NULL) {
1043 map_name = last_slash + 1;
1044 }
1045 return map_name;
1046}
1047
Elliott Hughes46e251b2012-05-22 15:10:45 -07001048void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Christopher Ferris6e9aeb62013-11-05 16:23:10 -08001049 UniquePtr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001050 if (!backtrace->Unwind(0)) {
1051 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001052 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001053 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001054 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001055 return;
1056 }
1057
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001058 for (size_t i = 0; i < backtrace->NumFrames(); ++i) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001059 // We produce output like this:
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001060 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libbacktrace.so)
1061 const backtrace_frame_data_t* frame = backtrace->GetFrame(i);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001062
1063 os << prefix;
1064 if (include_count) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001065 os << StringPrintf("#%02zu ", i);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001066 }
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001067 if (frame->func_name) {
1068 os << frame->func_name;
1069 } else {
1070 os << "???";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001071 }
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001072 if (frame->func_offset != 0) {
1073 os << "+" << frame->func_offset;
1074 }
1075 os << StringPrintf(" [%p]", reinterpret_cast<void*>(frame->pc));
1076 os << " (" << CleanMapName(frame->map_name) << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001077 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001078}
1079
Elliott Hughes058a6de2012-05-24 19:13:02 -07001080#if defined(__APPLE__)
1081
1082// TODO: is there any way to get the kernel stack on Mac OS?
1083void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1084
1085#else
1086
Elliott Hughes46e251b2012-05-22 15:10:45 -07001087void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001088 if (tid == GetTid()) {
1089 // There's no point showing that we're reading our stack out of /proc!
1090 return;
1091 }
1092
Elliott Hughes46e251b2012-05-22 15:10:45 -07001093 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1094 std::string kernel_stack;
1095 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001096 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001097 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001098 }
1099
1100 std::vector<std::string> kernel_stack_frames;
1101 Split(kernel_stack, '\n', kernel_stack_frames);
1102 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1103 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1104 kernel_stack_frames.pop_back();
1105 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1106 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1107 const char* text = kernel_stack_frames[i].c_str();
1108 const char* close_bracket = strchr(text, ']');
1109 if (close_bracket != NULL) {
1110 text = close_bracket + 2;
1111 }
1112 os << prefix;
1113 if (include_count) {
1114 os << StringPrintf("#%02zd ", i);
1115 }
1116 os << text << "\n";
1117 }
1118}
1119
1120#endif
1121
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001122const char* GetAndroidRoot() {
1123 const char* android_root = getenv("ANDROID_ROOT");
1124 if (android_root == NULL) {
1125 if (OS::DirectoryExists("/system")) {
1126 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001127 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001128 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1129 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001130 }
1131 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001132 if (!OS::DirectoryExists(android_root)) {
1133 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001134 return "";
1135 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001136 return android_root;
1137}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001138
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001139const char* GetAndroidData() {
1140 const char* android_data = getenv("ANDROID_DATA");
1141 if (android_data == NULL) {
1142 if (OS::DirectoryExists("/data")) {
1143 android_data = "/data";
1144 } else {
1145 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1146 return "";
1147 }
1148 }
1149 if (!OS::DirectoryExists(android_data)) {
1150 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1151 return "";
1152 }
1153 return android_data;
1154}
1155
Brian Carlstrom7675e162013-06-10 16:18:04 -07001156std::string GetDalvikCacheOrDie(const char* android_data) {
1157 std::string dalvik_cache(StringPrintf("%s/dalvik-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001158
Brian Carlstrom7675e162013-06-10 16:18:04 -07001159 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1160 if (StartsWith(dalvik_cache, "/tmp/")) {
1161 int result = mkdir(dalvik_cache.c_str(), 0700);
Brian Carlstroma9f19782011-10-13 00:14:47 -07001162 if (result != 0) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001163 LOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001164 return "";
1165 }
1166 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001167 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001168 return "";
1169 }
1170 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001171 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001172}
1173
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001174std::string GetDalvikCacheFilenameOrDie(const char* location) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001175 std::string dalvik_cache(GetDalvikCacheOrDie(GetAndroidData()));
Ian Rogerse6060102013-05-16 12:01:04 -07001176 if (location[0] != '/') {
1177 LOG(FATAL) << "Expected path in location to be absolute: "<< location;
1178 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001179 std::string cache_file(&location[1]); // skip leading slash
Brian Carlstrom19a08362013-10-16 14:37:22 -07001180 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001181 cache_file += "/";
1182 cache_file += DexFile::kClassesDex;
1183 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001184 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Brian Carlstrom7675e162013-06-10 16:18:04 -07001185 return dalvik_cache + "/" + cache_file;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001186}
1187
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001188bool IsZipMagic(uint32_t magic) {
1189 return (('P' == ((magic >> 0) & 0xff)) &&
1190 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001191}
1192
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001193bool IsDexMagic(uint32_t magic) {
1194 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001195}
1196
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001197bool IsOatMagic(uint32_t magic) {
1198 return (memcmp(reinterpret_cast<const byte*>(magic),
1199 OatHeader::kOatMagic,
1200 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001201}
1202
Elliott Hughes42ee1422011-09-06 12:33:32 -07001203} // namespace art