blob: fb6c1b3d3c327cca7a3d388902f8d5ff8a7d2e57 [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>
Elliott Hughes42ee1422011-09-06 12:33:32 -070025#include <unistd.h>
Ian Rogers700a4022014-05-19 16:49:03 -070026#include <memory>
Elliott Hughes42ee1422011-09-06 12:33:32 -070027
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_method-inl.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080030#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080031#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "dex_file-inl.h"
Andreas Gampe5073fed2015-08-10 11:40:25 -070033#include "dex_instruction.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"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010039#include "oat_quick_method_header.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 Hughes4ae722a2012-03-13 11:08:51 -070044#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070045#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070046#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070047#endif
48
Christopher Ferris6cff48f2014-01-26 21:36:13 -080049// For DumpNativeStack.
50#include <backtrace/Backtrace.h>
51#include <backtrace/BacktraceMap.h>
Elliott Hughes46e251b2012-05-22 15:10:45 -070052
Elliott Hughes058a6de2012-05-24 19:13:02 -070053#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080054#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080055#endif
56
Elliott Hughes11e45072011-08-16 17:40:46 -070057namespace art {
58
David Sehr1488ff82016-08-16 19:22:57 -070059namespace {
60#ifdef __APPLE__
61inline char** GetEnviron() {
62 // When Google Test is built as a framework on MacOS X, the environ variable
63 // is unavailable. Apple's documentation (man environ) recommends using
64 // _NSGetEnviron() instead.
65 return *_NSGetEnviron();
66}
67#else
68// Some POSIX platforms expect you to declare environ. extern "C" makes
69// it reside in the global namespace.
70extern "C" char** environ;
71inline char** GetEnviron() { return environ; }
72#endif
73} // namespace
74
Andreas Gampe8e1cb912015-01-08 20:11:09 -080075#if defined(__linux__)
76static constexpr bool kUseAddr2line = !kIsTargetBuild;
77#endif
78
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080079pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070080#if defined(__APPLE__)
81 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070082 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -070083 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070084#elif defined(__BIONIC__)
85 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080086#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080087 return syscall(__NR_gettid);
88#endif
89}
90
Elliott Hughes289be852012-06-12 13:57:20 -070091std::string GetThreadName(pid_t tid) {
92 std::string result;
93 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070094 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070095 } else {
96 result = "<unknown>";
97 }
98 return result;
99}
100
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700101void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -0700102#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -0700103 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -0700104 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -0700105
106 // Check whether stack_addr is the base or end of the stack.
107 // (On Mac OS 10.7, it's the end.)
108 int stack_variable;
109 if (stack_addr > &stack_variable) {
Ian Rogers13735952014-10-08 12:43:28 -0700110 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -0700111 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -0700112 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -0700113 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700114
115 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
116 pthread_attr_t attributes;
117 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
118 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
119 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700120#else
121 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700122 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700123 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700124 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700125 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700126
127#if defined(__GLIBC__)
128 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
129 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
130 // will be broken because we'll die long before we get close to 2GB.
131 bool is_main_thread = (::art::GetTid() == getpid());
132 if (is_main_thread) {
133 rlimit stack_limit;
134 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
135 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
136 }
137 if (stack_limit.rlim_cur == RLIM_INFINITY) {
138 size_t old_stack_size = *stack_size;
139
140 // Use the kernel default limit as our size, and adjust the base to match.
141 *stack_size = 8 * MB;
142 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
143
144 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
145 << " to " << PrettySize(*stack_size)
146 << " with base " << *stack_base;
147 }
148 }
149#endif
150
Elliott Hughese1884192012-04-23 12:38:15 -0700151#endif
152}
153
Elliott Hughesd92bec42011-09-02 17:04:36 -0700154bool ReadFileToString(const std::string& file_name, std::string* result) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800155 File file;
156 if (!file.Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700157 return false;
158 }
buzbeec143c552011-08-20 17:38:58 -0700159
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700160 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700161 while (true) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800162 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700163 if (n == -1) {
164 return false;
buzbeec143c552011-08-20 17:38:58 -0700165 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700166 if (n == 0) {
167 return true;
168 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700169 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700170 }
buzbeec143c552011-08-20 17:38:58 -0700171}
172
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800173bool PrintFileToLog(const std::string& file_name, LogSeverity level) {
174 File file;
175 if (!file.Open(file_name, O_RDONLY)) {
176 return false;
177 }
178
179 constexpr size_t kBufSize = 256; // Small buffer. Avoid stack overflow and stack size warnings.
180 char buf[kBufSize + 1]; // +1 for terminator.
181 size_t filled_to = 0;
182 while (true) {
183 DCHECK_LT(filled_to, kBufSize);
184 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[filled_to], kBufSize - filled_to));
185 if (n <= 0) {
186 // Print the rest of the buffer, if it exists.
187 if (filled_to > 0) {
188 buf[filled_to] = 0;
189 LOG(level) << buf;
190 }
191 return n == 0;
192 }
193 // Scan for '\n'.
194 size_t i = filled_to;
195 bool found_newline = false;
196 for (; i < filled_to + n; ++i) {
197 if (buf[i] == '\n') {
198 // Found a line break, that's something to print now.
199 buf[i] = 0;
200 LOG(level) << buf;
201 // Copy the rest to the front.
202 if (i + 1 < filled_to + n) {
203 memmove(&buf[0], &buf[i + 1], filled_to + n - i - 1);
204 filled_to = filled_to + n - i - 1;
205 } else {
206 filled_to = 0;
207 }
208 found_newline = true;
209 break;
210 }
211 }
212 if (found_newline) {
213 continue;
214 } else {
215 filled_to += n;
216 // Check if we must flush now.
217 if (filled_to == kBufSize) {
218 buf[kBufSize] = 0;
219 LOG(level) << buf;
220 filled_to = 0;
221 }
222 }
223 }
224}
225
Ian Rogersef7d42f2014-01-06 12:55:46 -0800226std::string PrettyDescriptor(mirror::String* java_descriptor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700227 if (java_descriptor == nullptr) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700228 return "null";
229 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700230 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700231}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700232
Ian Rogersef7d42f2014-01-06 12:55:46 -0800233std::string PrettyDescriptor(mirror::Class* klass) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700234 if (klass == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800235 return "null";
236 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700237 std::string temp;
238 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800239}
240
Ian Rogers1ff3c982014-08-12 02:30:58 -0700241std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700242 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700243 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700244 size_t dim = 0;
245 while (*c == '[') {
246 dim++;
247 c++;
248 }
249
250 // Reference or primitive?
251 if (*c == 'L') {
252 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700253 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700254 } else {
255 // "[[B" -> "byte[][]".
256 // To make life easier, we make primitives look like unqualified
257 // reference types.
258 switch (*c) {
259 case 'B': c = "byte;"; break;
260 case 'C': c = "char;"; break;
261 case 'D': c = "double;"; break;
262 case 'F': c = "float;"; break;
263 case 'I': c = "int;"; break;
264 case 'J': c = "long;"; break;
265 case 'S': c = "short;"; break;
266 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700267 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700268 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700269 }
270 }
271
272 // At this point, 'c' is a string of the form "fully/qualified/Type;"
273 // or "primitive;". Rewrite the type with '.' instead of '/':
274 std::string result;
275 const char* p = c;
276 while (*p != ';') {
277 char ch = *p++;
278 if (ch == '/') {
279 ch = '.';
280 }
281 result.push_back(ch);
282 }
283 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700284 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700285 result += "[]";
286 }
287 return result;
288}
289
Mathieu Chartierc7853442015-03-27 14:35:38 -0700290std::string PrettyField(ArtField* f, bool with_type) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700291 if (f == nullptr) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700292 return "null";
293 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700294 std::string result;
295 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700296 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700297 result += ' ';
298 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800299 std::string temp;
300 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700301 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700302 result += f->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 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700345 {
346 std::string argument_descriptor(signature, argument_length);
347 result += PrettyDescriptor(argument_descriptor.c_str());
348 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700349 if (signature[argument_length] != ')') {
350 result += ", ";
351 }
352 signature += argument_length;
353 }
354 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700355 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700356 result += ')';
357 return result;
358}
359
360std::string PrettyReturnType(const char* signature) {
361 const char* return_type = strchr(signature, ')');
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700362 CHECK(return_type != nullptr);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700363 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700364 return PrettyDescriptor(return_type);
365}
366
Mathieu Chartiere401d142015-04-22 13:56:20 -0700367std::string PrettyMethod(ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800368 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700369 return "null";
370 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700371 if (!m->IsRuntimeMethod()) {
372 m = m->GetInterfaceMethodIfProxy(Runtime::Current()->GetClassLinker()->GetImagePointerSize());
373 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700374 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700375 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700376 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800377 if (UNLIKELY(m->IsFastNative())) {
378 result += "!";
379 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700380 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700381 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700382 std::string sig_as_string(signature.ToString());
383 if (signature == Signature::NoSignature()) {
384 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700385 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700386 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
387 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700388 }
389 return result;
390}
391
Ian Rogers0571d352011-11-03 19:51:38 -0700392std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800393 if (method_idx >= dex_file.NumMethodIds()) {
394 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
395 }
Ian Rogers0571d352011-11-03 19:51:38 -0700396 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
397 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
398 result += '.';
399 result += dex_file.GetMethodName(method_id);
400 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700401 const Signature signature = dex_file.GetMethodSignature(method_id);
402 std::string sig_as_string(signature.ToString());
403 if (signature == Signature::NoSignature()) {
404 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700405 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700406 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
407 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700408 }
409 return result;
410}
411
Ian Rogersef7d42f2014-01-06 12:55:46 -0800412std::string PrettyTypeOf(mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700413 if (obj == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700414 return "null";
415 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700416 if (obj->GetClass() == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700417 return "(raw)";
418 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700419 std::string temp;
420 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700421 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700422 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700423 }
424 return result;
425}
426
Ian Rogersef7d42f2014-01-06 12:55:46 -0800427std::string PrettyClass(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700428 if (c == nullptr) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700429 return "null";
430 }
431 std::string result;
432 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800433 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700434 result += ">";
435 return result;
436}
437
Ian Rogersef7d42f2014-01-06 12:55:46 -0800438std::string PrettyClassAndClassLoader(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700439 if (c == nullptr) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700440 return "null";
441 }
442 std::string result;
443 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800444 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700445 result += ",";
446 result += PrettyTypeOf(c->GetClassLoader());
447 // TODO: add an identifying hash value for the loader
448 result += ">";
449 return result;
450}
451
Andreas Gampec0d82292014-09-23 10:38:30 -0700452std::string PrettyJavaAccessFlags(uint32_t access_flags) {
453 std::string result;
454 if ((access_flags & kAccPublic) != 0) {
455 result += "public ";
456 }
457 if ((access_flags & kAccProtected) != 0) {
458 result += "protected ";
459 }
460 if ((access_flags & kAccPrivate) != 0) {
461 result += "private ";
462 }
463 if ((access_flags & kAccFinal) != 0) {
464 result += "final ";
465 }
466 if ((access_flags & kAccStatic) != 0) {
467 result += "static ";
468 }
469 if ((access_flags & kAccTransient) != 0) {
470 result += "transient ";
471 }
472 if ((access_flags & kAccVolatile) != 0) {
473 result += "volatile ";
474 }
475 if ((access_flags & kAccSynchronized) != 0) {
476 result += "synchronized ";
477 }
478 return result;
479}
480
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800481std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700482 // The byte thresholds at which we display amounts. A byte count is displayed
483 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800484 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700485 0, // B up to...
486 3*1024, // KB up to...
487 2*1024*1024, // MB up to...
488 1024*1024*1024 // GB from here.
489 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800490 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700491 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800492 const char* negative_str = "";
493 if (byte_count < 0) {
494 negative_str = "-";
495 byte_count = -byte_count;
496 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700497 int i = arraysize(kUnitThresholds);
498 while (--i > 0) {
499 if (byte_count >= kUnitThresholds[i]) {
500 break;
501 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800502 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800503 return StringPrintf("%s%" PRId64 "%s",
504 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800505}
506
Ian Rogers576ca0c2014-06-06 15:58:22 -0700507std::string PrintableChar(uint16_t ch) {
508 std::string result;
509 result += '\'';
510 if (NeedsEscaping(ch)) {
511 StringAppendF(&result, "\\u%04x", ch);
512 } else {
513 result += ch;
514 }
515 result += '\'';
516 return result;
517}
518
Ian Rogers68b56852014-08-29 20:19:11 -0700519std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700520 std::string result;
521 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700522 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700523 size_t char_count = CountModifiedUtf8Chars(p);
524 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000525 uint32_t ch = GetUtf16FromUtf8(&p);
Elliott Hughes82914b62012-04-09 15:56:29 -0700526 if (ch == '\\') {
527 result += "\\\\";
528 } else if (ch == '\n') {
529 result += "\\n";
530 } else if (ch == '\r') {
531 result += "\\r";
532 } else if (ch == '\t') {
533 result += "\\t";
Elliott Hughes82914b62012-04-09 15:56:29 -0700534 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000535 const uint16_t leading = GetLeadingUtf16Char(ch);
536
537 if (NeedsEscaping(leading)) {
538 StringAppendF(&result, "\\u%04x", leading);
539 } else {
540 result += leading;
541 }
542
543 const uint32_t trailing = GetTrailingUtf16Char(ch);
544 if (trailing != 0) {
545 // All high surrogates will need escaping.
546 StringAppendF(&result, "\\u%04x", trailing);
547 }
Elliott Hughes82914b62012-04-09 15:56:29 -0700548 }
549 }
550 result += '"';
551 return result;
552}
553
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800554// 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 -0700555std::string MangleForJni(const std::string& s) {
556 std::string result;
557 size_t char_count = CountModifiedUtf8Chars(s.c_str());
558 const char* cp = &s[0];
559 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000560 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800561 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
562 result.push_back(ch);
563 } else if (ch == '.' || ch == '/') {
564 result += "_";
565 } else if (ch == '_') {
566 result += "_1";
567 } else if (ch == ';') {
568 result += "_2";
569 } else if (ch == '[') {
570 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700571 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000572 const uint16_t leading = GetLeadingUtf16Char(ch);
573 const uint32_t trailing = GetTrailingUtf16Char(ch);
574
575 StringAppendF(&result, "_0%04x", leading);
576 if (trailing != 0) {
577 StringAppendF(&result, "_0%04x", trailing);
578 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700579 }
580 }
581 return result;
582}
583
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700584std::string DotToDescriptor(const char* class_name) {
585 std::string descriptor(class_name);
586 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
587 if (descriptor.length() > 0 && descriptor[0] != '[') {
588 descriptor = "L" + descriptor + ";";
589 }
590 return descriptor;
591}
592
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800593std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800594 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700595 if (length > 1) {
596 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
597 // Descriptors have the leading 'L' and trailing ';' stripped.
598 std::string result(descriptor + 1, length - 2);
599 std::replace(result.begin(), result.end(), '/', '.');
600 return result;
601 } else {
602 // For arrays the 'L' and ';' remain intact.
603 std::string result(descriptor);
604 std::replace(result.begin(), result.end(), '/', '.');
605 return result;
606 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800607 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700608 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800609 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800610}
611
612std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800613 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800614 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
615 std::string result(descriptor + 1, length - 2);
616 return result;
617 }
618 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700619}
620
Mathieu Chartiere401d142015-04-22 13:56:20 -0700621std::string JniShortName(ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700622 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700623 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700624 CHECK_EQ(class_name[0], 'L') << class_name;
625 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700626 class_name.erase(0, 1);
627 class_name.erase(class_name.size() - 1, 1);
628
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700629 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700630
631 std::string short_name;
632 short_name += "Java_";
633 short_name += MangleForJni(class_name);
634 short_name += "_";
635 short_name += MangleForJni(method_name);
636 return short_name;
637}
638
Mathieu Chartiere401d142015-04-22 13:56:20 -0700639std::string JniLongName(ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700640 std::string long_name;
641 long_name += JniShortName(m);
642 long_name += "__";
643
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700644 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700645 signature.erase(0, 1);
646 signature.erase(signature.begin() + signature.find(')'), signature.end());
647
648 long_name += MangleForJni(signature);
649
650 return long_name;
651}
652
jeffhao10037c82012-01-23 15:06:23 -0800653// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700654uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700655 0x00000000, // 00..1f low control characters; nothing valid
656 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
657 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
658 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700659};
660
jeffhao10037c82012-01-23 15:06:23 -0800661// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
662bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700663 /*
664 * It's a multibyte encoded character. Decode it and analyze. We
665 * accept anything that isn't (a) an improperly encoded low value,
666 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
667 * control character, or (e) a high space, layout, or special
668 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
669 * U+fff0..U+ffff). This is all specified in the dex format
670 * document.
671 */
672
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000673 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000674 const uint16_t leading = GetLeadingUtf16Char(pair);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000675
Narayan Kamath8508e372015-05-06 14:55:43 +0100676 // We have a surrogate pair resulting from a valid 4 byte UTF sequence.
677 // No further checks are necessary because 4 byte sequences span code
678 // points [U+10000, U+1FFFFF], which are valid codepoints in a dex
679 // identifier. Furthermore, GetUtf16FromUtf8 guarantees that each of
680 // the surrogate halves are valid and well formed in this instance.
681 if (GetTrailingUtf16Char(pair) != 0) {
682 return true;
683 }
684
685
686 // We've encountered a one, two or three byte UTF-8 sequence. The
687 // three byte UTF-8 sequence could be one half of a surrogate pair.
688 switch (leading >> 8) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000689 case 0x00:
690 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
691 return (leading > 0x00a0);
692 case 0xd8:
693 case 0xd9:
694 case 0xda:
695 case 0xdb:
Narayan Kamath8508e372015-05-06 14:55:43 +0100696 {
697 // We found a three byte sequence encoding one half of a surrogate.
698 // Look for the other half.
699 const uint32_t pair2 = GetUtf16FromUtf8(pUtf8Ptr);
700 const uint16_t trailing = GetLeadingUtf16Char(pair2);
701
702 return (GetTrailingUtf16Char(pair2) == 0) && (0xdc00 <= trailing && trailing <= 0xdfff);
703 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000704 case 0xdc:
705 case 0xdd:
706 case 0xde:
707 case 0xdf:
708 // It's a trailing surrogate, which is not valid at this point.
709 return false;
710 case 0x20:
711 case 0xff:
712 // It's in the range that has spaces, controls, and specials.
713 switch (leading & 0xfff8) {
Narayan Kamath8508e372015-05-06 14:55:43 +0100714 case 0x2000:
715 case 0x2008:
716 case 0x2028:
717 case 0xfff0:
718 case 0xfff8:
719 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000720 }
Narayan Kamath8508e372015-05-06 14:55:43 +0100721 return true;
722 default:
723 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700724 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000725
Narayan Kamath8508e372015-05-06 14:55:43 +0100726 UNREACHABLE();
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700727}
728
729/* Return whether the pointed-at modified-UTF-8 encoded character is
730 * valid as part of a member name, updating the pointer to point past
731 * the consumed character. This will consume two encoded UTF-16 code
732 * points if the character is encoded as a surrogate pair. Also, if
733 * this function returns false, then the given pointer may only have
734 * been partially advanced.
735 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700736static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700737 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700738 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700739 // It's low-ascii, so check the table.
740 uint32_t wordIdx = c >> 5;
741 uint32_t bitIdx = c & 0x1f;
742 (*pUtf8Ptr)++;
743 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
744 }
745
746 // It's a multibyte encoded character. Call a non-inline function
747 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800748 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
749}
750
751bool IsValidMemberName(const char* s) {
752 bool angle_name = false;
753
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700754 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800755 case '\0':
756 // The empty string is not a valid name.
757 return false;
758 case '<':
759 angle_name = true;
760 s++;
761 break;
762 }
763
764 while (true) {
765 switch (*s) {
766 case '\0':
767 return !angle_name;
768 case '>':
769 return angle_name && s[1] == '\0';
770 }
771
772 if (!IsValidPartOfMemberNameUtf8(&s)) {
773 return false;
774 }
775 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700776}
777
Elliott Hughes906e6852011-10-28 14:52:10 -0700778enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700779template<ClassNameType kType, char kSeparator>
780static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700781 int arrayCount = 0;
782 while (*s == '[') {
783 arrayCount++;
784 s++;
785 }
786
787 if (arrayCount > 255) {
788 // Arrays may have no more than 255 dimensions.
789 return false;
790 }
791
Ian Rogers7b078e82014-09-10 14:44:24 -0700792 ClassNameType type = kType;
793 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700794 /*
795 * If we're looking at an array of some sort, then it doesn't
796 * matter if what is being asked for is a class name; the
797 * format looks the same as a type descriptor in that case, so
798 * treat it as such.
799 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700800 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700801 }
802
Elliott Hughes906e6852011-10-28 14:52:10 -0700803 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700804 /*
805 * We are looking for a descriptor. Either validate it as a
806 * single-character primitive type, or continue on to check the
807 * embedded class name (bracketed by "L" and ";").
808 */
809 switch (*(s++)) {
810 case 'B':
811 case 'C':
812 case 'D':
813 case 'F':
814 case 'I':
815 case 'J':
816 case 'S':
817 case 'Z':
818 // These are all single-character descriptors for primitive types.
819 return (*s == '\0');
820 case 'V':
821 // Non-array void is valid, but you can't have an array of void.
822 return (arrayCount == 0) && (*s == '\0');
823 case 'L':
824 // Class name: Break out and continue below.
825 break;
826 default:
827 // Oddball descriptor character.
828 return false;
829 }
830 }
831
832 /*
833 * We just consumed the 'L' that introduces a class name as part
834 * of a type descriptor, or we are looking for an unadorned class
835 * name.
836 */
837
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700838 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700839 for (;;) {
840 uint8_t c = (uint8_t) *s;
841 switch (c) {
842 case '\0':
843 /*
844 * Premature end for a type descriptor, but valid for
845 * a class name as long as we haven't encountered an
846 * empty component (including the degenerate case of
847 * the empty string "").
848 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700849 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700850 case ';':
851 /*
852 * Invalid character for a class name, but the
853 * legitimate end of a type descriptor. In the latter
854 * case, make sure that this is the end of the string
855 * and that it doesn't end with an empty component
856 * (including the degenerate case of "L;").
857 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700858 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700859 case '/':
860 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700861 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700862 // The wrong separator character.
863 return false;
864 }
865 if (sepOrFirst) {
866 // Separator at start or two separators in a row.
867 return false;
868 }
869 sepOrFirst = true;
870 s++;
871 break;
872 default:
jeffhao10037c82012-01-23 15:06:23 -0800873 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700874 return false;
875 }
876 sepOrFirst = false;
877 break;
878 }
879 }
880}
881
Elliott Hughes906e6852011-10-28 14:52:10 -0700882bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700883 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700884}
885
886bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700887 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700888}
889
890bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700891 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700892}
893
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700894void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700895 const char* p = s.data();
896 const char* end = p + s.size();
897 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800898 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700899 ++p;
900 } else {
901 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800902 while (++p != end && *p != separator) {
903 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700904 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700905 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700906 }
907 }
908}
909
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700910std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -0700911 std::string result;
912 unsigned int start_index = 0;
913 unsigned int end_index = s.size() - 1;
914
915 // Skip initial whitespace.
916 while (start_index < s.size()) {
917 if (!isspace(s[start_index])) {
918 break;
919 }
920 start_index++;
921 }
922
923 // Skip terminating whitespace.
924 while (end_index >= start_index) {
925 if (!isspace(s[end_index])) {
926 break;
927 }
928 end_index--;
929 }
930
931 // All spaces, no beef.
932 if (end_index < start_index) {
933 return "";
934 }
935 // Start_index is the first non-space, end_index is the last one.
936 return s.substr(start_index, end_index - start_index + 1);
937}
938
Elliott Hughes48436bb2012-02-07 15:23:28 -0800939template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700940std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800941 if (strings.empty()) {
942 return "";
943 }
944
945 std::string result(strings[0]);
946 for (size_t i = 1; i < strings.size(); ++i) {
947 result += separator;
948 result += strings[i];
949 }
950 return result;
951}
952
953// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700954template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
955template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -0800956
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800957bool StartsWith(const std::string& s, const char* prefix) {
958 return s.compare(0, strlen(prefix), prefix) == 0;
959}
960
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700961bool EndsWith(const std::string& s, const char* suffix) {
962 size_t suffix_length = strlen(suffix);
963 size_t string_length = s.size();
964 if (suffix_length > string_length) {
965 return false;
966 }
967 size_t offset = string_length - suffix_length;
968 return s.compare(offset, suffix_length, suffix) == 0;
969}
970
Elliott Hughes22869a92012-03-27 14:08:24 -0700971void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700972 int hasAt = 0;
973 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700974 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700975 while (*s) {
976 if (*s == '.') {
977 hasDot = 1;
978 } else if (*s == '@') {
979 hasAt = 1;
980 }
981 s++;
982 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700983 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700984 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700985 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700986 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700987 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700988 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800989#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700990 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800991 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700992 strncpy(buf, s, sizeof(buf)-1);
993 buf[sizeof(buf)-1] = '\0';
994 errno = pthread_setname_np(pthread_self(), buf);
995 if (errno != 0) {
996 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
997 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800998#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700999 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001000#endif
1001}
1002
Brian Carlstrom29212012013-09-12 22:18:30 -07001003void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1004 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001005 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -07001006 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001007 return;
1008 }
1009 // Skip the command, which may contain spaces.
1010 stats = stats.substr(stats.find(')') + 2);
1011 // Extract the three fields we care about.
1012 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001013 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -07001014 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001015 *utime = strtoull(fields[11].c_str(), nullptr, 10);
1016 *stime = strtoull(fields[12].c_str(), nullptr, 10);
1017 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001018}
1019
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001020std::string GetSchedulerGroupName(pid_t tid) {
1021 // /proc/<pid>/cgroup looks like this:
1022 // 2:devices:/
1023 // 1:cpuacct,cpu:/
1024 // We want the third field from the line whose second field contains the "cpu" token.
1025 std::string cgroup_file;
1026 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1027 return "";
1028 }
1029 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001030 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001031 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1032 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001033 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001034 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001035 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001036 for (size_t j = 0; j < cgroups.size(); ++j) {
1037 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001038 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001039 }
1040 }
1041 }
1042 return "";
1043}
1044
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001045#if defined(__linux__)
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001046
1047ALWAYS_INLINE
1048static inline void WritePrefix(std::ostream* os, const char* prefix, bool odd) {
1049 if (prefix != nullptr) {
1050 *os << prefix;
1051 }
1052 *os << " ";
1053 if (!odd) {
1054 *os << " ";
1055 }
1056}
1057
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001058static bool RunCommand(std::string cmd, std::ostream* os, const char* prefix) {
1059 FILE* stream = popen(cmd.c_str(), "r");
1060 if (stream) {
1061 if (os != nullptr) {
1062 bool odd_line = true; // We indent them differently.
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001063 bool wrote_prefix = false; // Have we already written a prefix?
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001064 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
1065 // alt stack, but just to be sure...
1066 char buffer[kMaxBuffer];
1067 while (!feof(stream)) {
1068 if (fgets(buffer, kMaxBuffer, stream) != nullptr) {
1069 // Split on newlines.
1070 char* tmp = buffer;
1071 for (;;) {
1072 char* new_line = strchr(tmp, '\n');
1073 if (new_line == nullptr) {
1074 // Print the rest.
1075 if (*tmp != 0) {
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001076 if (!wrote_prefix) {
1077 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001078 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001079 wrote_prefix = true;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001080 *os << tmp;
1081 }
1082 break;
1083 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001084 if (!wrote_prefix) {
1085 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001086 }
1087 char saved = *(new_line + 1);
1088 *(new_line + 1) = 0;
1089 *os << tmp;
1090 *(new_line + 1) = saved;
1091 tmp = new_line + 1;
1092 odd_line = !odd_line;
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001093 wrote_prefix = false;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001094 }
1095 }
1096 }
1097 }
1098 pclose(stream);
1099 return true;
1100 } else {
1101 return false;
1102 }
1103}
1104
1105static void Addr2line(const std::string& map_src, uintptr_t offset, std::ostream& os,
1106 const char* prefix) {
1107 std::string cmdline(StringPrintf("addr2line --functions --inlines --demangle -e %s %zx",
1108 map_src.c_str(), offset));
1109 RunCommand(cmdline.c_str(), &os, prefix);
1110}
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001111
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001112static bool PcIsWithinQuickCode(ArtMethod* method, uintptr_t pc) NO_THREAD_SAFETY_ANALYSIS {
1113 uintptr_t code = reinterpret_cast<uintptr_t>(EntryPointToCodePointer(
1114 method->GetEntryPointFromQuickCompiledCode()));
1115 if (code == 0) {
1116 return pc == 0;
1117 }
1118 uintptr_t code_size = reinterpret_cast<const OatQuickMethodHeader*>(code)[-1].code_size_;
1119 return code <= pc && pc <= (code + code_size);
1120}
Nicolas Geoffrayab60b682015-10-20 13:35:38 +01001121#endif
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001122
Christopher Ferris6cff48f2014-01-26 21:36:13 -08001123void DumpNativeStack(std::ostream& os, pid_t tid, BacktraceMap* existing_map, const char* prefix,
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001124 ArtMethod* current_method, void* ucontext_ptr) {
Ian Rogers83597d02014-11-20 10:29:00 -08001125#if __linux__
Andreas Gamped7576322014-10-24 22:13:45 -07001126 // b/18119146
Evgenii Stepanov1e133742015-05-20 12:30:59 -07001127 if (RUNNING_ON_MEMORY_TOOL != 0) {
Andreas Gamped7576322014-10-24 22:13:45 -07001128 return;
1129 }
1130
Christopher Ferris6cff48f2014-01-26 21:36:13 -08001131 BacktraceMap* map = existing_map;
1132 std::unique_ptr<BacktraceMap> tmp_map;
1133 if (map == nullptr) {
tony.ys_liu59a8c0b2016-01-20 18:05:31 +08001134 tmp_map.reset(BacktraceMap::Create(getpid()));
Christopher Ferris6cff48f2014-01-26 21:36:13 -08001135 map = tmp_map.get();
1136 }
1137 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid, map));
Andreas Gampe628a61a2015-01-07 22:08:35 -08001138 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
Christopher Ferrisfa16a6d2016-03-09 16:03:00 -08001139 os << prefix << "(backtrace::Unwind failed for thread " << tid
1140 << ": " << backtrace->GetErrorString(backtrace->GetError()) << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001141 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001142 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001143 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001144 return;
1145 }
1146
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001147 // Check whether we have and should use addr2line.
1148 bool use_addr2line;
1149 if (kUseAddr2line) {
1150 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
1151 // and print to stderr.
Andreas Gampe941c5512015-01-15 10:38:19 -08001152 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h", nullptr, nullptr);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001153 } else {
1154 use_addr2line = false;
1155 }
1156
Christopher Ferris943af7d2014-01-16 12:41:46 -08001157 for (Backtrace::const_iterator it = backtrace->begin();
1158 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001159 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001160 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1161 // In order for parsing tools to continue to function, the stack dump
1162 // format must at least adhere to this format:
1163 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1164 // The parsers require a single space before and after pc, and two spaces
1165 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1166 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1167 os << prefix << StringPrintf("#%02zu pc ", it->num);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001168 bool try_addr2line = false;
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001169 if (!BacktraceMap::IsValid(it->map)) {
Andreas Gampedd671252015-07-23 14:37:18 -07001170 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIxPTR " ???"
1171 : "%08" PRIxPTR " ???",
1172 it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001173 } else {
Andreas Gampedd671252015-07-23 14:37:18 -07001174 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIxPTR " "
1175 : "%08" PRIxPTR " ",
1176 BacktraceMap::GetRelativePc(it->map, it->pc));
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001177 os << it->map.name;
Andreas Gampe3ef69b42015-01-26 10:38:34 -08001178 os << " (";
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001179 if (!it->func_name.empty()) {
1180 os << it->func_name;
1181 if (it->func_offset != 0) {
1182 os << "+" << it->func_offset;
1183 }
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001184 try_addr2line = true;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001185 } else if (current_method != nullptr &&
1186 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
1187 PcIsWithinQuickCode(current_method, it->pc)) {
1188 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
Brian Carlstrom474cc792014-03-07 14:18:15 -08001189 os << JniLongName(current_method) << "+"
1190 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001191 } else {
1192 os << "???";
1193 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001194 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001195 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001196 os << "\n";
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001197 if (try_addr2line && use_addr2line) {
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001198 Addr2line(it->map.name, it->pc - it->map.start, os, prefix);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001199 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001200 }
Nicolas Geoffraye6ac4fd2014-11-04 13:03:29 +00001201#else
Christopher Ferris6cff48f2014-01-26 21:36:13 -08001202 UNUSED(os, tid, existing_map, prefix, current_method, ucontext_ptr);
Ian Rogersc5f17732014-06-05 20:48:42 -07001203#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001204}
1205
Elliott Hughes058a6de2012-05-24 19:13:02 -07001206#if defined(__APPLE__)
1207
1208// TODO: is there any way to get the kernel stack on Mac OS?
1209void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1210
1211#else
1212
Elliott Hughes46e251b2012-05-22 15:10:45 -07001213void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001214 if (tid == GetTid()) {
1215 // There's no point showing that we're reading our stack out of /proc!
1216 return;
1217 }
1218
Elliott Hughes46e251b2012-05-22 15:10:45 -07001219 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1220 std::string kernel_stack;
1221 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001222 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001223 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001224 }
1225
1226 std::vector<std::string> kernel_stack_frames;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001227 Split(kernel_stack, '\n', &kernel_stack_frames);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001228 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1229 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1230 kernel_stack_frames.pop_back();
1231 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001232 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1233 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001234 const char* text = kernel_stack_frames[i].c_str();
1235 const char* close_bracket = strchr(text, ']');
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001236 if (close_bracket != nullptr) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001237 text = close_bracket + 2;
1238 }
1239 os << prefix;
1240 if (include_count) {
1241 os << StringPrintf("#%02zd ", i);
1242 }
1243 os << text << "\n";
1244 }
1245}
1246
1247#endif
1248
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001249const char* GetAndroidRoot() {
1250 const char* android_root = getenv("ANDROID_ROOT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001251 if (android_root == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001252 if (OS::DirectoryExists("/system")) {
1253 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001254 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001255 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1256 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001257 }
1258 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001259 if (!OS::DirectoryExists(android_root)) {
1260 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001261 return "";
1262 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001263 return android_root;
1264}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001265
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001266const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001267 std::string error_msg;
1268 const char* dir = GetAndroidDataSafe(&error_msg);
1269 if (dir != nullptr) {
1270 return dir;
1271 } else {
1272 LOG(FATAL) << error_msg;
1273 return "";
1274 }
1275}
1276
1277const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001278 const char* android_data = getenv("ANDROID_DATA");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001279 if (android_data == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001280 if (OS::DirectoryExists("/data")) {
1281 android_data = "/data";
1282 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001283 *error_msg = "ANDROID_DATA not set and /data does not exist";
1284 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001285 }
1286 }
1287 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001288 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1289 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001290 }
1291 return android_data;
1292}
1293
Alex Lighta59dd802014-07-02 16:28:08 -07001294void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001295 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001296 CHECK(subdir != nullptr);
1297 std::string error_msg;
1298 const char* android_data = GetAndroidDataSafe(&error_msg);
1299 if (android_data == nullptr) {
1300 *have_android_data = false;
1301 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001302 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001303 return;
1304 } else {
1305 *have_android_data = true;
1306 }
1307 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1308 *dalvik_cache = dalvik_cache_root + subdir;
1309 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001310 *is_global_cache = strcmp(android_data, "/data") == 0;
1311 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001312 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1313 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1314 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1315 }
1316}
1317
Andreas Gampe40da2862015-02-27 12:49:04 -08001318static std::string GetDalvikCacheImpl(const char* subdir,
1319 const bool create_if_absent,
1320 const bool abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001321 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001322 const char* android_data = GetAndroidData();
1323 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001324 const std::string dalvik_cache = dalvik_cache_root + subdir;
Andreas Gampe40da2862015-02-27 12:49:04 -08001325 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1326 if (!create_if_absent) {
1327 // TODO: Check callers. Traditional behavior is to not to abort, even when abort_on_error.
1328 return "";
1329 }
1330
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001331 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
Andreas Gampe40da2862015-02-27 12:49:04 -08001332 if (strcmp(android_data, "/data") == 0) {
1333 if (abort_on_error) {
1334 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache
1335 << ", cannot create /data dalvik-cache.";
1336 UNREACHABLE();
Narayan Kamath11d9f062014-04-23 20:24:57 +01001337 }
Andreas Gampe40da2862015-02-27 12:49:04 -08001338 return "";
1339 }
1340
1341 int result = mkdir(dalvik_cache_root.c_str(), 0700);
1342 if (result != 0 && errno != EEXIST) {
1343 if (abort_on_error) {
1344 PLOG(FATAL) << "Failed to create dalvik-cache root directory " << dalvik_cache_root;
1345 UNREACHABLE();
1346 }
1347 return "";
1348 }
1349
1350 result = mkdir(dalvik_cache.c_str(), 0700);
1351 if (result != 0) {
1352 if (abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001353 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Andreas Gampe40da2862015-02-27 12:49:04 -08001354 UNREACHABLE();
Brian Carlstroma9f19782011-10-13 00:14:47 -07001355 }
Brian Carlstroma9f19782011-10-13 00:14:47 -07001356 return "";
1357 }
1358 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001359 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001360}
1361
Andreas Gampe40da2862015-02-27 12:49:04 -08001362std::string GetDalvikCache(const char* subdir, const bool create_if_absent) {
1363 return GetDalvikCacheImpl(subdir, create_if_absent, false);
1364}
1365
1366std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1367 return GetDalvikCacheImpl(subdir, create_if_absent, true);
1368}
1369
Alex Lighta59dd802014-07-02 16:28:08 -07001370bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1371 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001372 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001373 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1374 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001375 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001376 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001377 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001378 cache_file += "/";
1379 cache_file += DexFile::kClassesDex;
1380 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001381 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001382 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1383 return true;
1384}
1385
1386std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1387 std::string ret;
1388 std::string error_msg;
1389 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1390 LOG(FATAL) << error_msg;
1391 }
1392 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001393}
1394
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001395static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001396 // in = /foo/bar/baz
1397 // out = /foo/bar/<isa>/baz
1398 size_t pos = filename->rfind('/');
1399 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1400 filename->insert(pos, "/", 1);
1401 filename->insert(pos + 1, GetInstructionSetString(isa));
1402}
1403
1404std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1405 // location = /system/framework/boot.art
1406 // filename = /system/framework/<isa>/boot.art
1407 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001408 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001409 return filename;
1410}
1411
David Sehr1488ff82016-08-16 19:22:57 -07001412const EnvSnapshot* TakeEnvSnapshot() {
1413 EnvSnapshot* snapshot = new EnvSnapshot();
1414 char** env = GetEnviron();
1415 for (size_t i = 0; env[i] != nullptr; ++i) {
1416 snapshot->name_value_pairs_.emplace_back(new std::string(env[i]));
1417 }
1418 return snapshot;
1419}
1420
Calin Juravle024160852016-02-23 12:00:03 +00001421int ExecAndReturnCode(std::vector<std::string>& arg_vector, std::string* error_msg) {
Brian Carlstrom6449c622014-02-10 23:48:36 -08001422 const std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom6449c622014-02-10 23:48:36 -08001423 CHECK_GE(arg_vector.size(), 1U) << command_line;
1424
1425 // Convert the args to char pointers.
1426 const char* program = arg_vector[0].c_str();
1427 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001428 for (size_t i = 0; i < arg_vector.size(); ++i) {
1429 const std::string& arg = arg_vector[i];
1430 char* arg_str = const_cast<char*>(arg.c_str());
1431 CHECK(arg_str != nullptr) << i;
1432 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001433 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001434 args.push_back(nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001435
1436 // fork and exec
1437 pid_t pid = fork();
1438 if (pid == 0) {
1439 // no allocation allowed between fork and exec
1440
1441 // change process groups, so we don't get reaped by ProcessManager
1442 setpgid(0, 0);
1443
David Sehr1488ff82016-08-16 19:22:57 -07001444 // The child inherits the environment unless the caller overrides it.
1445 if (Runtime::Current() == nullptr || Runtime::Current()->GetEnvSnapshot() == nullptr) {
1446 execv(program, &args[0]);
1447 } else {
1448 const EnvSnapshot* saved_snapshot = Runtime::Current()->GetEnvSnapshot();
1449 // Allocation between fork and exec is not well-behaved. Use a variable-length array instead.
1450 char* envp[saved_snapshot->name_value_pairs_.size() + 1];
1451 for (size_t i = 0; i < saved_snapshot->name_value_pairs_.size(); ++i) {
1452 envp[i] = const_cast<char*>(saved_snapshot->name_value_pairs_[i]->c_str());
1453 }
1454 envp[saved_snapshot->name_value_pairs_.size()] = nullptr;
1455 execve(program, &args[0], envp);
1456 }
1457 PLOG(ERROR) << "Failed to execve(" << command_line << ")";
Tobias Lindskogae35c372015-11-04 19:41:21 +01001458 // _exit to avoid atexit handlers in child.
1459 _exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001460 } else {
1461 if (pid == -1) {
1462 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1463 command_line.c_str(), strerror(errno));
Calin Juravle024160852016-02-23 12:00:03 +00001464 return -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001465 }
1466
1467 // wait for subprocess to finish
Calin Juravle024160852016-02-23 12:00:03 +00001468 int status = -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001469 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1470 if (got_pid != pid) {
1471 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1472 "wanted %d, got %d: %s",
1473 command_line.c_str(), pid, got_pid, strerror(errno));
Calin Juravle024160852016-02-23 12:00:03 +00001474 return -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001475 }
Calin Juravle024160852016-02-23 12:00:03 +00001476 if (WIFEXITED(status)) {
1477 return WEXITSTATUS(status);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001478 }
Calin Juravle024160852016-02-23 12:00:03 +00001479 return -1;
1480 }
1481}
1482
1483bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1484 int status = ExecAndReturnCode(arg_vector, error_msg);
1485 if (status != 0) {
1486 const std::string command_line(Join(arg_vector, ' '));
1487 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1488 command_line.c_str());
1489 return false;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001490 }
1491 return true;
1492}
1493
Calin Juravle5e2b9712015-12-18 14:10:00 +02001494bool FileExists(const std::string& filename) {
1495 struct stat buffer;
1496 return stat(filename.c_str(), &buffer) == 0;
1497}
1498
Calin Juravlec15e5662016-03-17 17:07:52 +00001499bool FileExistsAndNotEmpty(const std::string& filename) {
1500 struct stat buffer;
1501 if (stat(filename.c_str(), &buffer) != 0) {
1502 return false;
1503 }
1504 return buffer.st_size > 0;
1505}
1506
Mathieu Chartier76433272014-09-26 14:32:37 -07001507std::string PrettyDescriptor(Primitive::Type type) {
1508 return PrettyDescriptor(Primitive::Descriptor(type));
1509}
1510
Andreas Gampe5073fed2015-08-10 11:40:25 -07001511static void DumpMethodCFGImpl(const DexFile* dex_file,
1512 uint32_t dex_method_idx,
1513 const DexFile::CodeItem* code_item,
1514 std::ostream& os) {
1515 os << "digraph {\n";
1516 os << " # /* " << PrettyMethod(dex_method_idx, *dex_file, true) << " */\n";
1517
1518 std::set<uint32_t> dex_pc_is_branch_target;
1519 {
1520 // Go and populate.
1521 const Instruction* inst = Instruction::At(code_item->insns_);
1522 for (uint32_t dex_pc = 0;
1523 dex_pc < code_item->insns_size_in_code_units_;
1524 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1525 if (inst->IsBranch()) {
1526 dex_pc_is_branch_target.insert(dex_pc + inst->GetTargetOffset());
1527 } else if (inst->IsSwitch()) {
1528 const uint16_t* insns = code_item->insns_ + dex_pc;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001529 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001530 const uint16_t* switch_insns = insns + switch_offset;
1531 uint32_t switch_count = switch_insns[1];
1532 int32_t targets_offset;
1533 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1534 /* 0=sig, 1=count, 2/3=firstKey */
1535 targets_offset = 4;
1536 } else {
1537 /* 0=sig, 1=count, 2..count*2 = keys */
1538 targets_offset = 2 + 2 * switch_count;
1539 }
1540 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001541 int32_t offset =
1542 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1543 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001544 dex_pc_is_branch_target.insert(dex_pc + offset);
1545 }
1546 }
1547 }
1548 }
1549
1550 // Create nodes for "basic blocks."
1551 std::map<uint32_t, uint32_t> dex_pc_to_node_id; // This only has entries for block starts.
1552 std::map<uint32_t, uint32_t> dex_pc_to_incl_id; // This has entries for all dex pcs.
1553
1554 {
1555 const Instruction* inst = Instruction::At(code_item->insns_);
1556 bool first_in_block = true;
1557 bool force_new_block = false;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001558 for (uint32_t dex_pc = 0;
1559 dex_pc < code_item->insns_size_in_code_units_;
1560 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001561 if (dex_pc == 0 ||
1562 (dex_pc_is_branch_target.find(dex_pc) != dex_pc_is_branch_target.end()) ||
1563 force_new_block) {
1564 uint32_t id = dex_pc_to_node_id.size();
1565 if (id > 0) {
1566 // End last node.
1567 os << "}\"];\n";
1568 }
1569 // Start next node.
1570 os << " node" << id << " [shape=record,label=\"{";
1571 dex_pc_to_node_id.insert(std::make_pair(dex_pc, id));
1572 first_in_block = true;
1573 force_new_block = false;
1574 }
1575
1576 // Register instruction.
1577 dex_pc_to_incl_id.insert(std::make_pair(dex_pc, dex_pc_to_node_id.size() - 1));
1578
1579 // Print instruction.
1580 if (!first_in_block) {
1581 os << " | ";
1582 } else {
1583 first_in_block = false;
1584 }
1585
1586 // Dump the instruction. Need to escape '"', '<', '>', '{' and '}'.
1587 os << "<" << "p" << dex_pc << ">";
1588 os << " 0x" << std::hex << dex_pc << std::dec << ": ";
1589 std::string inst_str = inst->DumpString(dex_file);
1590 size_t cur_start = 0; // It's OK to start at zero, instruction dumps don't start with chars
Andreas Gampe53de99c2015-08-17 13:43:55 -07001591 // we need to escape.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001592 while (cur_start != std::string::npos) {
1593 size_t next_escape = inst_str.find_first_of("\"{}<>", cur_start + 1);
1594 if (next_escape == std::string::npos) {
1595 os << inst_str.substr(cur_start, inst_str.size() - cur_start);
1596 break;
1597 } else {
1598 os << inst_str.substr(cur_start, next_escape - cur_start);
1599 // Escape all necessary characters.
1600 while (next_escape < inst_str.size()) {
1601 char c = inst_str.at(next_escape);
1602 if (c == '"' || c == '{' || c == '}' || c == '<' || c == '>') {
1603 os << '\\' << c;
1604 } else {
1605 break;
1606 }
1607 next_escape++;
1608 }
1609 if (next_escape >= inst_str.size()) {
1610 next_escape = std::string::npos;
1611 }
1612 cur_start = next_escape;
1613 }
1614 }
1615
1616 // Force a new block for some fall-throughs and some instructions that terminate the "local"
1617 // control flow.
1618 force_new_block = inst->IsSwitch() || inst->IsBasicBlockEnd();
1619 }
1620 // Close last node.
1621 if (dex_pc_to_node_id.size() > 0) {
1622 os << "}\"];\n";
1623 }
1624 }
1625
1626 // Create edges between them.
1627 {
1628 std::ostringstream regular_edges;
1629 std::ostringstream taken_edges;
1630 std::ostringstream exception_edges;
1631
1632 // Common set of exception edges.
1633 std::set<uint32_t> exception_targets;
1634
1635 // These blocks (given by the first dex pc) need exception per dex-pc handling in a second
1636 // pass. In the first pass we try and see whether we can use a common set of edges.
1637 std::set<uint32_t> blocks_with_detailed_exceptions;
1638
1639 {
1640 uint32_t last_node_id = std::numeric_limits<uint32_t>::max();
1641 uint32_t old_dex_pc = 0;
1642 uint32_t block_start_dex_pc = std::numeric_limits<uint32_t>::max();
1643 const Instruction* inst = Instruction::At(code_item->insns_);
1644 for (uint32_t dex_pc = 0;
1645 dex_pc < code_item->insns_size_in_code_units_;
1646 old_dex_pc = dex_pc, dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1647 {
1648 auto it = dex_pc_to_node_id.find(dex_pc);
1649 if (it != dex_pc_to_node_id.end()) {
1650 if (!exception_targets.empty()) {
1651 // It seems the last block had common exception handlers. Add the exception edges now.
1652 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1653 for (uint32_t handler_pc : exception_targets) {
1654 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1655 if (node_id_it != dex_pc_to_incl_id.end()) {
1656 exception_edges << " node" << node_id
1657 << " -> node" << node_id_it->second << ":p" << handler_pc
1658 << ";\n";
1659 }
1660 }
1661 exception_targets.clear();
1662 }
1663
1664 block_start_dex_pc = dex_pc;
1665
1666 // Seems to be a fall-through, connect to last_node_id. May be spurious edges for things
1667 // like switch data.
1668 uint32_t old_last = last_node_id;
1669 last_node_id = it->second;
1670 if (old_last != std::numeric_limits<uint32_t>::max()) {
1671 regular_edges << " node" << old_last << ":p" << old_dex_pc
1672 << " -> node" << last_node_id << ":p" << dex_pc
1673 << ";\n";
1674 }
1675 }
1676
1677 // Look at the exceptions of the first entry.
1678 CatchHandlerIterator catch_it(*code_item, dex_pc);
1679 for (; catch_it.HasNext(); catch_it.Next()) {
1680 exception_targets.insert(catch_it.GetHandlerAddress());
1681 }
1682 }
1683
1684 // Handle instruction.
1685
1686 // Branch: something with at most two targets.
1687 if (inst->IsBranch()) {
1688 const int32_t offset = inst->GetTargetOffset();
1689 const bool conditional = !inst->IsUnconditional();
1690
1691 auto target_it = dex_pc_to_node_id.find(dex_pc + offset);
1692 if (target_it != dex_pc_to_node_id.end()) {
1693 taken_edges << " node" << last_node_id << ":p" << dex_pc
1694 << " -> node" << target_it->second << ":p" << (dex_pc + offset)
1695 << ";\n";
1696 }
1697 if (!conditional) {
1698 // No fall-through.
1699 last_node_id = std::numeric_limits<uint32_t>::max();
1700 }
1701 } else if (inst->IsSwitch()) {
1702 // TODO: Iterate through all switch targets.
1703 const uint16_t* insns = code_item->insns_ + dex_pc;
1704 /* make sure the start of the switch is in range */
Andreas Gampe53de99c2015-08-17 13:43:55 -07001705 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001706 /* offset to switch table is a relative branch-style offset */
1707 const uint16_t* switch_insns = insns + switch_offset;
1708 uint32_t switch_count = switch_insns[1];
1709 int32_t targets_offset;
1710 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1711 /* 0=sig, 1=count, 2/3=firstKey */
1712 targets_offset = 4;
1713 } else {
1714 /* 0=sig, 1=count, 2..count*2 = keys */
1715 targets_offset = 2 + 2 * switch_count;
1716 }
1717 /* make sure the end of the switch is in range */
1718 /* verify each switch target */
1719 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001720 int32_t offset =
1721 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1722 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001723 int32_t abs_offset = dex_pc + offset;
1724 auto target_it = dex_pc_to_node_id.find(abs_offset);
1725 if (target_it != dex_pc_to_node_id.end()) {
1726 // TODO: value label.
1727 taken_edges << " node" << last_node_id << ":p" << dex_pc
1728 << " -> node" << target_it->second << ":p" << (abs_offset)
1729 << ";\n";
1730 }
1731 }
1732 }
1733
1734 // Exception edges. If this is not the first instruction in the block
1735 if (block_start_dex_pc != dex_pc) {
1736 std::set<uint32_t> current_handler_pcs;
1737 CatchHandlerIterator catch_it(*code_item, dex_pc);
1738 for (; catch_it.HasNext(); catch_it.Next()) {
1739 current_handler_pcs.insert(catch_it.GetHandlerAddress());
1740 }
1741 if (current_handler_pcs != exception_targets) {
1742 exception_targets.clear(); // Clear so we don't do something at the end.
1743 blocks_with_detailed_exceptions.insert(block_start_dex_pc);
1744 }
1745 }
1746
1747 if (inst->IsReturn() ||
1748 (inst->Opcode() == Instruction::THROW) ||
1749 (inst->IsBranch() && inst->IsUnconditional())) {
1750 // No fall-through.
1751 last_node_id = std::numeric_limits<uint32_t>::max();
1752 }
1753 }
1754 // Finish up the last block, if it had common exceptions.
1755 if (!exception_targets.empty()) {
1756 // It seems the last block had common exception handlers. Add the exception edges now.
1757 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1758 for (uint32_t handler_pc : exception_targets) {
1759 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1760 if (node_id_it != dex_pc_to_incl_id.end()) {
1761 exception_edges << " node" << node_id
1762 << " -> node" << node_id_it->second << ":p" << handler_pc
1763 << ";\n";
1764 }
1765 }
1766 exception_targets.clear();
1767 }
1768 }
1769
1770 // Second pass for detailed exception blocks.
1771 // TODO
1772 // Exception edges. If this is not the first instruction in the block
1773 for (uint32_t dex_pc : blocks_with_detailed_exceptions) {
1774 const Instruction* inst = Instruction::At(&code_item->insns_[dex_pc]);
1775 uint32_t this_node_id = dex_pc_to_incl_id.find(dex_pc)->second;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001776 while (true) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001777 CatchHandlerIterator catch_it(*code_item, dex_pc);
1778 if (catch_it.HasNext()) {
1779 std::set<uint32_t> handled_targets;
1780 for (; catch_it.HasNext(); catch_it.Next()) {
1781 uint32_t handler_pc = catch_it.GetHandlerAddress();
1782 auto it = handled_targets.find(handler_pc);
1783 if (it == handled_targets.end()) {
1784 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1785 if (node_id_it != dex_pc_to_incl_id.end()) {
1786 exception_edges << " node" << this_node_id << ":p" << dex_pc
1787 << " -> node" << node_id_it->second << ":p" << handler_pc
1788 << ";\n";
1789 }
1790
1791 // Mark as done.
1792 handled_targets.insert(handler_pc);
1793 }
1794 }
1795 }
1796 if (inst->IsBasicBlockEnd()) {
1797 break;
1798 }
1799
Andreas Gampe53de99c2015-08-17 13:43:55 -07001800 // Loop update. Have a break-out if the next instruction is a branch target and thus in
1801 // another block.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001802 dex_pc += inst->SizeInCodeUnits();
1803 if (dex_pc >= code_item->insns_size_in_code_units_) {
1804 break;
1805 }
1806 if (dex_pc_to_node_id.find(dex_pc) != dex_pc_to_node_id.end()) {
1807 break;
1808 }
1809 inst = inst->Next();
1810 }
1811 }
1812
1813 // Write out the sub-graphs to make edges styled.
1814 os << "\n";
1815 os << " subgraph regular_edges {\n";
1816 os << " edge [color=\"#000000\",weight=.3,len=3];\n\n";
1817 os << " " << regular_edges.str() << "\n";
1818 os << " }\n\n";
1819
1820 os << " subgraph taken_edges {\n";
1821 os << " edge [color=\"#00FF00\",weight=.3,len=3];\n\n";
1822 os << " " << taken_edges.str() << "\n";
1823 os << " }\n\n";
1824
1825 os << " subgraph exception_edges {\n";
1826 os << " edge [color=\"#FF0000\",weight=.3,len=3];\n\n";
1827 os << " " << exception_edges.str() << "\n";
1828 os << " }\n\n";
1829 }
1830
1831 os << "}\n";
1832}
1833
1834void DumpMethodCFG(ArtMethod* method, std::ostream& os) {
1835 const DexFile* dex_file = method->GetDexFile();
1836 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1837
1838 DumpMethodCFGImpl(dex_file, method->GetDexMethodIndex(), code_item, os);
1839}
1840
1841void DumpMethodCFG(const DexFile* dex_file, uint32_t dex_method_idx, std::ostream& os) {
1842 // This is painful, we need to find the code item. That means finding the class, and then
1843 // iterating the table.
1844 if (dex_method_idx >= dex_file->NumMethodIds()) {
1845 os << "Could not find method-idx.";
1846 return;
1847 }
1848 const DexFile::MethodId& method_id = dex_file->GetMethodId(dex_method_idx);
1849
1850 const DexFile::ClassDef* class_def = dex_file->FindClassDef(method_id.class_idx_);
1851 if (class_def == nullptr) {
1852 os << "Could not find class-def.";
1853 return;
1854 }
1855
1856 const uint8_t* class_data = dex_file->GetClassData(*class_def);
1857 if (class_data == nullptr) {
1858 os << "No class data.";
1859 return;
1860 }
1861
1862 ClassDataItemIterator it(*dex_file, class_data);
1863 // Skip fields
1864 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
1865 it.Next();
1866 }
1867
1868 // Find method, and dump it.
1869 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
1870 uint32_t method_idx = it.GetMemberIndex();
1871 if (method_idx == dex_method_idx) {
1872 DumpMethodCFGImpl(dex_file, dex_method_idx, it.GetMethodCodeItem(), os);
1873 return;
1874 }
1875 it.Next();
1876 }
1877
1878 // Otherwise complain.
1879 os << "Something went wrong, didn't find the method in the class data.";
1880}
1881
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001882static void ParseStringAfterChar(const std::string& s,
1883 char c,
1884 std::string* parsed_value,
1885 UsageFn Usage) {
1886 std::string::size_type colon = s.find(c);
1887 if (colon == std::string::npos) {
1888 Usage("Missing char %c in option %s\n", c, s.c_str());
1889 }
1890 // Add one to remove the char we were trimming until.
1891 *parsed_value = s.substr(colon + 1);
1892}
1893
1894void ParseDouble(const std::string& option,
1895 char after_char,
1896 double min,
1897 double max,
1898 double* parsed_value,
1899 UsageFn Usage) {
1900 std::string substring;
1901 ParseStringAfterChar(option, after_char, &substring, Usage);
1902 bool sane_val = true;
1903 double value;
1904 if ((false)) {
1905 // TODO: this doesn't seem to work on the emulator. b/15114595
1906 std::stringstream iss(substring);
1907 iss >> value;
1908 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
1909 sane_val = iss.eof() && (value >= min) && (value <= max);
1910 } else {
1911 char* end = nullptr;
1912 value = strtod(substring.c_str(), &end);
1913 sane_val = *end == '\0' && value >= min && value <= max;
1914 }
1915 if (!sane_val) {
1916 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
1917 }
1918 *parsed_value = value;
1919}
1920
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001921int64_t GetFileSizeBytes(const std::string& filename) {
1922 struct stat stat_buf;
1923 int rc = stat(filename.c_str(), &stat_buf);
1924 return rc == 0 ? stat_buf.st_size : -1;
1925}
1926
Mathieu Chartier4d87df62016-01-07 15:14:19 -08001927void SleepForever() {
1928 while (true) {
1929 usleep(1000000);
1930 }
1931}
1932
Elliott Hughes42ee1422011-09-06 12:33:32 -07001933} // namespace art