blob: 62af38021950de237dc062dbc3996bb948da1ea7 [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 Ferris7b5f0cf2013-11-01 15:18:45 -070049#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070050
Elliott Hughes058a6de2012-05-24 19:13:02 -070051#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080052#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080053#endif
54
Elliott Hughes11e45072011-08-16 17:40:46 -070055namespace art {
56
Andreas Gampe8e1cb912015-01-08 20:11:09 -080057#if defined(__linux__)
58static constexpr bool kUseAddr2line = !kIsTargetBuild;
59#endif
60
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080061pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070062#if defined(__APPLE__)
63 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070064 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -070065 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070066#elif defined(__BIONIC__)
67 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080068#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080069 return syscall(__NR_gettid);
70#endif
71}
72
Elliott Hughes289be852012-06-12 13:57:20 -070073std::string GetThreadName(pid_t tid) {
74 std::string result;
75 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070076 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070077 } else {
78 result = "<unknown>";
79 }
80 return result;
81}
82
Elliott Hughes6d3fc562014-08-27 11:47:01 -070083void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070084#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070085 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070086 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070087
88 // Check whether stack_addr is the base or end of the stack.
89 // (On Mac OS 10.7, it's the end.)
90 int stack_variable;
91 if (stack_addr > &stack_variable) {
Ian Rogers13735952014-10-08 12:43:28 -070092 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070093 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070094 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070095 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070096
97 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
98 pthread_attr_t attributes;
99 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
100 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
101 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700102#else
103 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700104 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700105 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700106 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700107 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700108
109#if defined(__GLIBC__)
110 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
111 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
112 // will be broken because we'll die long before we get close to 2GB.
113 bool is_main_thread = (::art::GetTid() == getpid());
114 if (is_main_thread) {
115 rlimit stack_limit;
116 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
117 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
118 }
119 if (stack_limit.rlim_cur == RLIM_INFINITY) {
120 size_t old_stack_size = *stack_size;
121
122 // Use the kernel default limit as our size, and adjust the base to match.
123 *stack_size = 8 * MB;
124 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
125
126 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
127 << " to " << PrettySize(*stack_size)
128 << " with base " << *stack_base;
129 }
130 }
131#endif
132
Elliott Hughese1884192012-04-23 12:38:15 -0700133#endif
134}
135
Elliott Hughesd92bec42011-09-02 17:04:36 -0700136bool ReadFileToString(const std::string& file_name, std::string* result) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800137 File file;
138 if (!file.Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700139 return false;
140 }
buzbeec143c552011-08-20 17:38:58 -0700141
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700142 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700143 while (true) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800144 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700145 if (n == -1) {
146 return false;
buzbeec143c552011-08-20 17:38:58 -0700147 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700148 if (n == 0) {
149 return true;
150 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700151 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700152 }
buzbeec143c552011-08-20 17:38:58 -0700153}
154
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800155bool PrintFileToLog(const std::string& file_name, LogSeverity level) {
156 File file;
157 if (!file.Open(file_name, O_RDONLY)) {
158 return false;
159 }
160
161 constexpr size_t kBufSize = 256; // Small buffer. Avoid stack overflow and stack size warnings.
162 char buf[kBufSize + 1]; // +1 for terminator.
163 size_t filled_to = 0;
164 while (true) {
165 DCHECK_LT(filled_to, kBufSize);
166 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[filled_to], kBufSize - filled_to));
167 if (n <= 0) {
168 // Print the rest of the buffer, if it exists.
169 if (filled_to > 0) {
170 buf[filled_to] = 0;
171 LOG(level) << buf;
172 }
173 return n == 0;
174 }
175 // Scan for '\n'.
176 size_t i = filled_to;
177 bool found_newline = false;
178 for (; i < filled_to + n; ++i) {
179 if (buf[i] == '\n') {
180 // Found a line break, that's something to print now.
181 buf[i] = 0;
182 LOG(level) << buf;
183 // Copy the rest to the front.
184 if (i + 1 < filled_to + n) {
185 memmove(&buf[0], &buf[i + 1], filled_to + n - i - 1);
186 filled_to = filled_to + n - i - 1;
187 } else {
188 filled_to = 0;
189 }
190 found_newline = true;
191 break;
192 }
193 }
194 if (found_newline) {
195 continue;
196 } else {
197 filled_to += n;
198 // Check if we must flush now.
199 if (filled_to == kBufSize) {
200 buf[kBufSize] = 0;
201 LOG(level) << buf;
202 filled_to = 0;
203 }
204 }
205 }
206}
207
Ian Rogersef7d42f2014-01-06 12:55:46 -0800208std::string PrettyDescriptor(mirror::String* java_descriptor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700209 if (java_descriptor == nullptr) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700210 return "null";
211 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700212 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700213}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700214
Ian Rogersef7d42f2014-01-06 12:55:46 -0800215std::string PrettyDescriptor(mirror::Class* klass) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700216 if (klass == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800217 return "null";
218 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700219 std::string temp;
220 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800221}
222
Ian Rogers1ff3c982014-08-12 02:30:58 -0700223std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700224 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700225 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700226 size_t dim = 0;
227 while (*c == '[') {
228 dim++;
229 c++;
230 }
231
232 // Reference or primitive?
233 if (*c == 'L') {
234 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700235 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700236 } else {
237 // "[[B" -> "byte[][]".
238 // To make life easier, we make primitives look like unqualified
239 // reference types.
240 switch (*c) {
241 case 'B': c = "byte;"; break;
242 case 'C': c = "char;"; break;
243 case 'D': c = "double;"; break;
244 case 'F': c = "float;"; break;
245 case 'I': c = "int;"; break;
246 case 'J': c = "long;"; break;
247 case 'S': c = "short;"; break;
248 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700249 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700250 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700251 }
252 }
253
254 // At this point, 'c' is a string of the form "fully/qualified/Type;"
255 // or "primitive;". Rewrite the type with '.' instead of '/':
256 std::string result;
257 const char* p = c;
258 while (*p != ';') {
259 char ch = *p++;
260 if (ch == '/') {
261 ch = '.';
262 }
263 result.push_back(ch);
264 }
265 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700266 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700267 result += "[]";
268 }
269 return result;
270}
271
Mathieu Chartierc7853442015-03-27 14:35:38 -0700272std::string PrettyField(ArtField* f, bool with_type) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700273 if (f == nullptr) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700274 return "null";
275 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700276 std::string result;
277 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700278 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700279 result += ' ';
280 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800281 std::string temp;
282 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700283 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700284 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700285 return result;
286}
287
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700288std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800289 if (field_idx >= dex_file.NumFieldIds()) {
290 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
291 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700292 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
293 std::string result;
294 if (with_type) {
295 result += dex_file.GetFieldTypeDescriptor(field_id);
296 result += ' ';
297 }
298 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
299 result += '.';
300 result += dex_file.GetFieldName(field_id);
301 return result;
302}
303
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700304std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800305 if (type_idx >= dex_file.NumTypeIds()) {
306 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
307 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700308 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700309 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700310}
311
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700312std::string PrettyArguments(const char* signature) {
313 std::string result;
314 result += '(';
315 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700316 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700317 while (*signature != ')') {
318 size_t argument_length = 0;
319 while (signature[argument_length] == '[') {
320 ++argument_length;
321 }
322 if (signature[argument_length] == 'L') {
323 argument_length = (strchr(signature, ';') - signature + 1);
324 } else {
325 ++argument_length;
326 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700327 {
328 std::string argument_descriptor(signature, argument_length);
329 result += PrettyDescriptor(argument_descriptor.c_str());
330 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700331 if (signature[argument_length] != ')') {
332 result += ", ";
333 }
334 signature += argument_length;
335 }
336 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700337 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700338 result += ')';
339 return result;
340}
341
342std::string PrettyReturnType(const char* signature) {
343 const char* return_type = strchr(signature, ')');
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700344 CHECK(return_type != nullptr);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700345 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700346 return PrettyDescriptor(return_type);
347}
348
Mathieu Chartiere401d142015-04-22 13:56:20 -0700349std::string PrettyMethod(ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800350 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700351 return "null";
352 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700353 if (!m->IsRuntimeMethod()) {
354 m = m->GetInterfaceMethodIfProxy(Runtime::Current()->GetClassLinker()->GetImagePointerSize());
355 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700356 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700357 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700358 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800359 if (UNLIKELY(m->IsFastNative())) {
360 result += "!";
361 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700362 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700363 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700364 std::string sig_as_string(signature.ToString());
365 if (signature == Signature::NoSignature()) {
366 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700367 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700368 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
369 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700370 }
371 return result;
372}
373
Ian Rogers0571d352011-11-03 19:51:38 -0700374std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800375 if (method_idx >= dex_file.NumMethodIds()) {
376 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
377 }
Ian Rogers0571d352011-11-03 19:51:38 -0700378 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
379 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
380 result += '.';
381 result += dex_file.GetMethodName(method_id);
382 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700383 const Signature signature = dex_file.GetMethodSignature(method_id);
384 std::string sig_as_string(signature.ToString());
385 if (signature == Signature::NoSignature()) {
386 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700387 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700388 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
389 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700390 }
391 return result;
392}
393
Ian Rogersef7d42f2014-01-06 12:55:46 -0800394std::string PrettyTypeOf(mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700395 if (obj == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700396 return "null";
397 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700398 if (obj->GetClass() == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700399 return "(raw)";
400 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700401 std::string temp;
402 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700403 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700404 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700405 }
406 return result;
407}
408
Ian Rogersef7d42f2014-01-06 12:55:46 -0800409std::string PrettyClass(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700410 if (c == nullptr) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700411 return "null";
412 }
413 std::string result;
414 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800415 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700416 result += ">";
417 return result;
418}
419
Ian Rogersef7d42f2014-01-06 12:55:46 -0800420std::string PrettyClassAndClassLoader(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700421 if (c == nullptr) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700422 return "null";
423 }
424 std::string result;
425 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800426 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700427 result += ",";
428 result += PrettyTypeOf(c->GetClassLoader());
429 // TODO: add an identifying hash value for the loader
430 result += ">";
431 return result;
432}
433
Andreas Gampec0d82292014-09-23 10:38:30 -0700434std::string PrettyJavaAccessFlags(uint32_t access_flags) {
435 std::string result;
436 if ((access_flags & kAccPublic) != 0) {
437 result += "public ";
438 }
439 if ((access_flags & kAccProtected) != 0) {
440 result += "protected ";
441 }
442 if ((access_flags & kAccPrivate) != 0) {
443 result += "private ";
444 }
445 if ((access_flags & kAccFinal) != 0) {
446 result += "final ";
447 }
448 if ((access_flags & kAccStatic) != 0) {
449 result += "static ";
450 }
451 if ((access_flags & kAccTransient) != 0) {
452 result += "transient ";
453 }
454 if ((access_flags & kAccVolatile) != 0) {
455 result += "volatile ";
456 }
457 if ((access_flags & kAccSynchronized) != 0) {
458 result += "synchronized ";
459 }
460 return result;
461}
462
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800463std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700464 // The byte thresholds at which we display amounts. A byte count is displayed
465 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800466 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700467 0, // B up to...
468 3*1024, // KB up to...
469 2*1024*1024, // MB up to...
470 1024*1024*1024 // GB from here.
471 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800472 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700473 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800474 const char* negative_str = "";
475 if (byte_count < 0) {
476 negative_str = "-";
477 byte_count = -byte_count;
478 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700479 int i = arraysize(kUnitThresholds);
480 while (--i > 0) {
481 if (byte_count >= kUnitThresholds[i]) {
482 break;
483 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800484 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800485 return StringPrintf("%s%" PRId64 "%s",
486 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800487}
488
Ian Rogers576ca0c2014-06-06 15:58:22 -0700489std::string PrintableChar(uint16_t ch) {
490 std::string result;
491 result += '\'';
492 if (NeedsEscaping(ch)) {
493 StringAppendF(&result, "\\u%04x", ch);
494 } else {
495 result += ch;
496 }
497 result += '\'';
498 return result;
499}
500
Ian Rogers68b56852014-08-29 20:19:11 -0700501std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700502 std::string result;
503 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700504 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700505 size_t char_count = CountModifiedUtf8Chars(p);
506 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000507 uint32_t ch = GetUtf16FromUtf8(&p);
Elliott Hughes82914b62012-04-09 15:56:29 -0700508 if (ch == '\\') {
509 result += "\\\\";
510 } else if (ch == '\n') {
511 result += "\\n";
512 } else if (ch == '\r') {
513 result += "\\r";
514 } else if (ch == '\t') {
515 result += "\\t";
Elliott Hughes82914b62012-04-09 15:56:29 -0700516 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000517 const uint16_t leading = GetLeadingUtf16Char(ch);
518
519 if (NeedsEscaping(leading)) {
520 StringAppendF(&result, "\\u%04x", leading);
521 } else {
522 result += leading;
523 }
524
525 const uint32_t trailing = GetTrailingUtf16Char(ch);
526 if (trailing != 0) {
527 // All high surrogates will need escaping.
528 StringAppendF(&result, "\\u%04x", trailing);
529 }
Elliott Hughes82914b62012-04-09 15:56:29 -0700530 }
531 }
532 result += '"';
533 return result;
534}
535
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800536// 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 -0700537std::string MangleForJni(const std::string& s) {
538 std::string result;
539 size_t char_count = CountModifiedUtf8Chars(s.c_str());
540 const char* cp = &s[0];
541 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000542 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800543 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
544 result.push_back(ch);
545 } else if (ch == '.' || ch == '/') {
546 result += "_";
547 } else if (ch == '_') {
548 result += "_1";
549 } else if (ch == ';') {
550 result += "_2";
551 } else if (ch == '[') {
552 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700553 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000554 const uint16_t leading = GetLeadingUtf16Char(ch);
555 const uint32_t trailing = GetTrailingUtf16Char(ch);
556
557 StringAppendF(&result, "_0%04x", leading);
558 if (trailing != 0) {
559 StringAppendF(&result, "_0%04x", trailing);
560 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700561 }
562 }
563 return result;
564}
565
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700566std::string DotToDescriptor(const char* class_name) {
567 std::string descriptor(class_name);
568 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
569 if (descriptor.length() > 0 && descriptor[0] != '[') {
570 descriptor = "L" + descriptor + ";";
571 }
572 return descriptor;
573}
574
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800575std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800576 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700577 if (length > 1) {
578 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
579 // Descriptors have the leading 'L' and trailing ';' stripped.
580 std::string result(descriptor + 1, length - 2);
581 std::replace(result.begin(), result.end(), '/', '.');
582 return result;
583 } else {
584 // For arrays the 'L' and ';' remain intact.
585 std::string result(descriptor);
586 std::replace(result.begin(), result.end(), '/', '.');
587 return result;
588 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800589 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700590 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800591 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800592}
593
594std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800595 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800596 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
597 std::string result(descriptor + 1, length - 2);
598 return result;
599 }
600 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700601}
602
Mathieu Chartiere401d142015-04-22 13:56:20 -0700603std::string JniShortName(ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700604 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700605 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700606 CHECK_EQ(class_name[0], 'L') << class_name;
607 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700608 class_name.erase(0, 1);
609 class_name.erase(class_name.size() - 1, 1);
610
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700611 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700612
613 std::string short_name;
614 short_name += "Java_";
615 short_name += MangleForJni(class_name);
616 short_name += "_";
617 short_name += MangleForJni(method_name);
618 return short_name;
619}
620
Mathieu Chartiere401d142015-04-22 13:56:20 -0700621std::string JniLongName(ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700622 std::string long_name;
623 long_name += JniShortName(m);
624 long_name += "__";
625
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700626 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700627 signature.erase(0, 1);
628 signature.erase(signature.begin() + signature.find(')'), signature.end());
629
630 long_name += MangleForJni(signature);
631
632 return long_name;
633}
634
jeffhao10037c82012-01-23 15:06:23 -0800635// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700636uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700637 0x00000000, // 00..1f low control characters; nothing valid
638 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
639 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
640 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700641};
642
jeffhao10037c82012-01-23 15:06:23 -0800643// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
644bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700645 /*
646 * It's a multibyte encoded character. Decode it and analyze. We
647 * accept anything that isn't (a) an improperly encoded low value,
648 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
649 * control character, or (e) a high space, layout, or special
650 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
651 * U+fff0..U+ffff). This is all specified in the dex format
652 * document.
653 */
654
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000655 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000656 const uint16_t leading = GetLeadingUtf16Char(pair);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000657
Narayan Kamath8508e372015-05-06 14:55:43 +0100658 // We have a surrogate pair resulting from a valid 4 byte UTF sequence.
659 // No further checks are necessary because 4 byte sequences span code
660 // points [U+10000, U+1FFFFF], which are valid codepoints in a dex
661 // identifier. Furthermore, GetUtf16FromUtf8 guarantees that each of
662 // the surrogate halves are valid and well formed in this instance.
663 if (GetTrailingUtf16Char(pair) != 0) {
664 return true;
665 }
666
667
668 // We've encountered a one, two or three byte UTF-8 sequence. The
669 // three byte UTF-8 sequence could be one half of a surrogate pair.
670 switch (leading >> 8) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000671 case 0x00:
672 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
673 return (leading > 0x00a0);
674 case 0xd8:
675 case 0xd9:
676 case 0xda:
677 case 0xdb:
Narayan Kamath8508e372015-05-06 14:55:43 +0100678 {
679 // We found a three byte sequence encoding one half of a surrogate.
680 // Look for the other half.
681 const uint32_t pair2 = GetUtf16FromUtf8(pUtf8Ptr);
682 const uint16_t trailing = GetLeadingUtf16Char(pair2);
683
684 return (GetTrailingUtf16Char(pair2) == 0) && (0xdc00 <= trailing && trailing <= 0xdfff);
685 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000686 case 0xdc:
687 case 0xdd:
688 case 0xde:
689 case 0xdf:
690 // It's a trailing surrogate, which is not valid at this point.
691 return false;
692 case 0x20:
693 case 0xff:
694 // It's in the range that has spaces, controls, and specials.
695 switch (leading & 0xfff8) {
Narayan Kamath8508e372015-05-06 14:55:43 +0100696 case 0x2000:
697 case 0x2008:
698 case 0x2028:
699 case 0xfff0:
700 case 0xfff8:
701 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000702 }
Narayan Kamath8508e372015-05-06 14:55:43 +0100703 return true;
704 default:
705 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700706 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000707
Narayan Kamath8508e372015-05-06 14:55:43 +0100708 UNREACHABLE();
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700709}
710
711/* Return whether the pointed-at modified-UTF-8 encoded character is
712 * valid as part of a member name, updating the pointer to point past
713 * the consumed character. This will consume two encoded UTF-16 code
714 * points if the character is encoded as a surrogate pair. Also, if
715 * this function returns false, then the given pointer may only have
716 * been partially advanced.
717 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700718static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700719 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700720 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700721 // It's low-ascii, so check the table.
722 uint32_t wordIdx = c >> 5;
723 uint32_t bitIdx = c & 0x1f;
724 (*pUtf8Ptr)++;
725 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
726 }
727
728 // It's a multibyte encoded character. Call a non-inline function
729 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800730 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
731}
732
733bool IsValidMemberName(const char* s) {
734 bool angle_name = false;
735
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700736 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800737 case '\0':
738 // The empty string is not a valid name.
739 return false;
740 case '<':
741 angle_name = true;
742 s++;
743 break;
744 }
745
746 while (true) {
747 switch (*s) {
748 case '\0':
749 return !angle_name;
750 case '>':
751 return angle_name && s[1] == '\0';
752 }
753
754 if (!IsValidPartOfMemberNameUtf8(&s)) {
755 return false;
756 }
757 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700758}
759
Elliott Hughes906e6852011-10-28 14:52:10 -0700760enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700761template<ClassNameType kType, char kSeparator>
762static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700763 int arrayCount = 0;
764 while (*s == '[') {
765 arrayCount++;
766 s++;
767 }
768
769 if (arrayCount > 255) {
770 // Arrays may have no more than 255 dimensions.
771 return false;
772 }
773
Ian Rogers7b078e82014-09-10 14:44:24 -0700774 ClassNameType type = kType;
775 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700776 /*
777 * If we're looking at an array of some sort, then it doesn't
778 * matter if what is being asked for is a class name; the
779 * format looks the same as a type descriptor in that case, so
780 * treat it as such.
781 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700782 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700783 }
784
Elliott Hughes906e6852011-10-28 14:52:10 -0700785 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700786 /*
787 * We are looking for a descriptor. Either validate it as a
788 * single-character primitive type, or continue on to check the
789 * embedded class name (bracketed by "L" and ";").
790 */
791 switch (*(s++)) {
792 case 'B':
793 case 'C':
794 case 'D':
795 case 'F':
796 case 'I':
797 case 'J':
798 case 'S':
799 case 'Z':
800 // These are all single-character descriptors for primitive types.
801 return (*s == '\0');
802 case 'V':
803 // Non-array void is valid, but you can't have an array of void.
804 return (arrayCount == 0) && (*s == '\0');
805 case 'L':
806 // Class name: Break out and continue below.
807 break;
808 default:
809 // Oddball descriptor character.
810 return false;
811 }
812 }
813
814 /*
815 * We just consumed the 'L' that introduces a class name as part
816 * of a type descriptor, or we are looking for an unadorned class
817 * name.
818 */
819
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700820 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700821 for (;;) {
822 uint8_t c = (uint8_t) *s;
823 switch (c) {
824 case '\0':
825 /*
826 * Premature end for a type descriptor, but valid for
827 * a class name as long as we haven't encountered an
828 * empty component (including the degenerate case of
829 * the empty string "").
830 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700831 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700832 case ';':
833 /*
834 * Invalid character for a class name, but the
835 * legitimate end of a type descriptor. In the latter
836 * case, make sure that this is the end of the string
837 * and that it doesn't end with an empty component
838 * (including the degenerate case of "L;").
839 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700840 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700841 case '/':
842 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700843 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700844 // The wrong separator character.
845 return false;
846 }
847 if (sepOrFirst) {
848 // Separator at start or two separators in a row.
849 return false;
850 }
851 sepOrFirst = true;
852 s++;
853 break;
854 default:
jeffhao10037c82012-01-23 15:06:23 -0800855 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700856 return false;
857 }
858 sepOrFirst = false;
859 break;
860 }
861 }
862}
863
Elliott Hughes906e6852011-10-28 14:52:10 -0700864bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700865 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700866}
867
868bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700869 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700870}
871
872bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700873 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700874}
875
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700876void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700877 const char* p = s.data();
878 const char* end = p + s.size();
879 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800880 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700881 ++p;
882 } else {
883 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800884 while (++p != end && *p != separator) {
885 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700886 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700887 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700888 }
889 }
890}
891
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700892std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -0700893 std::string result;
894 unsigned int start_index = 0;
895 unsigned int end_index = s.size() - 1;
896
897 // Skip initial whitespace.
898 while (start_index < s.size()) {
899 if (!isspace(s[start_index])) {
900 break;
901 }
902 start_index++;
903 }
904
905 // Skip terminating whitespace.
906 while (end_index >= start_index) {
907 if (!isspace(s[end_index])) {
908 break;
909 }
910 end_index--;
911 }
912
913 // All spaces, no beef.
914 if (end_index < start_index) {
915 return "";
916 }
917 // Start_index is the first non-space, end_index is the last one.
918 return s.substr(start_index, end_index - start_index + 1);
919}
920
Elliott Hughes48436bb2012-02-07 15:23:28 -0800921template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700922std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800923 if (strings.empty()) {
924 return "";
925 }
926
927 std::string result(strings[0]);
928 for (size_t i = 1; i < strings.size(); ++i) {
929 result += separator;
930 result += strings[i];
931 }
932 return result;
933}
934
935// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700936template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
937template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -0800938
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800939bool StartsWith(const std::string& s, const char* prefix) {
940 return s.compare(0, strlen(prefix), prefix) == 0;
941}
942
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700943bool EndsWith(const std::string& s, const char* suffix) {
944 size_t suffix_length = strlen(suffix);
945 size_t string_length = s.size();
946 if (suffix_length > string_length) {
947 return false;
948 }
949 size_t offset = string_length - suffix_length;
950 return s.compare(offset, suffix_length, suffix) == 0;
951}
952
Elliott Hughes22869a92012-03-27 14:08:24 -0700953void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700954 int hasAt = 0;
955 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700956 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700957 while (*s) {
958 if (*s == '.') {
959 hasDot = 1;
960 } else if (*s == '@') {
961 hasAt = 1;
962 }
963 s++;
964 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700965 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700966 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700967 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700968 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700969 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700970 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800971#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700972 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800973 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700974 strncpy(buf, s, sizeof(buf)-1);
975 buf[sizeof(buf)-1] = '\0';
976 errno = pthread_setname_np(pthread_self(), buf);
977 if (errno != 0) {
978 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
979 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800980#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700981 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700982#endif
983}
984
Brian Carlstrom29212012013-09-12 22:18:30 -0700985void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
986 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700987 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700988 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700989 return;
990 }
991 // Skip the command, which may contain spaces.
992 stats = stats.substr(stats.find(')') + 2);
993 // Extract the three fields we care about.
994 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700995 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700996 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700997 *utime = strtoull(fields[11].c_str(), nullptr, 10);
998 *stime = strtoull(fields[12].c_str(), nullptr, 10);
999 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -07001000}
1001
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001002std::string GetSchedulerGroupName(pid_t tid) {
1003 // /proc/<pid>/cgroup looks like this:
1004 // 2:devices:/
1005 // 1:cpuacct,cpu:/
1006 // We want the third field from the line whose second field contains the "cpu" token.
1007 std::string cgroup_file;
1008 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1009 return "";
1010 }
1011 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001012 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001013 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1014 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001015 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001016 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001017 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001018 for (size_t j = 0; j < cgroups.size(); ++j) {
1019 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001020 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001021 }
1022 }
1023 }
1024 return "";
1025}
1026
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001027#if defined(__linux__)
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001028
1029ALWAYS_INLINE
1030static inline void WritePrefix(std::ostream* os, const char* prefix, bool odd) {
1031 if (prefix != nullptr) {
1032 *os << prefix;
1033 }
1034 *os << " ";
1035 if (!odd) {
1036 *os << " ";
1037 }
1038}
1039
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001040static bool RunCommand(std::string cmd, std::ostream* os, const char* prefix) {
1041 FILE* stream = popen(cmd.c_str(), "r");
1042 if (stream) {
1043 if (os != nullptr) {
1044 bool odd_line = true; // We indent them differently.
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001045 bool wrote_prefix = false; // Have we already written a prefix?
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001046 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
1047 // alt stack, but just to be sure...
1048 char buffer[kMaxBuffer];
1049 while (!feof(stream)) {
1050 if (fgets(buffer, kMaxBuffer, stream) != nullptr) {
1051 // Split on newlines.
1052 char* tmp = buffer;
1053 for (;;) {
1054 char* new_line = strchr(tmp, '\n');
1055 if (new_line == nullptr) {
1056 // Print the rest.
1057 if (*tmp != 0) {
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001058 if (!wrote_prefix) {
1059 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001060 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001061 wrote_prefix = true;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001062 *os << tmp;
1063 }
1064 break;
1065 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001066 if (!wrote_prefix) {
1067 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001068 }
1069 char saved = *(new_line + 1);
1070 *(new_line + 1) = 0;
1071 *os << tmp;
1072 *(new_line + 1) = saved;
1073 tmp = new_line + 1;
1074 odd_line = !odd_line;
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001075 wrote_prefix = false;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001076 }
1077 }
1078 }
1079 }
1080 pclose(stream);
1081 return true;
1082 } else {
1083 return false;
1084 }
1085}
1086
1087static void Addr2line(const std::string& map_src, uintptr_t offset, std::ostream& os,
1088 const char* prefix) {
1089 std::string cmdline(StringPrintf("addr2line --functions --inlines --demangle -e %s %zx",
1090 map_src.c_str(), offset));
1091 RunCommand(cmdline.c_str(), &os, prefix);
1092}
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001093
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001094static bool PcIsWithinQuickCode(ArtMethod* method, uintptr_t pc) NO_THREAD_SAFETY_ANALYSIS {
1095 uintptr_t code = reinterpret_cast<uintptr_t>(EntryPointToCodePointer(
1096 method->GetEntryPointFromQuickCompiledCode()));
1097 if (code == 0) {
1098 return pc == 0;
1099 }
1100 uintptr_t code_size = reinterpret_cast<const OatQuickMethodHeader*>(code)[-1].code_size_;
1101 return code <= pc && pc <= (code + code_size);
1102}
Nicolas Geoffrayab60b682015-10-20 13:35:38 +01001103#endif
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001104
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001105void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001106 ArtMethod* current_method, void* ucontext_ptr) {
Ian Rogers83597d02014-11-20 10:29:00 -08001107#if __linux__
Andreas Gamped7576322014-10-24 22:13:45 -07001108 // b/18119146
Evgenii Stepanov1e133742015-05-20 12:30:59 -07001109 if (RUNNING_ON_MEMORY_TOOL != 0) {
Andreas Gamped7576322014-10-24 22:13:45 -07001110 return;
1111 }
1112
Ian Rogers700a4022014-05-19 16:49:03 -07001113 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Andreas Gampe628a61a2015-01-07 22:08:35 -08001114 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001115 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001116 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001117 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001118 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001119 return;
1120 }
1121
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001122 // Check whether we have and should use addr2line.
1123 bool use_addr2line;
1124 if (kUseAddr2line) {
1125 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
1126 // and print to stderr.
Andreas Gampe941c5512015-01-15 10:38:19 -08001127 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h", nullptr, nullptr);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001128 } else {
1129 use_addr2line = false;
1130 }
1131
Christopher Ferris943af7d2014-01-16 12:41:46 -08001132 for (Backtrace::const_iterator it = backtrace->begin();
1133 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001134 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001135 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1136 // In order for parsing tools to continue to function, the stack dump
1137 // format must at least adhere to this format:
1138 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1139 // The parsers require a single space before and after pc, and two spaces
1140 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1141 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1142 os << prefix << StringPrintf("#%02zu pc ", it->num);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001143 bool try_addr2line = false;
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001144 if (!BacktraceMap::IsValid(it->map)) {
Andreas Gampedd671252015-07-23 14:37:18 -07001145 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIxPTR " ???"
1146 : "%08" PRIxPTR " ???",
1147 it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001148 } else {
Andreas Gampedd671252015-07-23 14:37:18 -07001149 os << StringPrintf(Is64BitInstructionSet(kRuntimeISA) ? "%016" PRIxPTR " "
1150 : "%08" PRIxPTR " ",
1151 BacktraceMap::GetRelativePc(it->map, it->pc));
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001152 os << it->map.name;
Andreas Gampe3ef69b42015-01-26 10:38:34 -08001153 os << " (";
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001154 if (!it->func_name.empty()) {
1155 os << it->func_name;
1156 if (it->func_offset != 0) {
1157 os << "+" << it->func_offset;
1158 }
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001159 try_addr2line = true;
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01001160 } else if (current_method != nullptr &&
1161 Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
1162 PcIsWithinQuickCode(current_method, it->pc)) {
1163 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
Brian Carlstrom474cc792014-03-07 14:18:15 -08001164 os << JniLongName(current_method) << "+"
1165 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001166 } else {
1167 os << "???";
1168 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001169 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001170 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001171 os << "\n";
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001172 if (try_addr2line && use_addr2line) {
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001173 Addr2line(it->map.name, it->pc - it->map.start, os, prefix);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001174 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001175 }
Nicolas Geoffraye6ac4fd2014-11-04 13:03:29 +00001176#else
Nicolas Geoffrayb937a442015-10-20 12:55:20 +01001177 UNUSED(os, tid, prefix, current_method, ucontext_ptr);
Ian Rogersc5f17732014-06-05 20:48:42 -07001178#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001179}
1180
Elliott Hughes058a6de2012-05-24 19:13:02 -07001181#if defined(__APPLE__)
1182
1183// TODO: is there any way to get the kernel stack on Mac OS?
1184void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1185
1186#else
1187
Elliott Hughes46e251b2012-05-22 15:10:45 -07001188void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001189 if (tid == GetTid()) {
1190 // There's no point showing that we're reading our stack out of /proc!
1191 return;
1192 }
1193
Elliott Hughes46e251b2012-05-22 15:10:45 -07001194 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1195 std::string kernel_stack;
1196 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001197 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001198 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001199 }
1200
1201 std::vector<std::string> kernel_stack_frames;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001202 Split(kernel_stack, '\n', &kernel_stack_frames);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001203 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1204 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1205 kernel_stack_frames.pop_back();
1206 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001207 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1208 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001209 const char* text = kernel_stack_frames[i].c_str();
1210 const char* close_bracket = strchr(text, ']');
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001211 if (close_bracket != nullptr) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001212 text = close_bracket + 2;
1213 }
1214 os << prefix;
1215 if (include_count) {
1216 os << StringPrintf("#%02zd ", i);
1217 }
1218 os << text << "\n";
1219 }
1220}
1221
1222#endif
1223
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001224const char* GetAndroidRoot() {
1225 const char* android_root = getenv("ANDROID_ROOT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001226 if (android_root == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001227 if (OS::DirectoryExists("/system")) {
1228 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001229 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001230 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1231 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001232 }
1233 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001234 if (!OS::DirectoryExists(android_root)) {
1235 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001236 return "";
1237 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001238 return android_root;
1239}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001240
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001241const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001242 std::string error_msg;
1243 const char* dir = GetAndroidDataSafe(&error_msg);
1244 if (dir != nullptr) {
1245 return dir;
1246 } else {
1247 LOG(FATAL) << error_msg;
1248 return "";
1249 }
1250}
1251
1252const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001253 const char* android_data = getenv("ANDROID_DATA");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001254 if (android_data == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001255 if (OS::DirectoryExists("/data")) {
1256 android_data = "/data";
1257 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001258 *error_msg = "ANDROID_DATA not set and /data does not exist";
1259 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001260 }
1261 }
1262 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001263 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1264 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001265 }
1266 return android_data;
1267}
1268
Alex Lighta59dd802014-07-02 16:28:08 -07001269void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001270 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001271 CHECK(subdir != nullptr);
1272 std::string error_msg;
1273 const char* android_data = GetAndroidDataSafe(&error_msg);
1274 if (android_data == nullptr) {
1275 *have_android_data = false;
1276 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001277 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001278 return;
1279 } else {
1280 *have_android_data = true;
1281 }
1282 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1283 *dalvik_cache = dalvik_cache_root + subdir;
1284 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001285 *is_global_cache = strcmp(android_data, "/data") == 0;
1286 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001287 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1288 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1289 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1290 }
1291}
1292
Andreas Gampe40da2862015-02-27 12:49:04 -08001293static std::string GetDalvikCacheImpl(const char* subdir,
1294 const bool create_if_absent,
1295 const bool abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001296 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001297 const char* android_data = GetAndroidData();
1298 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001299 const std::string dalvik_cache = dalvik_cache_root + subdir;
Andreas Gampe40da2862015-02-27 12:49:04 -08001300 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1301 if (!create_if_absent) {
1302 // TODO: Check callers. Traditional behavior is to not to abort, even when abort_on_error.
1303 return "";
1304 }
1305
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001306 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
Andreas Gampe40da2862015-02-27 12:49:04 -08001307 if (strcmp(android_data, "/data") == 0) {
1308 if (abort_on_error) {
1309 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache
1310 << ", cannot create /data dalvik-cache.";
1311 UNREACHABLE();
Narayan Kamath11d9f062014-04-23 20:24:57 +01001312 }
Andreas Gampe40da2862015-02-27 12:49:04 -08001313 return "";
1314 }
1315
1316 int result = mkdir(dalvik_cache_root.c_str(), 0700);
1317 if (result != 0 && errno != EEXIST) {
1318 if (abort_on_error) {
1319 PLOG(FATAL) << "Failed to create dalvik-cache root directory " << dalvik_cache_root;
1320 UNREACHABLE();
1321 }
1322 return "";
1323 }
1324
1325 result = mkdir(dalvik_cache.c_str(), 0700);
1326 if (result != 0) {
1327 if (abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001328 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Andreas Gampe40da2862015-02-27 12:49:04 -08001329 UNREACHABLE();
Brian Carlstroma9f19782011-10-13 00:14:47 -07001330 }
Brian Carlstroma9f19782011-10-13 00:14:47 -07001331 return "";
1332 }
1333 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001334 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001335}
1336
Andreas Gampe40da2862015-02-27 12:49:04 -08001337std::string GetDalvikCache(const char* subdir, const bool create_if_absent) {
1338 return GetDalvikCacheImpl(subdir, create_if_absent, false);
1339}
1340
1341std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1342 return GetDalvikCacheImpl(subdir, create_if_absent, true);
1343}
1344
Alex Lighta59dd802014-07-02 16:28:08 -07001345bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1346 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001347 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001348 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1349 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001350 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001351 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001352 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001353 cache_file += "/";
1354 cache_file += DexFile::kClassesDex;
1355 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001356 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001357 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1358 return true;
1359}
1360
1361std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1362 std::string ret;
1363 std::string error_msg;
1364 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1365 LOG(FATAL) << error_msg;
1366 }
1367 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001368}
1369
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001370static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001371 // in = /foo/bar/baz
1372 // out = /foo/bar/<isa>/baz
1373 size_t pos = filename->rfind('/');
1374 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1375 filename->insert(pos, "/", 1);
1376 filename->insert(pos + 1, GetInstructionSetString(isa));
1377}
1378
1379std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1380 // location = /system/framework/boot.art
1381 // filename = /system/framework/<isa>/boot.art
1382 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001383 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001384 return filename;
1385}
1386
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001387bool IsZipMagic(uint32_t magic) {
1388 return (('P' == ((magic >> 0) & 0xff)) &&
1389 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001390}
1391
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001392bool IsDexMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001393 return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001394}
1395
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001396bool IsOatMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001397 return (memcmp(reinterpret_cast<const uint8_t*>(magic),
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001398 OatHeader::kOatMagic,
1399 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001400}
1401
Brian Carlstrom6449c622014-02-10 23:48:36 -08001402bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1403 const std::string command_line(Join(arg_vector, ' '));
1404
1405 CHECK_GE(arg_vector.size(), 1U) << command_line;
1406
1407 // Convert the args to char pointers.
1408 const char* program = arg_vector[0].c_str();
1409 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001410 for (size_t i = 0; i < arg_vector.size(); ++i) {
1411 const std::string& arg = arg_vector[i];
1412 char* arg_str = const_cast<char*>(arg.c_str());
1413 CHECK(arg_str != nullptr) << i;
1414 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001415 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001416 args.push_back(nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001417
1418 // fork and exec
1419 pid_t pid = fork();
1420 if (pid == 0) {
1421 // no allocation allowed between fork and exec
1422
1423 // change process groups, so we don't get reaped by ProcessManager
1424 setpgid(0, 0);
1425
1426 execv(program, &args[0]);
1427
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001428 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1429 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001430 } else {
1431 if (pid == -1) {
1432 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1433 command_line.c_str(), strerror(errno));
1434 return false;
1435 }
1436
1437 // wait for subprocess to finish
1438 int status;
1439 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1440 if (got_pid != pid) {
1441 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1442 "wanted %d, got %d: %s",
1443 command_line.c_str(), pid, got_pid, strerror(errno));
1444 return false;
1445 }
1446 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1447 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1448 command_line.c_str());
1449 return false;
1450 }
1451 }
1452 return true;
1453}
1454
Mathieu Chartier76433272014-09-26 14:32:37 -07001455std::string PrettyDescriptor(Primitive::Type type) {
1456 return PrettyDescriptor(Primitive::Descriptor(type));
1457}
1458
Andreas Gampe5073fed2015-08-10 11:40:25 -07001459static void DumpMethodCFGImpl(const DexFile* dex_file,
1460 uint32_t dex_method_idx,
1461 const DexFile::CodeItem* code_item,
1462 std::ostream& os) {
1463 os << "digraph {\n";
1464 os << " # /* " << PrettyMethod(dex_method_idx, *dex_file, true) << " */\n";
1465
1466 std::set<uint32_t> dex_pc_is_branch_target;
1467 {
1468 // Go and populate.
1469 const Instruction* inst = Instruction::At(code_item->insns_);
1470 for (uint32_t dex_pc = 0;
1471 dex_pc < code_item->insns_size_in_code_units_;
1472 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1473 if (inst->IsBranch()) {
1474 dex_pc_is_branch_target.insert(dex_pc + inst->GetTargetOffset());
1475 } else if (inst->IsSwitch()) {
1476 const uint16_t* insns = code_item->insns_ + dex_pc;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001477 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001478 const uint16_t* switch_insns = insns + switch_offset;
1479 uint32_t switch_count = switch_insns[1];
1480 int32_t targets_offset;
1481 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1482 /* 0=sig, 1=count, 2/3=firstKey */
1483 targets_offset = 4;
1484 } else {
1485 /* 0=sig, 1=count, 2..count*2 = keys */
1486 targets_offset = 2 + 2 * switch_count;
1487 }
1488 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001489 int32_t offset =
1490 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1491 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001492 dex_pc_is_branch_target.insert(dex_pc + offset);
1493 }
1494 }
1495 }
1496 }
1497
1498 // Create nodes for "basic blocks."
1499 std::map<uint32_t, uint32_t> dex_pc_to_node_id; // This only has entries for block starts.
1500 std::map<uint32_t, uint32_t> dex_pc_to_incl_id; // This has entries for all dex pcs.
1501
1502 {
1503 const Instruction* inst = Instruction::At(code_item->insns_);
1504 bool first_in_block = true;
1505 bool force_new_block = false;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001506 for (uint32_t dex_pc = 0;
1507 dex_pc < code_item->insns_size_in_code_units_;
1508 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001509 if (dex_pc == 0 ||
1510 (dex_pc_is_branch_target.find(dex_pc) != dex_pc_is_branch_target.end()) ||
1511 force_new_block) {
1512 uint32_t id = dex_pc_to_node_id.size();
1513 if (id > 0) {
1514 // End last node.
1515 os << "}\"];\n";
1516 }
1517 // Start next node.
1518 os << " node" << id << " [shape=record,label=\"{";
1519 dex_pc_to_node_id.insert(std::make_pair(dex_pc, id));
1520 first_in_block = true;
1521 force_new_block = false;
1522 }
1523
1524 // Register instruction.
1525 dex_pc_to_incl_id.insert(std::make_pair(dex_pc, dex_pc_to_node_id.size() - 1));
1526
1527 // Print instruction.
1528 if (!first_in_block) {
1529 os << " | ";
1530 } else {
1531 first_in_block = false;
1532 }
1533
1534 // Dump the instruction. Need to escape '"', '<', '>', '{' and '}'.
1535 os << "<" << "p" << dex_pc << ">";
1536 os << " 0x" << std::hex << dex_pc << std::dec << ": ";
1537 std::string inst_str = inst->DumpString(dex_file);
1538 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 -07001539 // we need to escape.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001540 while (cur_start != std::string::npos) {
1541 size_t next_escape = inst_str.find_first_of("\"{}<>", cur_start + 1);
1542 if (next_escape == std::string::npos) {
1543 os << inst_str.substr(cur_start, inst_str.size() - cur_start);
1544 break;
1545 } else {
1546 os << inst_str.substr(cur_start, next_escape - cur_start);
1547 // Escape all necessary characters.
1548 while (next_escape < inst_str.size()) {
1549 char c = inst_str.at(next_escape);
1550 if (c == '"' || c == '{' || c == '}' || c == '<' || c == '>') {
1551 os << '\\' << c;
1552 } else {
1553 break;
1554 }
1555 next_escape++;
1556 }
1557 if (next_escape >= inst_str.size()) {
1558 next_escape = std::string::npos;
1559 }
1560 cur_start = next_escape;
1561 }
1562 }
1563
1564 // Force a new block for some fall-throughs and some instructions that terminate the "local"
1565 // control flow.
1566 force_new_block = inst->IsSwitch() || inst->IsBasicBlockEnd();
1567 }
1568 // Close last node.
1569 if (dex_pc_to_node_id.size() > 0) {
1570 os << "}\"];\n";
1571 }
1572 }
1573
1574 // Create edges between them.
1575 {
1576 std::ostringstream regular_edges;
1577 std::ostringstream taken_edges;
1578 std::ostringstream exception_edges;
1579
1580 // Common set of exception edges.
1581 std::set<uint32_t> exception_targets;
1582
1583 // These blocks (given by the first dex pc) need exception per dex-pc handling in a second
1584 // pass. In the first pass we try and see whether we can use a common set of edges.
1585 std::set<uint32_t> blocks_with_detailed_exceptions;
1586
1587 {
1588 uint32_t last_node_id = std::numeric_limits<uint32_t>::max();
1589 uint32_t old_dex_pc = 0;
1590 uint32_t block_start_dex_pc = std::numeric_limits<uint32_t>::max();
1591 const Instruction* inst = Instruction::At(code_item->insns_);
1592 for (uint32_t dex_pc = 0;
1593 dex_pc < code_item->insns_size_in_code_units_;
1594 old_dex_pc = dex_pc, dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1595 {
1596 auto it = dex_pc_to_node_id.find(dex_pc);
1597 if (it != dex_pc_to_node_id.end()) {
1598 if (!exception_targets.empty()) {
1599 // It seems the last block had common exception handlers. Add the exception edges now.
1600 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1601 for (uint32_t handler_pc : exception_targets) {
1602 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1603 if (node_id_it != dex_pc_to_incl_id.end()) {
1604 exception_edges << " node" << node_id
1605 << " -> node" << node_id_it->second << ":p" << handler_pc
1606 << ";\n";
1607 }
1608 }
1609 exception_targets.clear();
1610 }
1611
1612 block_start_dex_pc = dex_pc;
1613
1614 // Seems to be a fall-through, connect to last_node_id. May be spurious edges for things
1615 // like switch data.
1616 uint32_t old_last = last_node_id;
1617 last_node_id = it->second;
1618 if (old_last != std::numeric_limits<uint32_t>::max()) {
1619 regular_edges << " node" << old_last << ":p" << old_dex_pc
1620 << " -> node" << last_node_id << ":p" << dex_pc
1621 << ";\n";
1622 }
1623 }
1624
1625 // Look at the exceptions of the first entry.
1626 CatchHandlerIterator catch_it(*code_item, dex_pc);
1627 for (; catch_it.HasNext(); catch_it.Next()) {
1628 exception_targets.insert(catch_it.GetHandlerAddress());
1629 }
1630 }
1631
1632 // Handle instruction.
1633
1634 // Branch: something with at most two targets.
1635 if (inst->IsBranch()) {
1636 const int32_t offset = inst->GetTargetOffset();
1637 const bool conditional = !inst->IsUnconditional();
1638
1639 auto target_it = dex_pc_to_node_id.find(dex_pc + offset);
1640 if (target_it != dex_pc_to_node_id.end()) {
1641 taken_edges << " node" << last_node_id << ":p" << dex_pc
1642 << " -> node" << target_it->second << ":p" << (dex_pc + offset)
1643 << ";\n";
1644 }
1645 if (!conditional) {
1646 // No fall-through.
1647 last_node_id = std::numeric_limits<uint32_t>::max();
1648 }
1649 } else if (inst->IsSwitch()) {
1650 // TODO: Iterate through all switch targets.
1651 const uint16_t* insns = code_item->insns_ + dex_pc;
1652 /* make sure the start of the switch is in range */
Andreas Gampe53de99c2015-08-17 13:43:55 -07001653 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001654 /* offset to switch table is a relative branch-style offset */
1655 const uint16_t* switch_insns = insns + switch_offset;
1656 uint32_t switch_count = switch_insns[1];
1657 int32_t targets_offset;
1658 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1659 /* 0=sig, 1=count, 2/3=firstKey */
1660 targets_offset = 4;
1661 } else {
1662 /* 0=sig, 1=count, 2..count*2 = keys */
1663 targets_offset = 2 + 2 * switch_count;
1664 }
1665 /* make sure the end of the switch is in range */
1666 /* verify each switch target */
1667 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001668 int32_t offset =
1669 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1670 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001671 int32_t abs_offset = dex_pc + offset;
1672 auto target_it = dex_pc_to_node_id.find(abs_offset);
1673 if (target_it != dex_pc_to_node_id.end()) {
1674 // TODO: value label.
1675 taken_edges << " node" << last_node_id << ":p" << dex_pc
1676 << " -> node" << target_it->second << ":p" << (abs_offset)
1677 << ";\n";
1678 }
1679 }
1680 }
1681
1682 // Exception edges. If this is not the first instruction in the block
1683 if (block_start_dex_pc != dex_pc) {
1684 std::set<uint32_t> current_handler_pcs;
1685 CatchHandlerIterator catch_it(*code_item, dex_pc);
1686 for (; catch_it.HasNext(); catch_it.Next()) {
1687 current_handler_pcs.insert(catch_it.GetHandlerAddress());
1688 }
1689 if (current_handler_pcs != exception_targets) {
1690 exception_targets.clear(); // Clear so we don't do something at the end.
1691 blocks_with_detailed_exceptions.insert(block_start_dex_pc);
1692 }
1693 }
1694
1695 if (inst->IsReturn() ||
1696 (inst->Opcode() == Instruction::THROW) ||
1697 (inst->IsBranch() && inst->IsUnconditional())) {
1698 // No fall-through.
1699 last_node_id = std::numeric_limits<uint32_t>::max();
1700 }
1701 }
1702 // Finish up the last block, if it had common exceptions.
1703 if (!exception_targets.empty()) {
1704 // It seems the last block had common exception handlers. Add the exception edges now.
1705 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1706 for (uint32_t handler_pc : exception_targets) {
1707 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1708 if (node_id_it != dex_pc_to_incl_id.end()) {
1709 exception_edges << " node" << node_id
1710 << " -> node" << node_id_it->second << ":p" << handler_pc
1711 << ";\n";
1712 }
1713 }
1714 exception_targets.clear();
1715 }
1716 }
1717
1718 // Second pass for detailed exception blocks.
1719 // TODO
1720 // Exception edges. If this is not the first instruction in the block
1721 for (uint32_t dex_pc : blocks_with_detailed_exceptions) {
1722 const Instruction* inst = Instruction::At(&code_item->insns_[dex_pc]);
1723 uint32_t this_node_id = dex_pc_to_incl_id.find(dex_pc)->second;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001724 while (true) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001725 CatchHandlerIterator catch_it(*code_item, dex_pc);
1726 if (catch_it.HasNext()) {
1727 std::set<uint32_t> handled_targets;
1728 for (; catch_it.HasNext(); catch_it.Next()) {
1729 uint32_t handler_pc = catch_it.GetHandlerAddress();
1730 auto it = handled_targets.find(handler_pc);
1731 if (it == handled_targets.end()) {
1732 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1733 if (node_id_it != dex_pc_to_incl_id.end()) {
1734 exception_edges << " node" << this_node_id << ":p" << dex_pc
1735 << " -> node" << node_id_it->second << ":p" << handler_pc
1736 << ";\n";
1737 }
1738
1739 // Mark as done.
1740 handled_targets.insert(handler_pc);
1741 }
1742 }
1743 }
1744 if (inst->IsBasicBlockEnd()) {
1745 break;
1746 }
1747
Andreas Gampe53de99c2015-08-17 13:43:55 -07001748 // Loop update. Have a break-out if the next instruction is a branch target and thus in
1749 // another block.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001750 dex_pc += inst->SizeInCodeUnits();
1751 if (dex_pc >= code_item->insns_size_in_code_units_) {
1752 break;
1753 }
1754 if (dex_pc_to_node_id.find(dex_pc) != dex_pc_to_node_id.end()) {
1755 break;
1756 }
1757 inst = inst->Next();
1758 }
1759 }
1760
1761 // Write out the sub-graphs to make edges styled.
1762 os << "\n";
1763 os << " subgraph regular_edges {\n";
1764 os << " edge [color=\"#000000\",weight=.3,len=3];\n\n";
1765 os << " " << regular_edges.str() << "\n";
1766 os << " }\n\n";
1767
1768 os << " subgraph taken_edges {\n";
1769 os << " edge [color=\"#00FF00\",weight=.3,len=3];\n\n";
1770 os << " " << taken_edges.str() << "\n";
1771 os << " }\n\n";
1772
1773 os << " subgraph exception_edges {\n";
1774 os << " edge [color=\"#FF0000\",weight=.3,len=3];\n\n";
1775 os << " " << exception_edges.str() << "\n";
1776 os << " }\n\n";
1777 }
1778
1779 os << "}\n";
1780}
1781
1782void DumpMethodCFG(ArtMethod* method, std::ostream& os) {
1783 const DexFile* dex_file = method->GetDexFile();
1784 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1785
1786 DumpMethodCFGImpl(dex_file, method->GetDexMethodIndex(), code_item, os);
1787}
1788
1789void DumpMethodCFG(const DexFile* dex_file, uint32_t dex_method_idx, std::ostream& os) {
1790 // This is painful, we need to find the code item. That means finding the class, and then
1791 // iterating the table.
1792 if (dex_method_idx >= dex_file->NumMethodIds()) {
1793 os << "Could not find method-idx.";
1794 return;
1795 }
1796 const DexFile::MethodId& method_id = dex_file->GetMethodId(dex_method_idx);
1797
1798 const DexFile::ClassDef* class_def = dex_file->FindClassDef(method_id.class_idx_);
1799 if (class_def == nullptr) {
1800 os << "Could not find class-def.";
1801 return;
1802 }
1803
1804 const uint8_t* class_data = dex_file->GetClassData(*class_def);
1805 if (class_data == nullptr) {
1806 os << "No class data.";
1807 return;
1808 }
1809
1810 ClassDataItemIterator it(*dex_file, class_data);
1811 // Skip fields
1812 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
1813 it.Next();
1814 }
1815
1816 // Find method, and dump it.
1817 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
1818 uint32_t method_idx = it.GetMemberIndex();
1819 if (method_idx == dex_method_idx) {
1820 DumpMethodCFGImpl(dex_file, dex_method_idx, it.GetMethodCodeItem(), os);
1821 return;
1822 }
1823 it.Next();
1824 }
1825
1826 // Otherwise complain.
1827 os << "Something went wrong, didn't find the method in the class data.";
1828}
1829
Elliott Hughes42ee1422011-09-06 12:33:32 -07001830} // namespace art