blob: 8e6ddaf0c967dbdba6dc80243eddc9a96b97ae44 [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
Christopher Ferris943af7d2014-01-16 12:41:46 -080019#include <inttypes.h>
Elliott Hughes92b3b562011-09-08 16:32:26 -070020#include <pthread.h>
Brian Carlstroma9f19782011-10-13 00:14:47 -070021#include <sys/stat.h>
Elliott Hughes42ee1422011-09-06 12:33:32 -070022#include <sys/syscall.h>
23#include <sys/types.h>
24#include <unistd.h>
25
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include "UniquePtr.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080027#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070030#include "mirror/art_field-inl.h"
31#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "mirror/object-inl.h"
35#include "mirror/object_array-inl.h"
36#include "mirror/string.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080037#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070038#include "os.h"
Ian Rogersa6724902013-09-23 09:23:37 -070039#include "utf-inl.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070040
Elliott Hughesad6c9c32012-01-19 17:39:12 -080041#if !defined(HAVE_POSIX_CLOCKS)
42#include <sys/time.h>
43#endif
44
Elliott Hughesdcc24742011-09-07 14:02:44 -070045#if defined(HAVE_PRCTL)
46#include <sys/prctl.h>
47#endif
48
Elliott Hughes4ae722a2012-03-13 11:08:51 -070049#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070050#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070051#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070052#endif
53
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070054#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070055
Elliott Hughes058a6de2012-05-24 19:13:02 -070056#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080057#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080058#endif
59
Elliott Hughes11e45072011-08-16 17:40:46 -070060namespace art {
61
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080062pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070063#if defined(__APPLE__)
64 uint64_t owner;
65 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
66 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080067#else
68 // Neither bionic nor glibc exposes gettid(2).
69 return syscall(__NR_gettid);
70#endif
71}
72
Elliott Hughes289be852012-06-12 13:57:20 -070073std::string GetThreadName(pid_t tid) {
74 std::string result;
75 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070076 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070077 } else {
78 result = "<unknown>";
79 }
80 return result;
81}
82
Brian Carlstrom29212012013-09-12 22:18:30 -070083void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070084#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070085 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070086 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070087
88 // Check whether stack_addr is the base or end of the stack.
89 // (On Mac OS 10.7, it's the end.)
90 int stack_variable;
91 if (stack_addr > &stack_variable) {
Brian Carlstrom29212012013-09-12 22:18:30 -070092 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070093 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070094 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070095 }
96#else
97 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070098 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -070099 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700100 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
101#endif
102}
103
Elliott Hughesd92bec42011-09-02 17:04:36 -0700104bool ReadFileToString(const std::string& file_name, std::string* result) {
Elliott Hughes76160052012-12-12 16:31:20 -0800105 UniquePtr<File> file(new File);
106 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700107 return false;
108 }
buzbeec143c552011-08-20 17:38:58 -0700109
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700110 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700111 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800112 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700113 if (n == -1) {
114 return false;
buzbeec143c552011-08-20 17:38:58 -0700115 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700116 if (n == 0) {
117 return true;
118 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700119 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700120 }
buzbeec143c552011-08-20 17:38:58 -0700121}
122
Elliott Hughese27955c2011-08-26 15:21:24 -0700123std::string GetIsoDate() {
124 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700125 tm tmbuf;
126 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700127 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
128 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
129 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
130}
131
Elliott Hughes7162ad92011-10-27 14:08:42 -0700132uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800133#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700134 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135 clock_gettime(CLOCK_MONOTONIC, &now);
136 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800137#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700138 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800139 gettimeofday(&now, NULL);
140 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
141#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700142}
143
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800144uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800145#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700146 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147 clock_gettime(CLOCK_MONOTONIC, &now);
148 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800149#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700150 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800151 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700152 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800153#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800154}
155
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700156uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800157#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700158 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159 clock_gettime(CLOCK_MONOTONIC, &now);
160 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800161#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700162 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800163 gettimeofday(&now, NULL);
164 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
165#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700166}
167
Elliott Hughes0512f022012-03-15 22:10:52 -0700168uint64_t ThreadCpuNanoTime() {
169#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700170 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700171 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
172 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
173#else
174 UNIMPLEMENTED(WARNING);
175 return -1;
176#endif
177}
178
Ian Rogers56edc432013-01-18 16:51:51 -0800179void NanoSleep(uint64_t ns) {
180 timespec tm;
181 tm.tv_sec = 0;
182 tm.tv_nsec = ns;
183 nanosleep(&tm, NULL);
184}
185
Brian Carlstrombcc29262012-11-02 11:36:03 -0700186void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
187 int64_t endSec;
188
189 if (absolute) {
190#if !defined(__APPLE__)
191 clock_gettime(clock, ts);
192#else
193 UNUSED(clock);
194 timeval tv;
195 gettimeofday(&tv, NULL);
196 ts->tv_sec = tv.tv_sec;
197 ts->tv_nsec = tv.tv_usec * 1000;
198#endif
199 } else {
200 ts->tv_sec = 0;
201 ts->tv_nsec = 0;
202 }
203 endSec = ts->tv_sec + ms / 1000;
204 if (UNLIKELY(endSec >= 0x7fffffff)) {
205 std::ostringstream ss;
206 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
207 endSec = 0x7ffffffe;
208 }
209 ts->tv_sec = endSec;
210 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
211
212 // Catch rollover.
213 if (ts->tv_nsec >= 1000000000L) {
214 ts->tv_sec++;
215 ts->tv_nsec -= 1000000000L;
216 }
217}
218
Ian Rogersef7d42f2014-01-06 12:55:46 -0800219std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700220 if (java_descriptor == NULL) {
221 return "null";
222 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700223 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
224}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700225
Ian Rogersef7d42f2014-01-06 12:55:46 -0800226std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800227 if (klass == NULL) {
228 return "null";
229 }
230 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800231}
232
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700233std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700234 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700235 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700236 size_t dim = 0;
237 while (*c == '[') {
238 dim++;
239 c++;
240 }
241
242 // Reference or primitive?
243 if (*c == 'L') {
244 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700245 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700246 } else {
247 // "[[B" -> "byte[][]".
248 // To make life easier, we make primitives look like unqualified
249 // reference types.
250 switch (*c) {
251 case 'B': c = "byte;"; break;
252 case 'C': c = "char;"; break;
253 case 'D': c = "double;"; break;
254 case 'F': c = "float;"; break;
255 case 'I': c = "int;"; break;
256 case 'J': c = "long;"; break;
257 case 'S': c = "short;"; break;
258 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700259 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700260 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700261 }
262 }
263
264 // At this point, 'c' is a string of the form "fully/qualified/Type;"
265 // or "primitive;". Rewrite the type with '.' instead of '/':
266 std::string result;
267 const char* p = c;
268 while (*p != ';') {
269 char ch = *p++;
270 if (ch == '/') {
271 ch = '.';
272 }
273 result.push_back(ch);
274 }
275 // ...and replace the semicolon with 'dim' "[]" pairs:
276 while (dim--) {
277 result += "[]";
278 }
279 return result;
280}
281
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700282std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800283 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700284 return PrettyDescriptor(descriptor_string);
285}
286
Ian Rogersef7d42f2014-01-06 12:55:46 -0800287std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700288 if (f == NULL) {
289 return "null";
290 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800291 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700292 std::string result;
293 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800294 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700295 result += ' ';
296 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800297 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700298 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800299 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700300 return result;
301}
302
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700303std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800304 if (field_idx >= dex_file.NumFieldIds()) {
305 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
306 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700307 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
308 std::string result;
309 if (with_type) {
310 result += dex_file.GetFieldTypeDescriptor(field_id);
311 result += ' ';
312 }
313 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
314 result += '.';
315 result += dex_file.GetFieldName(field_id);
316 return result;
317}
318
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700319std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800320 if (type_idx >= dex_file.NumTypeIds()) {
321 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
322 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700323 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700324 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700325}
326
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700327std::string PrettyArguments(const char* signature) {
328 std::string result;
329 result += '(';
330 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700331 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700332 while (*signature != ')') {
333 size_t argument_length = 0;
334 while (signature[argument_length] == '[') {
335 ++argument_length;
336 }
337 if (signature[argument_length] == 'L') {
338 argument_length = (strchr(signature, ';') - signature + 1);
339 } else {
340 ++argument_length;
341 }
342 std::string argument_descriptor(signature, argument_length);
343 result += PrettyDescriptor(argument_descriptor);
344 if (signature[argument_length] != ')') {
345 result += ", ";
346 }
347 signature += argument_length;
348 }
349 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700350 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700351 result += ')';
352 return result;
353}
354
355std::string PrettyReturnType(const char* signature) {
356 const char* return_type = strchr(signature, ')');
357 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700358 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700359 return PrettyDescriptor(return_type);
360}
361
Ian Rogersef7d42f2014-01-06 12:55:46 -0800362std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800363 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700364 return "null";
365 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800366 MethodHelper mh(m);
367 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700368 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800369 result += mh.GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800370 if (UNLIKELY(m->IsFastNative())) {
371 result += "!";
372 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700373 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700374 const Signature signature = mh.GetSignature();
375 std::string sig_as_string(signature.ToString());
376 if (signature == Signature::NoSignature()) {
377 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700378 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700379 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
380 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700381 }
382 return result;
383}
384
Ian Rogers0571d352011-11-03 19:51:38 -0700385std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800386 if (method_idx >= dex_file.NumMethodIds()) {
387 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
388 }
Ian Rogers0571d352011-11-03 19:51:38 -0700389 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
390 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
391 result += '.';
392 result += dex_file.GetMethodName(method_id);
393 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700394 const Signature signature = dex_file.GetMethodSignature(method_id);
395 std::string sig_as_string(signature.ToString());
396 if (signature == Signature::NoSignature()) {
397 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700398 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700399 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
400 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700401 }
402 return result;
403}
404
Ian Rogersef7d42f2014-01-06 12:55:46 -0800405std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700406 if (obj == NULL) {
407 return "null";
408 }
409 if (obj->GetClass() == NULL) {
410 return "(raw)";
411 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800412 ClassHelper kh(obj->GetClass());
413 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700414 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800415 kh.ChangeClass(obj->AsClass());
416 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700417 }
418 return result;
419}
420
Ian Rogersef7d42f2014-01-06 12:55:46 -0800421std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700422 if (c == NULL) {
423 return "null";
424 }
425 std::string result;
426 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800427 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700428 result += ">";
429 return result;
430}
431
Ian Rogersef7d42f2014-01-06 12:55:46 -0800432std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700433 if (c == NULL) {
434 return "null";
435 }
436 std::string result;
437 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800438 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700439 result += ",";
440 result += PrettyTypeOf(c->GetClassLoader());
441 // TODO: add an identifying hash value for the loader
442 result += ">";
443 return result;
444}
445
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800446std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700447 // The byte thresholds at which we display amounts. A byte count is displayed
448 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800449 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700450 0, // B up to...
451 3*1024, // KB up to...
452 2*1024*1024, // MB up to...
453 1024*1024*1024 // GB from here.
454 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800455 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700456 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800457 const char* negative_str = "";
458 if (byte_count < 0) {
459 negative_str = "-";
460 byte_count = -byte_count;
461 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700462 int i = arraysize(kUnitThresholds);
463 while (--i > 0) {
464 if (byte_count >= kUnitThresholds[i]) {
465 break;
466 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800467 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800468 return StringPrintf("%s%" PRId64 "%s", negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800469}
470
471std::string PrettyDuration(uint64_t nano_duration) {
472 if (nano_duration == 0) {
473 return "0";
474 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700475 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
476 }
477}
478
479TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
480 const uint64_t one_sec = 1000 * 1000 * 1000;
481 const uint64_t one_ms = 1000 * 1000;
482 const uint64_t one_us = 1000;
483 if (nano_duration >= one_sec) {
484 return kTimeUnitSecond;
485 } else if (nano_duration >= one_ms) {
486 return kTimeUnitMillisecond;
487 } else if (nano_duration >= one_us) {
488 return kTimeUnitMicrosecond;
489 } else {
490 return kTimeUnitNanosecond;
491 }
492}
493
494uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
495 const uint64_t one_sec = 1000 * 1000 * 1000;
496 const uint64_t one_ms = 1000 * 1000;
497 const uint64_t one_us = 1000;
498
499 switch (time_unit) {
500 case kTimeUnitSecond:
501 return one_sec;
502 case kTimeUnitMillisecond:
503 return one_ms;
504 case kTimeUnitMicrosecond:
505 return one_us;
506 case kTimeUnitNanosecond:
507 return 1;
508 }
509 return 0;
510}
511
512std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
513 const char* unit = NULL;
514 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
515 uint32_t zero_fill = 1;
516 switch (time_unit) {
517 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800518 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800519 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700520 break;
521 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800522 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800523 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700524 break;
525 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800526 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800527 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700528 break;
529 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800530 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800531 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700532 break;
533 }
534
535 uint64_t whole_part = nano_duration / divisor;
536 uint64_t fractional_part = nano_duration % divisor;
537 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800538 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700539 } else {
540 while ((fractional_part % 1000) == 0) {
541 zero_fill -= 3;
542 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800543 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700544 if (zero_fill == 3) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800545 return StringPrintf("%" PRIu64 ".%03" PRIu64 "%s", whole_part, fractional_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700546 } else if (zero_fill == 6) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800547 return StringPrintf("%" PRIu64 ".%06" PRIu64 "%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800548 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800549 return StringPrintf("%" PRIu64 ".%09" PRIu64 "%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800550 }
551 }
552}
553
Elliott Hughes82914b62012-04-09 15:56:29 -0700554std::string PrintableString(const std::string& utf) {
555 std::string result;
556 result += '"';
557 const char* p = utf.c_str();
558 size_t char_count = CountModifiedUtf8Chars(p);
559 for (size_t i = 0; i < char_count; ++i) {
560 uint16_t ch = GetUtf16FromUtf8(&p);
561 if (ch == '\\') {
562 result += "\\\\";
563 } else if (ch == '\n') {
564 result += "\\n";
565 } else if (ch == '\r') {
566 result += "\\r";
567 } else if (ch == '\t') {
568 result += "\\t";
569 } else if (NeedsEscaping(ch)) {
570 StringAppendF(&result, "\\u%04x", ch);
571 } else {
572 result += ch;
573 }
574 }
575 result += '"';
576 return result;
577}
578
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800579// See http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp615 for the full rules.
Elliott Hughes79082e32011-08-25 12:07:32 -0700580std::string MangleForJni(const std::string& s) {
581 std::string result;
582 size_t char_count = CountModifiedUtf8Chars(s.c_str());
583 const char* cp = &s[0];
584 for (size_t i = 0; i < char_count; ++i) {
585 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800586 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
587 result.push_back(ch);
588 } else if (ch == '.' || ch == '/') {
589 result += "_";
590 } else if (ch == '_') {
591 result += "_1";
592 } else if (ch == ';') {
593 result += "_2";
594 } else if (ch == '[') {
595 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700596 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800597 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700598 }
599 }
600 return result;
601}
602
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700603std::string DotToDescriptor(const char* class_name) {
604 std::string descriptor(class_name);
605 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
606 if (descriptor.length() > 0 && descriptor[0] != '[') {
607 descriptor = "L" + descriptor + ";";
608 }
609 return descriptor;
610}
611
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800612std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800613 size_t length = strlen(descriptor);
614 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
615 std::string result(descriptor + 1, length - 2);
616 std::replace(result.begin(), result.end(), '/', '.');
617 return result;
618 }
619 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800620}
621
622std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800623 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800624 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
625 std::string result(descriptor + 1, length - 2);
626 return result;
627 }
628 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700629}
630
Ian Rogersef7d42f2014-01-06 12:55:46 -0800631std::string JniShortName(mirror::ArtMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800632 MethodHelper mh(m);
633 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700634 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700635 CHECK_EQ(class_name[0], 'L') << class_name;
636 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700637 class_name.erase(0, 1);
638 class_name.erase(class_name.size() - 1, 1);
639
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800640 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700641
642 std::string short_name;
643 short_name += "Java_";
644 short_name += MangleForJni(class_name);
645 short_name += "_";
646 short_name += MangleForJni(method_name);
647 return short_name;
648}
649
Ian Rogersef7d42f2014-01-06 12:55:46 -0800650std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700651 std::string long_name;
652 long_name += JniShortName(m);
653 long_name += "__";
654
Ian Rogersd91d6d62013-09-25 20:26:14 -0700655 std::string signature(MethodHelper(m).GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700656 signature.erase(0, 1);
657 signature.erase(signature.begin() + signature.find(')'), signature.end());
658
659 long_name += MangleForJni(signature);
660
661 return long_name;
662}
663
jeffhao10037c82012-01-23 15:06:23 -0800664// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700665uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700666 0x00000000, // 00..1f low control characters; nothing valid
667 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
668 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
669 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700670};
671
jeffhao10037c82012-01-23 15:06:23 -0800672// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
673bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700674 /*
675 * It's a multibyte encoded character. Decode it and analyze. We
676 * accept anything that isn't (a) an improperly encoded low value,
677 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
678 * control character, or (e) a high space, layout, or special
679 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
680 * U+fff0..U+ffff). This is all specified in the dex format
681 * document.
682 */
683
684 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
685
686 // Perform follow-up tests based on the high 8 bits.
687 switch (utf16 >> 8) {
688 case 0x00:
689 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
690 return (utf16 > 0x00a0);
691 case 0xd8:
692 case 0xd9:
693 case 0xda:
694 case 0xdb:
695 // It's a leading surrogate. Check to see that a trailing
696 // surrogate follows.
697 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
698 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
699 case 0xdc:
700 case 0xdd:
701 case 0xde:
702 case 0xdf:
703 // It's a trailing surrogate, which is not valid at this point.
704 return false;
705 case 0x20:
706 case 0xff:
707 // It's in the range that has spaces, controls, and specials.
708 switch (utf16 & 0xfff8) {
709 case 0x2000:
710 case 0x2008:
711 case 0x2028:
712 case 0xfff0:
713 case 0xfff8:
714 return false;
715 }
716 break;
717 }
718 return true;
719}
720
721/* Return whether the pointed-at modified-UTF-8 encoded character is
722 * valid as part of a member name, updating the pointer to point past
723 * the consumed character. This will consume two encoded UTF-16 code
724 * points if the character is encoded as a surrogate pair. Also, if
725 * this function returns false, then the given pointer may only have
726 * been partially advanced.
727 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700728static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700729 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700730 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700731 // It's low-ascii, so check the table.
732 uint32_t wordIdx = c >> 5;
733 uint32_t bitIdx = c & 0x1f;
734 (*pUtf8Ptr)++;
735 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
736 }
737
738 // It's a multibyte encoded character. Call a non-inline function
739 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800740 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
741}
742
743bool IsValidMemberName(const char* s) {
744 bool angle_name = false;
745
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700746 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800747 case '\0':
748 // The empty string is not a valid name.
749 return false;
750 case '<':
751 angle_name = true;
752 s++;
753 break;
754 }
755
756 while (true) {
757 switch (*s) {
758 case '\0':
759 return !angle_name;
760 case '>':
761 return angle_name && s[1] == '\0';
762 }
763
764 if (!IsValidPartOfMemberNameUtf8(&s)) {
765 return false;
766 }
767 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700768}
769
Elliott Hughes906e6852011-10-28 14:52:10 -0700770enum ClassNameType { kName, kDescriptor };
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700771static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700772 int arrayCount = 0;
773 while (*s == '[') {
774 arrayCount++;
775 s++;
776 }
777
778 if (arrayCount > 255) {
779 // Arrays may have no more than 255 dimensions.
780 return false;
781 }
782
783 if (arrayCount != 0) {
784 /*
785 * If we're looking at an array of some sort, then it doesn't
786 * matter if what is being asked for is a class name; the
787 * format looks the same as a type descriptor in that case, so
788 * treat it as such.
789 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700790 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700791 }
792
Elliott Hughes906e6852011-10-28 14:52:10 -0700793 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700794 /*
795 * We are looking for a descriptor. Either validate it as a
796 * single-character primitive type, or continue on to check the
797 * embedded class name (bracketed by "L" and ";").
798 */
799 switch (*(s++)) {
800 case 'B':
801 case 'C':
802 case 'D':
803 case 'F':
804 case 'I':
805 case 'J':
806 case 'S':
807 case 'Z':
808 // These are all single-character descriptors for primitive types.
809 return (*s == '\0');
810 case 'V':
811 // Non-array void is valid, but you can't have an array of void.
812 return (arrayCount == 0) && (*s == '\0');
813 case 'L':
814 // Class name: Break out and continue below.
815 break;
816 default:
817 // Oddball descriptor character.
818 return false;
819 }
820 }
821
822 /*
823 * We just consumed the 'L' that introduces a class name as part
824 * of a type descriptor, or we are looking for an unadorned class
825 * name.
826 */
827
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700828 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700829 for (;;) {
830 uint8_t c = (uint8_t) *s;
831 switch (c) {
832 case '\0':
833 /*
834 * Premature end for a type descriptor, but valid for
835 * a class name as long as we haven't encountered an
836 * empty component (including the degenerate case of
837 * the empty string "").
838 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700839 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700840 case ';':
841 /*
842 * Invalid character for a class name, but the
843 * legitimate end of a type descriptor. In the latter
844 * case, make sure that this is the end of the string
845 * and that it doesn't end with an empty component
846 * (including the degenerate case of "L;").
847 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700848 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700849 case '/':
850 case '.':
851 if (c != separator) {
852 // The wrong separator character.
853 return false;
854 }
855 if (sepOrFirst) {
856 // Separator at start or two separators in a row.
857 return false;
858 }
859 sepOrFirst = true;
860 s++;
861 break;
862 default:
jeffhao10037c82012-01-23 15:06:23 -0800863 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700864 return false;
865 }
866 sepOrFirst = false;
867 break;
868 }
869 }
870}
871
Elliott Hughes906e6852011-10-28 14:52:10 -0700872bool IsValidBinaryClassName(const char* s) {
873 return IsValidClassName(s, kName, '.');
874}
875
876bool IsValidJniClassName(const char* s) {
877 return IsValidClassName(s, kName, '/');
878}
879
880bool IsValidDescriptor(const char* s) {
881 return IsValidClassName(s, kDescriptor, '/');
882}
883
Elliott Hughes48436bb2012-02-07 15:23:28 -0800884void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700885 const char* p = s.data();
886 const char* end = p + s.size();
887 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800888 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700889 ++p;
890 } else {
891 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800892 while (++p != end && *p != separator) {
893 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700894 }
895 result.push_back(std::string(start, p - start));
896 }
897 }
898}
899
Dave Allison70202782013-10-22 17:52:19 -0700900std::string Trim(std::string s) {
901 std::string result;
902 unsigned int start_index = 0;
903 unsigned int end_index = s.size() - 1;
904
905 // Skip initial whitespace.
906 while (start_index < s.size()) {
907 if (!isspace(s[start_index])) {
908 break;
909 }
910 start_index++;
911 }
912
913 // Skip terminating whitespace.
914 while (end_index >= start_index) {
915 if (!isspace(s[end_index])) {
916 break;
917 }
918 end_index--;
919 }
920
921 // All spaces, no beef.
922 if (end_index < start_index) {
923 return "";
924 }
925 // Start_index is the first non-space, end_index is the last one.
926 return s.substr(start_index, end_index - start_index + 1);
927}
928
Elliott Hughes48436bb2012-02-07 15:23:28 -0800929template <typename StringT>
930std::string Join(std::vector<StringT>& strings, char separator) {
931 if (strings.empty()) {
932 return "";
933 }
934
935 std::string result(strings[0]);
936 for (size_t i = 1; i < strings.size(); ++i) {
937 result += separator;
938 result += strings[i];
939 }
940 return result;
941}
942
943// Explicit instantiations.
944template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
945template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
946template std::string Join<char*>(std::vector<char*>& strings, char separator);
947
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800948bool StartsWith(const std::string& s, const char* prefix) {
949 return s.compare(0, strlen(prefix), prefix) == 0;
950}
951
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700952bool EndsWith(const std::string& s, const char* suffix) {
953 size_t suffix_length = strlen(suffix);
954 size_t string_length = s.size();
955 if (suffix_length > string_length) {
956 return false;
957 }
958 size_t offset = string_length - suffix_length;
959 return s.compare(offset, suffix_length, suffix) == 0;
960}
961
Elliott Hughes22869a92012-03-27 14:08:24 -0700962void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700963 int hasAt = 0;
964 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700965 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700966 while (*s) {
967 if (*s == '.') {
968 hasDot = 1;
969 } else if (*s == '@') {
970 hasAt = 1;
971 }
972 s++;
973 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700974 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700975 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700976 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700977 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700978 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700979 }
980#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700981 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700982 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
983 strncpy(buf, s, sizeof(buf)-1);
984 buf[sizeof(buf)-1] = '\0';
985 errno = pthread_setname_np(pthread_self(), buf);
986 if (errno != 0) {
987 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
988 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700989#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700990 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700991#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700992 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700993#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700994 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700995#endif
996}
997
Brian Carlstrom29212012013-09-12 22:18:30 -0700998void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
999 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001000 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001001 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001002 return;
1003 }
1004 // Skip the command, which may contain spaces.
1005 stats = stats.substr(stats.find(')') + 2);
1006 // Extract the three fields we care about.
1007 std::vector<std::string> fields;
1008 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001009 *state = fields[0][0];
1010 *utime = strtoull(fields[11].c_str(), NULL, 10);
1011 *stime = strtoull(fields[12].c_str(), NULL, 10);
1012 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001013}
1014
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001015std::string GetSchedulerGroupName(pid_t tid) {
1016 // /proc/<pid>/cgroup looks like this:
1017 // 2:devices:/
1018 // 1:cpuacct,cpu:/
1019 // We want the third field from the line whose second field contains the "cpu" token.
1020 std::string cgroup_file;
1021 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1022 return "";
1023 }
1024 std::vector<std::string> cgroup_lines;
1025 Split(cgroup_file, '\n', cgroup_lines);
1026 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1027 std::vector<std::string> cgroup_fields;
1028 Split(cgroup_lines[i], ':', cgroup_fields);
1029 std::vector<std::string> cgroups;
1030 Split(cgroup_fields[1], ',', cgroups);
1031 for (size_t i = 0; i < cgroups.size(); ++i) {
1032 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001033 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001034 }
1035 }
1036 }
1037 return "";
1038}
1039
Christopher Ferris943af7d2014-01-16 12:41:46 -08001040static std::string CleanMapName(const backtrace_map_t* map) {
1041 if (map == NULL || map->name.empty()) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001042 return "???";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001043 }
1044 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1045 // into "libartd.so".
Christopher Ferris943af7d2014-01-16 12:41:46 -08001046 size_t last_slash = map->name.rfind('/');
1047 if (last_slash == std::string::npos) {
1048 return map->name;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001049 }
Christopher Ferris943af7d2014-01-16 12:41:46 -08001050 return map->name.substr(last_slash);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001051}
1052
Elliott Hughes46e251b2012-05-22 15:10:45 -07001053void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Christopher Ferris6e9aeb62013-11-05 16:23:10 -08001054 UniquePtr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001055 if (!backtrace->Unwind(0)) {
1056 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001057 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001058 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001059 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001060 return;
1061 }
1062
Christopher Ferris943af7d2014-01-16 12:41:46 -08001063 for (Backtrace::const_iterator it = backtrace->begin();
1064 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001065 // We produce output like this:
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001066 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libbacktrace.so)
Elliott Hughes46e251b2012-05-22 15:10:45 -07001067 os << prefix;
1068 if (include_count) {
Christopher Ferris943af7d2014-01-16 12:41:46 -08001069 os << StringPrintf("#%02zu ", it->num);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001070 }
Christopher Ferris943af7d2014-01-16 12:41:46 -08001071 if (!it->func_name.empty()) {
1072 os << it->func_name;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001073 } else {
1074 os << "???";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001075 }
Christopher Ferris943af7d2014-01-16 12:41:46 -08001076 if (it->func_offset != 0) {
1077 os << "+" << it->func_offset;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001078 }
Christopher Ferris943af7d2014-01-16 12:41:46 -08001079 os << StringPrintf(" [%p]", reinterpret_cast<void*>(it->pc));
1080 os << " (" << CleanMapName(it->map) << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001081 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001082}
1083
Elliott Hughes058a6de2012-05-24 19:13:02 -07001084#if defined(__APPLE__)
1085
1086// TODO: is there any way to get the kernel stack on Mac OS?
1087void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1088
1089#else
1090
Elliott Hughes46e251b2012-05-22 15:10:45 -07001091void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001092 if (tid == GetTid()) {
1093 // There's no point showing that we're reading our stack out of /proc!
1094 return;
1095 }
1096
Elliott Hughes46e251b2012-05-22 15:10:45 -07001097 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1098 std::string kernel_stack;
1099 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001100 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001101 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001102 }
1103
1104 std::vector<std::string> kernel_stack_frames;
1105 Split(kernel_stack, '\n', kernel_stack_frames);
1106 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1107 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1108 kernel_stack_frames.pop_back();
1109 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1110 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1111 const char* text = kernel_stack_frames[i].c_str();
1112 const char* close_bracket = strchr(text, ']');
1113 if (close_bracket != NULL) {
1114 text = close_bracket + 2;
1115 }
1116 os << prefix;
1117 if (include_count) {
1118 os << StringPrintf("#%02zd ", i);
1119 }
1120 os << text << "\n";
1121 }
1122}
1123
1124#endif
1125
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001126const char* GetAndroidRoot() {
1127 const char* android_root = getenv("ANDROID_ROOT");
1128 if (android_root == NULL) {
1129 if (OS::DirectoryExists("/system")) {
1130 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001131 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001132 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1133 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001134 }
1135 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001136 if (!OS::DirectoryExists(android_root)) {
1137 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001138 return "";
1139 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001140 return android_root;
1141}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001142
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001143const char* GetAndroidData() {
1144 const char* android_data = getenv("ANDROID_DATA");
1145 if (android_data == NULL) {
1146 if (OS::DirectoryExists("/data")) {
1147 android_data = "/data";
1148 } else {
1149 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1150 return "";
1151 }
1152 }
1153 if (!OS::DirectoryExists(android_data)) {
1154 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1155 return "";
1156 }
1157 return android_data;
1158}
1159
Brian Carlstrom7675e162013-06-10 16:18:04 -07001160std::string GetDalvikCacheOrDie(const char* android_data) {
1161 std::string dalvik_cache(StringPrintf("%s/dalvik-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001162
Brian Carlstrom7675e162013-06-10 16:18:04 -07001163 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1164 if (StartsWith(dalvik_cache, "/tmp/")) {
1165 int result = mkdir(dalvik_cache.c_str(), 0700);
Brian Carlstroma9f19782011-10-13 00:14:47 -07001166 if (result != 0) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001167 LOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001168 return "";
1169 }
1170 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001171 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001172 return "";
1173 }
1174 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001175 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001176}
1177
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001178std::string GetDalvikCacheFilenameOrDie(const char* location) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001179 std::string dalvik_cache(GetDalvikCacheOrDie(GetAndroidData()));
Ian Rogerse6060102013-05-16 12:01:04 -07001180 if (location[0] != '/') {
1181 LOG(FATAL) << "Expected path in location to be absolute: "<< location;
1182 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001183 std::string cache_file(&location[1]); // skip leading slash
Brian Carlstrom19a08362013-10-16 14:37:22 -07001184 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001185 cache_file += "/";
1186 cache_file += DexFile::kClassesDex;
1187 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001188 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Brian Carlstrom7675e162013-06-10 16:18:04 -07001189 return dalvik_cache + "/" + cache_file;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001190}
1191
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001192bool IsZipMagic(uint32_t magic) {
1193 return (('P' == ((magic >> 0) & 0xff)) &&
1194 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001195}
1196
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001197bool IsDexMagic(uint32_t magic) {
1198 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001199}
1200
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001201bool IsOatMagic(uint32_t magic) {
1202 return (memcmp(reinterpret_cast<const byte*>(magic),
1203 OatHeader::kOatMagic,
1204 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001205}
1206
Brian Carlstrom6449c622014-02-10 23:48:36 -08001207bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1208 const std::string command_line(Join(arg_vector, ' '));
1209
1210 CHECK_GE(arg_vector.size(), 1U) << command_line;
1211
1212 // Convert the args to char pointers.
1213 const char* program = arg_vector[0].c_str();
1214 std::vector<char*> args;
1215 for (std::vector<std::string>::const_iterator it = arg_vector.begin(); it != arg_vector.end();
1216 ++it) {
1217 CHECK(*it != nullptr);
1218 args.push_back(const_cast<char*>(it->c_str()));
1219 }
1220 args.push_back(NULL);
1221
1222 // fork and exec
1223 pid_t pid = fork();
1224 if (pid == 0) {
1225 // no allocation allowed between fork and exec
1226
1227 // change process groups, so we don't get reaped by ProcessManager
1228 setpgid(0, 0);
1229
1230 execv(program, &args[0]);
1231
1232 *error_msg = StringPrintf("Failed to execv(%s): %s", command_line.c_str(), strerror(errno));
1233 return false;
1234 } else {
1235 if (pid == -1) {
1236 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1237 command_line.c_str(), strerror(errno));
1238 return false;
1239 }
1240
1241 // wait for subprocess to finish
1242 int status;
1243 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1244 if (got_pid != pid) {
1245 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1246 "wanted %d, got %d: %s",
1247 command_line.c_str(), pid, got_pid, strerror(errno));
1248 return false;
1249 }
1250 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1251 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1252 command_line.c_str());
1253 return false;
1254 }
1255 }
1256 return true;
1257}
1258
Elliott Hughes42ee1422011-09-06 12:33:32 -07001259} // namespace art