blob: d2d23e8de62d9c820633a34d21ab9a9d4c7cde40 [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>
Brian Carlstrom4cf5e572014-02-25 11:47:48 -080024#include <sys/wait.h>
25
Elliott Hughes42ee1422011-09-06 12:33:32 -070026#include <unistd.h>
27
Elliott Hughes90a33692011-08-30 13:27:07 -070028#include "UniquePtr.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070031#include "dex_file-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070032#include "mirror/art_field-inl.h"
33#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "mirror/object-inl.h"
37#include "mirror/object_array-inl.h"
38#include "mirror/string.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080039#include "object_utils.h"
buzbeec143c552011-08-20 17:38:58 -070040#include "os.h"
Kenny Root067d20f2014-03-05 14:57:21 -080041#include "scoped_thread_state_change.h"
Ian Rogersa6724902013-09-23 09:23:37 -070042#include "utf-inl.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070043
Elliott Hughesad6c9c32012-01-19 17:39:12 -080044#if !defined(HAVE_POSIX_CLOCKS)
45#include <sys/time.h>
46#endif
47
Elliott Hughesdcc24742011-09-07 14:02:44 -070048#if defined(HAVE_PRCTL)
49#include <sys/prctl.h>
50#endif
51
Elliott Hughes4ae722a2012-03-13 11:08:51 -070052#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070053#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070054#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070055#endif
56
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070057#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070058
Elliott Hughes058a6de2012-05-24 19:13:02 -070059#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080060#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080061#endif
62
Elliott Hughes11e45072011-08-16 17:40:46 -070063namespace art {
64
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080065pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070066#if defined(__APPLE__)
67 uint64_t owner;
68 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
69 return owner;
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080070#else
71 // Neither bionic nor glibc exposes gettid(2).
72 return syscall(__NR_gettid);
73#endif
74}
75
Elliott Hughes289be852012-06-12 13:57:20 -070076std::string GetThreadName(pid_t tid) {
77 std::string result;
78 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070079 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070080 } else {
81 result = "<unknown>";
82 }
83 return result;
84}
85
Brian Carlstrom29212012013-09-12 22:18:30 -070086void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070087#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070088 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070089 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070090
91 // Check whether stack_addr is the base or end of the stack.
92 // (On Mac OS 10.7, it's the end.)
93 int stack_variable;
94 if (stack_addr > &stack_variable) {
Brian Carlstrom29212012013-09-12 22:18:30 -070095 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070096 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070097 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070098 }
99#else
100 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700101 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700102 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700103 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
104#endif
105}
106
Elliott Hughesd92bec42011-09-02 17:04:36 -0700107bool ReadFileToString(const std::string& file_name, std::string* result) {
Elliott Hughes76160052012-12-12 16:31:20 -0800108 UniquePtr<File> file(new File);
109 if (!file->Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700110 return false;
111 }
buzbeec143c552011-08-20 17:38:58 -0700112
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700113 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700114 while (true) {
Elliott Hughes76160052012-12-12 16:31:20 -0800115 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700116 if (n == -1) {
117 return false;
buzbeec143c552011-08-20 17:38:58 -0700118 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700119 if (n == 0) {
120 return true;
121 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700122 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700123 }
buzbeec143c552011-08-20 17:38:58 -0700124}
125
Elliott Hughese27955c2011-08-26 15:21:24 -0700126std::string GetIsoDate() {
127 time_t now = time(NULL);
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700128 tm tmbuf;
129 tm* ptm = localtime_r(&now, &tmbuf);
Elliott Hughese27955c2011-08-26 15:21:24 -0700130 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
131 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
132 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
133}
134
Elliott Hughes7162ad92011-10-27 14:08:42 -0700135uint64_t MilliTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800136#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700137 timespec now;
Elliott Hughes7162ad92011-10-27 14:08:42 -0700138 clock_gettime(CLOCK_MONOTONIC, &now);
139 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800140#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700141 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800142 gettimeofday(&now, NULL);
143 return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
144#endif
Elliott Hughes7162ad92011-10-27 14:08:42 -0700145}
146
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800147uint64_t MicroTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800148#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700149 timespec now;
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800150 clock_gettime(CLOCK_MONOTONIC, &now);
151 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800152#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700153 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800154 gettimeofday(&now, NULL);
TDYa12754825032012-04-11 10:45:23 -0700155 return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800156#endif
jeffhaoa9ef3fd2011-12-13 18:33:43 -0800157}
158
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700159uint64_t NanoTime() {
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800160#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700161 timespec now;
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700162 clock_gettime(CLOCK_MONOTONIC, &now);
163 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800164#else
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700165 timeval now;
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800166 gettimeofday(&now, NULL);
167 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
168#endif
Elliott Hughes83df2ac2011-10-11 16:37:54 -0700169}
170
Elliott Hughes0512f022012-03-15 22:10:52 -0700171uint64_t ThreadCpuNanoTime() {
172#if defined(HAVE_POSIX_CLOCKS)
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700173 timespec now;
Elliott Hughes0512f022012-03-15 22:10:52 -0700174 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
175 return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
176#else
177 UNIMPLEMENTED(WARNING);
178 return -1;
179#endif
180}
181
Ian Rogers56edc432013-01-18 16:51:51 -0800182void NanoSleep(uint64_t ns) {
183 timespec tm;
184 tm.tv_sec = 0;
185 tm.tv_nsec = ns;
186 nanosleep(&tm, NULL);
187}
188
Brian Carlstrombcc29262012-11-02 11:36:03 -0700189void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
190 int64_t endSec;
191
192 if (absolute) {
193#if !defined(__APPLE__)
194 clock_gettime(clock, ts);
195#else
196 UNUSED(clock);
197 timeval tv;
198 gettimeofday(&tv, NULL);
199 ts->tv_sec = tv.tv_sec;
200 ts->tv_nsec = tv.tv_usec * 1000;
201#endif
202 } else {
203 ts->tv_sec = 0;
204 ts->tv_nsec = 0;
205 }
206 endSec = ts->tv_sec + ms / 1000;
207 if (UNLIKELY(endSec >= 0x7fffffff)) {
208 std::ostringstream ss;
209 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
210 endSec = 0x7ffffffe;
211 }
212 ts->tv_sec = endSec;
213 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
214
215 // Catch rollover.
216 if (ts->tv_nsec >= 1000000000L) {
217 ts->tv_sec++;
218 ts->tv_nsec -= 1000000000L;
219 }
220}
221
Ian Rogersef7d42f2014-01-06 12:55:46 -0800222std::string PrettyDescriptor(mirror::String* java_descriptor) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700223 if (java_descriptor == NULL) {
224 return "null";
225 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700226 return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
227}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700228
Ian Rogersef7d42f2014-01-06 12:55:46 -0800229std::string PrettyDescriptor(mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800230 if (klass == NULL) {
231 return "null";
232 }
233 return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800234}
235
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700236std::string PrettyDescriptor(const std::string& descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700237 // Count the number of '['s to get the dimensionality.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700238 const char* c = descriptor.c_str();
Elliott Hughes11e45072011-08-16 17:40:46 -0700239 size_t dim = 0;
240 while (*c == '[') {
241 dim++;
242 c++;
243 }
244
245 // Reference or primitive?
246 if (*c == 'L') {
247 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700248 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700249 } else {
250 // "[[B" -> "byte[][]".
251 // To make life easier, we make primitives look like unqualified
252 // reference types.
253 switch (*c) {
254 case 'B': c = "byte;"; break;
255 case 'C': c = "char;"; break;
256 case 'D': c = "double;"; break;
257 case 'F': c = "float;"; break;
258 case 'I': c = "int;"; break;
259 case 'J': c = "long;"; break;
260 case 'S': c = "short;"; break;
261 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700262 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700263 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700264 }
265 }
266
267 // At this point, 'c' is a string of the form "fully/qualified/Type;"
268 // or "primitive;". Rewrite the type with '.' instead of '/':
269 std::string result;
270 const char* p = c;
271 while (*p != ';') {
272 char ch = *p++;
273 if (ch == '/') {
274 ch = '.';
275 }
276 result.push_back(ch);
277 }
278 // ...and replace the semicolon with 'dim' "[]" pairs:
279 while (dim--) {
280 result += "[]";
281 }
282 return result;
283}
284
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700285std::string PrettyDescriptor(Primitive::Type type) {
Elliott Hughes91250e02011-12-13 22:30:35 -0800286 std::string descriptor_string(Primitive::Descriptor(type));
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700287 return PrettyDescriptor(descriptor_string);
288}
289
Ian Rogersef7d42f2014-01-06 12:55:46 -0800290std::string PrettyField(mirror::ArtField* f, bool with_type) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700291 if (f == NULL) {
292 return "null";
293 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800294 FieldHelper fh(f);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700295 std::string result;
296 if (with_type) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800297 result += PrettyDescriptor(fh.GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700298 result += ' ';
299 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800300 result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
Elliott Hughesa2501992011-08-26 19:39:54 -0700301 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800302 result += fh.GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700303 return result;
304}
305
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700306std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800307 if (field_idx >= dex_file.NumFieldIds()) {
308 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
309 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700310 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
311 std::string result;
312 if (with_type) {
313 result += dex_file.GetFieldTypeDescriptor(field_id);
314 result += ' ';
315 }
316 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
317 result += '.';
318 result += dex_file.GetFieldName(field_id);
319 return result;
320}
321
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700322std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800323 if (type_idx >= dex_file.NumTypeIds()) {
324 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
325 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700326 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700327 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700328}
329
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700330std::string PrettyArguments(const char* signature) {
331 std::string result;
332 result += '(';
333 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700334 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700335 while (*signature != ')') {
336 size_t argument_length = 0;
337 while (signature[argument_length] == '[') {
338 ++argument_length;
339 }
340 if (signature[argument_length] == 'L') {
341 argument_length = (strchr(signature, ';') - signature + 1);
342 } else {
343 ++argument_length;
344 }
345 std::string argument_descriptor(signature, argument_length);
346 result += PrettyDescriptor(argument_descriptor);
347 if (signature[argument_length] != ')') {
348 result += ", ";
349 }
350 signature += argument_length;
351 }
352 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700353 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700354 result += ')';
355 return result;
356}
357
358std::string PrettyReturnType(const char* signature) {
359 const char* return_type = strchr(signature, ')');
360 CHECK(return_type != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700361 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700362 return PrettyDescriptor(return_type);
363}
364
Ian Rogersef7d42f2014-01-06 12:55:46 -0800365std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800366 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700367 return "null";
368 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800369 MethodHelper mh(m);
370 std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700371 result += '.';
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800372 result += mh.GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800373 if (UNLIKELY(m->IsFastNative())) {
374 result += "!";
375 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700376 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700377 const Signature signature = mh.GetSignature();
378 std::string sig_as_string(signature.ToString());
379 if (signature == Signature::NoSignature()) {
380 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700381 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700382 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
383 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700384 }
385 return result;
386}
387
Ian Rogers0571d352011-11-03 19:51:38 -0700388std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800389 if (method_idx >= dex_file.NumMethodIds()) {
390 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
391 }
Ian Rogers0571d352011-11-03 19:51:38 -0700392 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
393 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
394 result += '.';
395 result += dex_file.GetMethodName(method_id);
396 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700397 const Signature signature = dex_file.GetMethodSignature(method_id);
398 std::string sig_as_string(signature.ToString());
399 if (signature == Signature::NoSignature()) {
400 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700401 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700402 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
403 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700404 }
405 return result;
406}
407
Ian Rogersef7d42f2014-01-06 12:55:46 -0800408std::string PrettyTypeOf(mirror::Object* obj) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700409 if (obj == NULL) {
410 return "null";
411 }
412 if (obj->GetClass() == NULL) {
413 return "(raw)";
414 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800415 ClassHelper kh(obj->GetClass());
416 std::string result(PrettyDescriptor(kh.GetDescriptor()));
Elliott Hughes11e45072011-08-16 17:40:46 -0700417 if (obj->IsClass()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800418 kh.ChangeClass(obj->AsClass());
419 result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700420 }
421 return result;
422}
423
Ian Rogersef7d42f2014-01-06 12:55:46 -0800424std::string PrettyClass(mirror::Class* c) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700425 if (c == NULL) {
426 return "null";
427 }
428 std::string result;
429 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800430 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700431 result += ">";
432 return result;
433}
434
Ian Rogersef7d42f2014-01-06 12:55:46 -0800435std::string PrettyClassAndClassLoader(mirror::Class* c) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700436 if (c == NULL) {
437 return "null";
438 }
439 std::string result;
440 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800441 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700442 result += ",";
443 result += PrettyTypeOf(c->GetClassLoader());
444 // TODO: add an identifying hash value for the loader
445 result += ">";
446 return result;
447}
448
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800449std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700450 // The byte thresholds at which we display amounts. A byte count is displayed
451 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800452 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700453 0, // B up to...
454 3*1024, // KB up to...
455 2*1024*1024, // MB up to...
456 1024*1024*1024 // GB from here.
457 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800458 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700459 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800460 const char* negative_str = "";
461 if (byte_count < 0) {
462 negative_str = "-";
463 byte_count = -byte_count;
464 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700465 int i = arraysize(kUnitThresholds);
466 while (--i > 0) {
467 if (byte_count >= kUnitThresholds[i]) {
468 break;
469 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800470 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800471 return StringPrintf("%s%" PRId64 "%s", negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800472}
473
474std::string PrettyDuration(uint64_t nano_duration) {
475 if (nano_duration == 0) {
476 return "0";
477 } else {
Mathieu Chartier0325e622012-09-05 14:22:51 -0700478 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration));
479 }
480}
481
482TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
483 const uint64_t one_sec = 1000 * 1000 * 1000;
484 const uint64_t one_ms = 1000 * 1000;
485 const uint64_t one_us = 1000;
486 if (nano_duration >= one_sec) {
487 return kTimeUnitSecond;
488 } else if (nano_duration >= one_ms) {
489 return kTimeUnitMillisecond;
490 } else if (nano_duration >= one_us) {
491 return kTimeUnitMicrosecond;
492 } else {
493 return kTimeUnitNanosecond;
494 }
495}
496
497uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
498 const uint64_t one_sec = 1000 * 1000 * 1000;
499 const uint64_t one_ms = 1000 * 1000;
500 const uint64_t one_us = 1000;
501
502 switch (time_unit) {
503 case kTimeUnitSecond:
504 return one_sec;
505 case kTimeUnitMillisecond:
506 return one_ms;
507 case kTimeUnitMicrosecond:
508 return one_us;
509 case kTimeUnitNanosecond:
510 return 1;
511 }
512 return 0;
513}
514
515std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit) {
516 const char* unit = NULL;
517 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
518 uint32_t zero_fill = 1;
519 switch (time_unit) {
520 case kTimeUnitSecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800521 unit = "s";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800522 zero_fill = 9;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700523 break;
524 case kTimeUnitMillisecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800525 unit = "ms";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800526 zero_fill = 6;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700527 break;
528 case kTimeUnitMicrosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800529 unit = "us";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800530 zero_fill = 3;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700531 break;
532 case kTimeUnitNanosecond:
Ian Rogers3bb17a62012-01-27 23:56:44 -0800533 unit = "ns";
Ian Rogers3bb17a62012-01-27 23:56:44 -0800534 zero_fill = 0;
Mathieu Chartier0325e622012-09-05 14:22:51 -0700535 break;
536 }
537
538 uint64_t whole_part = nano_duration / divisor;
539 uint64_t fractional_part = nano_duration % divisor;
540 if (fractional_part == 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800541 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700542 } else {
543 while ((fractional_part % 1000) == 0) {
544 zero_fill -= 3;
545 fractional_part /= 1000;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800546 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700547 if (zero_fill == 3) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800548 return StringPrintf("%" PRIu64 ".%03" PRIu64 "%s", whole_part, fractional_part, unit);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700549 } else if (zero_fill == 6) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800550 return StringPrintf("%" PRIu64 ".%06" PRIu64 "%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800551 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800552 return StringPrintf("%" PRIu64 ".%09" PRIu64 "%s", whole_part, fractional_part, unit);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800553 }
554 }
555}
556
Elliott Hughes82914b62012-04-09 15:56:29 -0700557std::string PrintableString(const std::string& utf) {
558 std::string result;
559 result += '"';
560 const char* p = utf.c_str();
561 size_t char_count = CountModifiedUtf8Chars(p);
562 for (size_t i = 0; i < char_count; ++i) {
563 uint16_t ch = GetUtf16FromUtf8(&p);
564 if (ch == '\\') {
565 result += "\\\\";
566 } else if (ch == '\n') {
567 result += "\\n";
568 } else if (ch == '\r') {
569 result += "\\r";
570 } else if (ch == '\t') {
571 result += "\\t";
572 } else if (NeedsEscaping(ch)) {
573 StringAppendF(&result, "\\u%04x", ch);
574 } else {
575 result += ch;
576 }
577 }
578 result += '"';
579 return result;
580}
581
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800582// 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 -0700583std::string MangleForJni(const std::string& s) {
584 std::string result;
585 size_t char_count = CountModifiedUtf8Chars(s.c_str());
586 const char* cp = &s[0];
587 for (size_t i = 0; i < char_count; ++i) {
588 uint16_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800589 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
590 result.push_back(ch);
591 } else if (ch == '.' || ch == '/') {
592 result += "_";
593 } else if (ch == '_') {
594 result += "_1";
595 } else if (ch == ';') {
596 result += "_2";
597 } else if (ch == '[') {
598 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700599 } else {
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800600 StringAppendF(&result, "_0%04x", ch);
Elliott Hughes79082e32011-08-25 12:07:32 -0700601 }
602 }
603 return result;
604}
605
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700606std::string DotToDescriptor(const char* class_name) {
607 std::string descriptor(class_name);
608 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
609 if (descriptor.length() > 0 && descriptor[0] != '[') {
610 descriptor = "L" + descriptor + ";";
611 }
612 return descriptor;
613}
614
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800615std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800616 size_t length = strlen(descriptor);
617 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
618 std::string result(descriptor + 1, length - 2);
619 std::replace(result.begin(), result.end(), '/', '.');
620 return result;
621 }
622 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800623}
624
625std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800626 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800627 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
628 std::string result(descriptor + 1, length - 2);
629 return result;
630 }
631 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700632}
633
Ian Rogersef7d42f2014-01-06 12:55:46 -0800634std::string JniShortName(mirror::ArtMethod* m) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800635 MethodHelper mh(m);
636 std::string class_name(mh.GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700637 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700638 CHECK_EQ(class_name[0], 'L') << class_name;
639 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700640 class_name.erase(0, 1);
641 class_name.erase(class_name.size() - 1, 1);
642
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800643 std::string method_name(mh.GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700644
645 std::string short_name;
646 short_name += "Java_";
647 short_name += MangleForJni(class_name);
648 short_name += "_";
649 short_name += MangleForJni(method_name);
650 return short_name;
651}
652
Ian Rogersef7d42f2014-01-06 12:55:46 -0800653std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700654 std::string long_name;
655 long_name += JniShortName(m);
656 long_name += "__";
657
Ian Rogersd91d6d62013-09-25 20:26:14 -0700658 std::string signature(MethodHelper(m).GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700659 signature.erase(0, 1);
660 signature.erase(signature.begin() + signature.find(')'), signature.end());
661
662 long_name += MangleForJni(signature);
663
664 return long_name;
665}
666
jeffhao10037c82012-01-23 15:06:23 -0800667// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700668uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700669 0x00000000, // 00..1f low control characters; nothing valid
670 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
671 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
672 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700673};
674
jeffhao10037c82012-01-23 15:06:23 -0800675// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
676bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700677 /*
678 * It's a multibyte encoded character. Decode it and analyze. We
679 * accept anything that isn't (a) an improperly encoded low value,
680 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
681 * control character, or (e) a high space, layout, or special
682 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
683 * U+fff0..U+ffff). This is all specified in the dex format
684 * document.
685 */
686
687 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
688
689 // Perform follow-up tests based on the high 8 bits.
690 switch (utf16 >> 8) {
691 case 0x00:
692 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
693 return (utf16 > 0x00a0);
694 case 0xd8:
695 case 0xd9:
696 case 0xda:
697 case 0xdb:
698 // It's a leading surrogate. Check to see that a trailing
699 // surrogate follows.
700 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
701 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
702 case 0xdc:
703 case 0xdd:
704 case 0xde:
705 case 0xdf:
706 // It's a trailing surrogate, which is not valid at this point.
707 return false;
708 case 0x20:
709 case 0xff:
710 // It's in the range that has spaces, controls, and specials.
711 switch (utf16 & 0xfff8) {
712 case 0x2000:
713 case 0x2008:
714 case 0x2028:
715 case 0xfff0:
716 case 0xfff8:
717 return false;
718 }
719 break;
720 }
721 return true;
722}
723
724/* Return whether the pointed-at modified-UTF-8 encoded character is
725 * valid as part of a member name, updating the pointer to point past
726 * the consumed character. This will consume two encoded UTF-16 code
727 * points if the character is encoded as a surrogate pair. Also, if
728 * this function returns false, then the given pointer may only have
729 * been partially advanced.
730 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700731static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700732 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700733 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700734 // It's low-ascii, so check the table.
735 uint32_t wordIdx = c >> 5;
736 uint32_t bitIdx = c & 0x1f;
737 (*pUtf8Ptr)++;
738 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
739 }
740
741 // It's a multibyte encoded character. Call a non-inline function
742 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800743 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
744}
745
746bool IsValidMemberName(const char* s) {
747 bool angle_name = false;
748
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700749 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800750 case '\0':
751 // The empty string is not a valid name.
752 return false;
753 case '<':
754 angle_name = true;
755 s++;
756 break;
757 }
758
759 while (true) {
760 switch (*s) {
761 case '\0':
762 return !angle_name;
763 case '>':
764 return angle_name && s[1] == '\0';
765 }
766
767 if (!IsValidPartOfMemberNameUtf8(&s)) {
768 return false;
769 }
770 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700771}
772
Elliott Hughes906e6852011-10-28 14:52:10 -0700773enum ClassNameType { kName, kDescriptor };
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700774static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700775 int arrayCount = 0;
776 while (*s == '[') {
777 arrayCount++;
778 s++;
779 }
780
781 if (arrayCount > 255) {
782 // Arrays may have no more than 255 dimensions.
783 return false;
784 }
785
786 if (arrayCount != 0) {
787 /*
788 * If we're looking at an array of some sort, then it doesn't
789 * matter if what is being asked for is a class name; the
790 * format looks the same as a type descriptor in that case, so
791 * treat it as such.
792 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700793 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700794 }
795
Elliott Hughes906e6852011-10-28 14:52:10 -0700796 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700797 /*
798 * We are looking for a descriptor. Either validate it as a
799 * single-character primitive type, or continue on to check the
800 * embedded class name (bracketed by "L" and ";").
801 */
802 switch (*(s++)) {
803 case 'B':
804 case 'C':
805 case 'D':
806 case 'F':
807 case 'I':
808 case 'J':
809 case 'S':
810 case 'Z':
811 // These are all single-character descriptors for primitive types.
812 return (*s == '\0');
813 case 'V':
814 // Non-array void is valid, but you can't have an array of void.
815 return (arrayCount == 0) && (*s == '\0');
816 case 'L':
817 // Class name: Break out and continue below.
818 break;
819 default:
820 // Oddball descriptor character.
821 return false;
822 }
823 }
824
825 /*
826 * We just consumed the 'L' that introduces a class name as part
827 * of a type descriptor, or we are looking for an unadorned class
828 * name.
829 */
830
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700831 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700832 for (;;) {
833 uint8_t c = (uint8_t) *s;
834 switch (c) {
835 case '\0':
836 /*
837 * Premature end for a type descriptor, but valid for
838 * a class name as long as we haven't encountered an
839 * empty component (including the degenerate case of
840 * the empty string "").
841 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700842 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700843 case ';':
844 /*
845 * Invalid character for a class name, but the
846 * legitimate end of a type descriptor. In the latter
847 * case, make sure that this is the end of the string
848 * and that it doesn't end with an empty component
849 * (including the degenerate case of "L;").
850 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700851 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700852 case '/':
853 case '.':
854 if (c != separator) {
855 // The wrong separator character.
856 return false;
857 }
858 if (sepOrFirst) {
859 // Separator at start or two separators in a row.
860 return false;
861 }
862 sepOrFirst = true;
863 s++;
864 break;
865 default:
jeffhao10037c82012-01-23 15:06:23 -0800866 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700867 return false;
868 }
869 sepOrFirst = false;
870 break;
871 }
872 }
873}
874
Elliott Hughes906e6852011-10-28 14:52:10 -0700875bool IsValidBinaryClassName(const char* s) {
876 return IsValidClassName(s, kName, '.');
877}
878
879bool IsValidJniClassName(const char* s) {
880 return IsValidClassName(s, kName, '/');
881}
882
883bool IsValidDescriptor(const char* s) {
884 return IsValidClassName(s, kDescriptor, '/');
885}
886
Elliott Hughes48436bb2012-02-07 15:23:28 -0800887void Split(const std::string& s, char separator, std::vector<std::string>& result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700888 const char* p = s.data();
889 const char* end = p + s.size();
890 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800891 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700892 ++p;
893 } else {
894 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800895 while (++p != end && *p != separator) {
896 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700897 }
898 result.push_back(std::string(start, p - start));
899 }
900 }
901}
902
Dave Allison70202782013-10-22 17:52:19 -0700903std::string Trim(std::string s) {
904 std::string result;
905 unsigned int start_index = 0;
906 unsigned int end_index = s.size() - 1;
907
908 // Skip initial whitespace.
909 while (start_index < s.size()) {
910 if (!isspace(s[start_index])) {
911 break;
912 }
913 start_index++;
914 }
915
916 // Skip terminating whitespace.
917 while (end_index >= start_index) {
918 if (!isspace(s[end_index])) {
919 break;
920 }
921 end_index--;
922 }
923
924 // All spaces, no beef.
925 if (end_index < start_index) {
926 return "";
927 }
928 // Start_index is the first non-space, end_index is the last one.
929 return s.substr(start_index, end_index - start_index + 1);
930}
931
Elliott Hughes48436bb2012-02-07 15:23:28 -0800932template <typename StringT>
933std::string Join(std::vector<StringT>& strings, char separator) {
934 if (strings.empty()) {
935 return "";
936 }
937
938 std::string result(strings[0]);
939 for (size_t i = 1; i < strings.size(); ++i) {
940 result += separator;
941 result += strings[i];
942 }
943 return result;
944}
945
946// Explicit instantiations.
947template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
948template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
949template std::string Join<char*>(std::vector<char*>& strings, char separator);
950
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800951bool StartsWith(const std::string& s, const char* prefix) {
952 return s.compare(0, strlen(prefix), prefix) == 0;
953}
954
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700955bool EndsWith(const std::string& s, const char* suffix) {
956 size_t suffix_length = strlen(suffix);
957 size_t string_length = s.size();
958 if (suffix_length > string_length) {
959 return false;
960 }
961 size_t offset = string_length - suffix_length;
962 return s.compare(offset, suffix_length, suffix) == 0;
963}
964
Elliott Hughes22869a92012-03-27 14:08:24 -0700965void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700966 int hasAt = 0;
967 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700968 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700969 while (*s) {
970 if (*s == '.') {
971 hasDot = 1;
972 } else if (*s == '@') {
973 hasAt = 1;
974 }
975 s++;
976 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700977 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700978 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700979 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700980 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700981 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700982 }
983#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700984 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700985 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
986 strncpy(buf, s, sizeof(buf)-1);
987 buf[sizeof(buf)-1] = '\0';
988 errno = pthread_setname_np(pthread_self(), buf);
989 if (errno != 0) {
990 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
991 }
Elliott Hughes4ae722a2012-03-13 11:08:51 -0700992#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
Elliott Hughes22869a92012-03-27 14:08:24 -0700993 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700994#elif defined(HAVE_PRCTL)
Elliott Hughes398f64b2012-03-26 18:05:48 -0700995 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
Elliott Hughesdcc24742011-09-07 14:02:44 -0700996#else
Elliott Hughes22869a92012-03-27 14:08:24 -0700997 UNIMPLEMENTED(WARNING) << thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700998#endif
999}
1000
Brian Carlstrom29212012013-09-12 22:18:30 -07001001void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1002 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001003 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001004 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001005 return;
1006 }
1007 // Skip the command, which may contain spaces.
1008 stats = stats.substr(stats.find(')') + 2);
1009 // Extract the three fields we care about.
1010 std::vector<std::string> fields;
1011 Split(stats, ' ', fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001012 *state = fields[0][0];
1013 *utime = strtoull(fields[11].c_str(), NULL, 10);
1014 *stime = strtoull(fields[12].c_str(), NULL, 10);
1015 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001016}
1017
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001018std::string GetSchedulerGroupName(pid_t tid) {
1019 // /proc/<pid>/cgroup looks like this:
1020 // 2:devices:/
1021 // 1:cpuacct,cpu:/
1022 // We want the third field from the line whose second field contains the "cpu" token.
1023 std::string cgroup_file;
1024 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1025 return "";
1026 }
1027 std::vector<std::string> cgroup_lines;
1028 Split(cgroup_file, '\n', cgroup_lines);
1029 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1030 std::vector<std::string> cgroup_fields;
1031 Split(cgroup_lines[i], ':', cgroup_fields);
1032 std::vector<std::string> cgroups;
1033 Split(cgroup_fields[1], ',', cgroups);
1034 for (size_t i = 0; i < cgroups.size(); ++i) {
1035 if (cgroups[i] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001036 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001037 }
1038 }
1039 }
1040 return "";
1041}
1042
Christopher Ferris943af7d2014-01-16 12:41:46 -08001043static std::string CleanMapName(const backtrace_map_t* map) {
1044 if (map == NULL || map->name.empty()) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001045 return "???";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001046 }
1047 // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1048 // into "libartd.so".
Christopher Ferris943af7d2014-01-16 12:41:46 -08001049 size_t last_slash = map->name.rfind('/');
1050 if (last_slash == std::string::npos) {
1051 return map->name;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001052 }
Kenny Rootcc460f12014-03-05 14:11:04 -08001053 return map->name.substr(last_slash + 1);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001054}
1055
Kenny Root067d20f2014-03-05 14:57:21 -08001056void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count,
1057 mirror::ArtMethod* current_method) {
1058 // We may be called from contexts where current_method is not null, so we must assert this.
1059 if (current_method != nullptr) {
1060 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1061 }
Christopher Ferris6e9aeb62013-11-05 16:23:10 -08001062 UniquePtr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001063 if (!backtrace->Unwind(0)) {
1064 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001065 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001066 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001067 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001068 return;
1069 }
1070
Christopher Ferris943af7d2014-01-16 12:41:46 -08001071 for (Backtrace::const_iterator it = backtrace->begin();
1072 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001073 // We produce output like this:
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001074 // ] #00 unwind_backtrace_thread+536 [0x55d75bb8] (libbacktrace.so)
Elliott Hughes46e251b2012-05-22 15:10:45 -07001075 os << prefix;
1076 if (include_count) {
Christopher Ferris943af7d2014-01-16 12:41:46 -08001077 os << StringPrintf("#%02zu ", it->num);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001078 }
Christopher Ferris943af7d2014-01-16 12:41:46 -08001079 if (!it->func_name.empty()) {
1080 os << it->func_name;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001081 } else {
Kenny Root067d20f2014-03-05 14:57:21 -08001082 if (current_method != nullptr && current_method->IsWithinQuickCode(it->pc)) {
1083 os << JniLongName(current_method) << "+" << (it->pc - current_method->GetQuickOatCodeOffset());
1084 } else {
1085 os << "???";
1086 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001087 }
Christopher Ferris943af7d2014-01-16 12:41:46 -08001088 if (it->func_offset != 0) {
1089 os << "+" << it->func_offset;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001090 }
Christopher Ferris943af7d2014-01-16 12:41:46 -08001091 os << StringPrintf(" [%p]", reinterpret_cast<void*>(it->pc));
1092 os << " (" << CleanMapName(it->map) << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001093 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001094}
1095
Elliott Hughes058a6de2012-05-24 19:13:02 -07001096#if defined(__APPLE__)
1097
1098// TODO: is there any way to get the kernel stack on Mac OS?
1099void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1100
1101#else
1102
Elliott Hughes46e251b2012-05-22 15:10:45 -07001103void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001104 if (tid == GetTid()) {
1105 // There's no point showing that we're reading our stack out of /proc!
1106 return;
1107 }
1108
Elliott Hughes46e251b2012-05-22 15:10:45 -07001109 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1110 std::string kernel_stack;
1111 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001112 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001113 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001114 }
1115
1116 std::vector<std::string> kernel_stack_frames;
1117 Split(kernel_stack, '\n', kernel_stack_frames);
1118 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1119 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1120 kernel_stack_frames.pop_back();
1121 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1122 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1123 const char* text = kernel_stack_frames[i].c_str();
1124 const char* close_bracket = strchr(text, ']');
1125 if (close_bracket != NULL) {
1126 text = close_bracket + 2;
1127 }
1128 os << prefix;
1129 if (include_count) {
1130 os << StringPrintf("#%02zd ", i);
1131 }
1132 os << text << "\n";
1133 }
1134}
1135
1136#endif
1137
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001138const char* GetAndroidRoot() {
1139 const char* android_root = getenv("ANDROID_ROOT");
1140 if (android_root == NULL) {
1141 if (OS::DirectoryExists("/system")) {
1142 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001143 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001144 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1145 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001146 }
1147 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001148 if (!OS::DirectoryExists(android_root)) {
1149 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001150 return "";
1151 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001152 return android_root;
1153}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001154
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001155const char* GetAndroidData() {
1156 const char* android_data = getenv("ANDROID_DATA");
1157 if (android_data == NULL) {
1158 if (OS::DirectoryExists("/data")) {
1159 android_data = "/data";
1160 } else {
1161 LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1162 return "";
1163 }
1164 }
1165 if (!OS::DirectoryExists(android_data)) {
1166 LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1167 return "";
1168 }
1169 return android_data;
1170}
1171
Brian Carlstrom7675e162013-06-10 16:18:04 -07001172std::string GetDalvikCacheOrDie(const char* android_data) {
1173 std::string dalvik_cache(StringPrintf("%s/dalvik-cache", android_data));
Brian Carlstroma9f19782011-10-13 00:14:47 -07001174
Brian Carlstrom7675e162013-06-10 16:18:04 -07001175 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1176 if (StartsWith(dalvik_cache, "/tmp/")) {
1177 int result = mkdir(dalvik_cache.c_str(), 0700);
Brian Carlstroma9f19782011-10-13 00:14:47 -07001178 if (result != 0) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001179 LOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001180 return "";
1181 }
1182 } else {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001183 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001184 return "";
1185 }
1186 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001187 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001188}
1189
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001190std::string GetDalvikCacheFilenameOrDie(const char* location) {
Brian Carlstrom7675e162013-06-10 16:18:04 -07001191 std::string dalvik_cache(GetDalvikCacheOrDie(GetAndroidData()));
Ian Rogerse6060102013-05-16 12:01:04 -07001192 if (location[0] != '/') {
1193 LOG(FATAL) << "Expected path in location to be absolute: "<< location;
1194 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001195 std::string cache_file(&location[1]); // skip leading slash
Brian Carlstrom19a08362013-10-16 14:37:22 -07001196 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001197 cache_file += "/";
1198 cache_file += DexFile::kClassesDex;
1199 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001200 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Brian Carlstrom7675e162013-06-10 16:18:04 -07001201 return dalvik_cache + "/" + cache_file;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001202}
1203
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001204bool IsZipMagic(uint32_t magic) {
1205 return (('P' == ((magic >> 0) & 0xff)) &&
1206 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001207}
1208
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001209bool IsDexMagic(uint32_t magic) {
1210 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001211}
1212
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001213bool IsOatMagic(uint32_t magic) {
1214 return (memcmp(reinterpret_cast<const byte*>(magic),
1215 OatHeader::kOatMagic,
1216 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001217}
1218
Brian Carlstrom6449c622014-02-10 23:48:36 -08001219bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1220 const std::string command_line(Join(arg_vector, ' '));
1221
1222 CHECK_GE(arg_vector.size(), 1U) << command_line;
1223
1224 // Convert the args to char pointers.
1225 const char* program = arg_vector[0].c_str();
1226 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001227 for (size_t i = 0; i < arg_vector.size(); ++i) {
1228 const std::string& arg = arg_vector[i];
1229 char* arg_str = const_cast<char*>(arg.c_str());
1230 CHECK(arg_str != nullptr) << i;
1231 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001232 }
1233 args.push_back(NULL);
1234
1235 // fork and exec
1236 pid_t pid = fork();
1237 if (pid == 0) {
1238 // no allocation allowed between fork and exec
1239
1240 // change process groups, so we don't get reaped by ProcessManager
1241 setpgid(0, 0);
1242
1243 execv(program, &args[0]);
1244
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001245 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1246 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001247 } else {
1248 if (pid == -1) {
1249 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1250 command_line.c_str(), strerror(errno));
1251 return false;
1252 }
1253
1254 // wait for subprocess to finish
1255 int status;
1256 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1257 if (got_pid != pid) {
1258 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1259 "wanted %d, got %d: %s",
1260 command_line.c_str(), pid, got_pid, strerror(errno));
1261 return false;
1262 }
1263 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1264 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1265 command_line.c_str());
1266 return false;
1267 }
1268 }
1269 return true;
1270}
1271
Elliott Hughes42ee1422011-09-06 12:33:32 -07001272} // namespace art