blob: 515ba9f9e388a57fc953c7a85761a7e456fb09d0 [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
Elliott Hughes058a6de2012-05-24 19:13:02 -070049#if defined(__linux__)
Elliott Hughese1aee692012-01-17 16:40:10 -080050#include <linux/unistd.h>
Elliott Hughese1aee692012-01-17 16:40:10 -080051#endif
52
Elliott Hughes11e45072011-08-16 17:40:46 -070053namespace art {
54
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080055pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070056#if defined(__APPLE__)
57 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070058 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -070059 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070060#elif defined(__BIONIC__)
61 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080062#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080063 return syscall(__NR_gettid);
64#endif
65}
66
Elliott Hughes289be852012-06-12 13:57:20 -070067std::string GetThreadName(pid_t tid) {
68 std::string result;
69 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070070 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070071 } else {
72 result = "<unknown>";
73 }
74 return result;
75}
76
Elliott Hughes6d3fc562014-08-27 11:47:01 -070077void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070078#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070079 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070080 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070081
82 // Check whether stack_addr is the base or end of the stack.
83 // (On Mac OS 10.7, it's the end.)
84 int stack_variable;
85 if (stack_addr > &stack_variable) {
Ian Rogers13735952014-10-08 12:43:28 -070086 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070087 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070088 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070089 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070090
91 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
92 pthread_attr_t attributes;
93 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
94 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
95 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -070096#else
97 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -070098 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -070099 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700100 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700101 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700102
103#if defined(__GLIBC__)
104 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
105 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
106 // will be broken because we'll die long before we get close to 2GB.
107 bool is_main_thread = (::art::GetTid() == getpid());
108 if (is_main_thread) {
109 rlimit stack_limit;
110 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
111 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
112 }
113 if (stack_limit.rlim_cur == RLIM_INFINITY) {
114 size_t old_stack_size = *stack_size;
115
116 // Use the kernel default limit as our size, and adjust the base to match.
117 *stack_size = 8 * MB;
118 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
119
120 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
121 << " to " << PrettySize(*stack_size)
122 << " with base " << *stack_base;
123 }
124 }
125#endif
126
Elliott Hughese1884192012-04-23 12:38:15 -0700127#endif
128}
129
Elliott Hughesd92bec42011-09-02 17:04:36 -0700130bool ReadFileToString(const std::string& file_name, std::string* result) {
Andreas Gampedf878922015-08-13 16:44:54 -0700131 File file(file_name, O_RDONLY, false);
132 if (!file.IsOpened()) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700133 return false;
134 }
buzbeec143c552011-08-20 17:38:58 -0700135
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700136 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700137 while (true) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800138 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700139 if (n == -1) {
140 return false;
buzbeec143c552011-08-20 17:38:58 -0700141 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700142 if (n == 0) {
143 return true;
144 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700145 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700146 }
buzbeec143c552011-08-20 17:38:58 -0700147}
148
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800149bool PrintFileToLog(const std::string& file_name, LogSeverity level) {
Andreas Gampedf878922015-08-13 16:44:54 -0700150 File file(file_name, O_RDONLY, false);
151 if (!file.IsOpened()) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800152 return false;
153 }
154
155 constexpr size_t kBufSize = 256; // Small buffer. Avoid stack overflow and stack size warnings.
156 char buf[kBufSize + 1]; // +1 for terminator.
157 size_t filled_to = 0;
158 while (true) {
159 DCHECK_LT(filled_to, kBufSize);
160 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[filled_to], kBufSize - filled_to));
161 if (n <= 0) {
162 // Print the rest of the buffer, if it exists.
163 if (filled_to > 0) {
164 buf[filled_to] = 0;
165 LOG(level) << buf;
166 }
167 return n == 0;
168 }
169 // Scan for '\n'.
170 size_t i = filled_to;
171 bool found_newline = false;
172 for (; i < filled_to + n; ++i) {
173 if (buf[i] == '\n') {
174 // Found a line break, that's something to print now.
175 buf[i] = 0;
176 LOG(level) << buf;
177 // Copy the rest to the front.
178 if (i + 1 < filled_to + n) {
179 memmove(&buf[0], &buf[i + 1], filled_to + n - i - 1);
180 filled_to = filled_to + n - i - 1;
181 } else {
182 filled_to = 0;
183 }
184 found_newline = true;
185 break;
186 }
187 }
188 if (found_newline) {
189 continue;
190 } else {
191 filled_to += n;
192 // Check if we must flush now.
193 if (filled_to == kBufSize) {
194 buf[kBufSize] = 0;
195 LOG(level) << buf;
196 filled_to = 0;
197 }
198 }
199 }
200}
201
Ian Rogersef7d42f2014-01-06 12:55:46 -0800202std::string PrettyDescriptor(mirror::String* java_descriptor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700203 if (java_descriptor == nullptr) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700204 return "null";
205 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700206 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700207}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700208
Ian Rogersef7d42f2014-01-06 12:55:46 -0800209std::string PrettyDescriptor(mirror::Class* klass) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700210 if (klass == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800211 return "null";
212 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700213 std::string temp;
214 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800215}
216
Ian Rogers1ff3c982014-08-12 02:30:58 -0700217std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700218 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700219 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700220 size_t dim = 0;
221 while (*c == '[') {
222 dim++;
223 c++;
224 }
225
226 // Reference or primitive?
227 if (*c == 'L') {
228 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700229 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700230 } else {
231 // "[[B" -> "byte[][]".
232 // To make life easier, we make primitives look like unqualified
233 // reference types.
234 switch (*c) {
235 case 'B': c = "byte;"; break;
236 case 'C': c = "char;"; break;
237 case 'D': c = "double;"; break;
238 case 'F': c = "float;"; break;
239 case 'I': c = "int;"; break;
240 case 'J': c = "long;"; break;
241 case 'S': c = "short;"; break;
242 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700243 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700244 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700245 }
246 }
247
248 // At this point, 'c' is a string of the form "fully/qualified/Type;"
249 // or "primitive;". Rewrite the type with '.' instead of '/':
250 std::string result;
251 const char* p = c;
252 while (*p != ';') {
253 char ch = *p++;
254 if (ch == '/') {
255 ch = '.';
256 }
257 result.push_back(ch);
258 }
259 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700260 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700261 result += "[]";
262 }
263 return result;
264}
265
Mathieu Chartierc7853442015-03-27 14:35:38 -0700266std::string PrettyField(ArtField* f, bool with_type) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700267 if (f == nullptr) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700268 return "null";
269 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700270 std::string result;
271 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700272 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700273 result += ' ';
274 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800275 std::string temp;
276 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700277 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700278 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700279 return result;
280}
281
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700282std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800283 if (field_idx >= dex_file.NumFieldIds()) {
284 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
285 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700286 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
287 std::string result;
288 if (with_type) {
289 result += dex_file.GetFieldTypeDescriptor(field_id);
290 result += ' ';
291 }
292 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
293 result += '.';
294 result += dex_file.GetFieldName(field_id);
295 return result;
296}
297
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700298std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800299 if (type_idx >= dex_file.NumTypeIds()) {
300 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
301 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700302 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700303 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700304}
305
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700306std::string PrettyArguments(const char* signature) {
307 std::string result;
308 result += '(';
309 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700310 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700311 while (*signature != ')') {
312 size_t argument_length = 0;
313 while (signature[argument_length] == '[') {
314 ++argument_length;
315 }
316 if (signature[argument_length] == 'L') {
317 argument_length = (strchr(signature, ';') - signature + 1);
318 } else {
319 ++argument_length;
320 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700321 {
322 std::string argument_descriptor(signature, argument_length);
323 result += PrettyDescriptor(argument_descriptor.c_str());
324 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700325 if (signature[argument_length] != ')') {
326 result += ", ";
327 }
328 signature += argument_length;
329 }
330 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700331 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700332 result += ')';
333 return result;
334}
335
336std::string PrettyReturnType(const char* signature) {
337 const char* return_type = strchr(signature, ')');
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700338 CHECK(return_type != nullptr);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700339 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700340 return PrettyDescriptor(return_type);
341}
342
Mathieu Chartiere401d142015-04-22 13:56:20 -0700343std::string PrettyMethod(ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800344 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700345 return "null";
346 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700347 if (!m->IsRuntimeMethod()) {
348 m = m->GetInterfaceMethodIfProxy(Runtime::Current()->GetClassLinker()->GetImagePointerSize());
349 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700350 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700351 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700352 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800353 if (UNLIKELY(m->IsFastNative())) {
354 result += "!";
355 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700356 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700357 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700358 std::string sig_as_string(signature.ToString());
359 if (signature == Signature::NoSignature()) {
360 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700361 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700362 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
363 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700364 }
365 return result;
366}
367
Ian Rogers0571d352011-11-03 19:51:38 -0700368std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800369 if (method_idx >= dex_file.NumMethodIds()) {
370 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
371 }
Ian Rogers0571d352011-11-03 19:51:38 -0700372 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
373 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
374 result += '.';
375 result += dex_file.GetMethodName(method_id);
376 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700377 const Signature signature = dex_file.GetMethodSignature(method_id);
378 std::string sig_as_string(signature.ToString());
379 if (signature == Signature::NoSignature()) {
380 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700381 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700382 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
383 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700384 }
385 return result;
386}
387
Ian Rogersef7d42f2014-01-06 12:55:46 -0800388std::string PrettyTypeOf(mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700389 if (obj == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700390 return "null";
391 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700392 if (obj->GetClass() == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700393 return "(raw)";
394 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700395 std::string temp;
396 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700397 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700398 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700399 }
400 return result;
401}
402
Ian Rogersef7d42f2014-01-06 12:55:46 -0800403std::string PrettyClass(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700404 if (c == nullptr) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700405 return "null";
406 }
407 std::string result;
408 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800409 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700410 result += ">";
411 return result;
412}
413
Ian Rogersef7d42f2014-01-06 12:55:46 -0800414std::string PrettyClassAndClassLoader(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700415 if (c == nullptr) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700416 return "null";
417 }
418 std::string result;
419 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800420 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700421 result += ",";
422 result += PrettyTypeOf(c->GetClassLoader());
423 // TODO: add an identifying hash value for the loader
424 result += ">";
425 return result;
426}
427
Andreas Gampec0d82292014-09-23 10:38:30 -0700428std::string PrettyJavaAccessFlags(uint32_t access_flags) {
429 std::string result;
430 if ((access_flags & kAccPublic) != 0) {
431 result += "public ";
432 }
433 if ((access_flags & kAccProtected) != 0) {
434 result += "protected ";
435 }
436 if ((access_flags & kAccPrivate) != 0) {
437 result += "private ";
438 }
439 if ((access_flags & kAccFinal) != 0) {
440 result += "final ";
441 }
442 if ((access_flags & kAccStatic) != 0) {
443 result += "static ";
444 }
445 if ((access_flags & kAccTransient) != 0) {
446 result += "transient ";
447 }
448 if ((access_flags & kAccVolatile) != 0) {
449 result += "volatile ";
450 }
451 if ((access_flags & kAccSynchronized) != 0) {
452 result += "synchronized ";
453 }
454 return result;
455}
456
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800457std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700458 // The byte thresholds at which we display amounts. A byte count is displayed
459 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800460 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700461 0, // B up to...
462 3*1024, // KB up to...
463 2*1024*1024, // MB up to...
464 1024*1024*1024 // GB from here.
465 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800466 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700467 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800468 const char* negative_str = "";
469 if (byte_count < 0) {
470 negative_str = "-";
471 byte_count = -byte_count;
472 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700473 int i = arraysize(kUnitThresholds);
474 while (--i > 0) {
475 if (byte_count >= kUnitThresholds[i]) {
476 break;
477 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800478 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800479 return StringPrintf("%s%" PRId64 "%s",
480 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800481}
482
Ian Rogers576ca0c2014-06-06 15:58:22 -0700483std::string PrintableChar(uint16_t ch) {
484 std::string result;
485 result += '\'';
486 if (NeedsEscaping(ch)) {
487 StringAppendF(&result, "\\u%04x", ch);
488 } else {
489 result += ch;
490 }
491 result += '\'';
492 return result;
493}
494
Ian Rogers68b56852014-08-29 20:19:11 -0700495std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700496 std::string result;
497 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700498 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700499 size_t char_count = CountModifiedUtf8Chars(p);
500 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000501 uint32_t ch = GetUtf16FromUtf8(&p);
Elliott Hughes82914b62012-04-09 15:56:29 -0700502 if (ch == '\\') {
503 result += "\\\\";
504 } else if (ch == '\n') {
505 result += "\\n";
506 } else if (ch == '\r') {
507 result += "\\r";
508 } else if (ch == '\t') {
509 result += "\\t";
Elliott Hughes82914b62012-04-09 15:56:29 -0700510 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000511 const uint16_t leading = GetLeadingUtf16Char(ch);
512
513 if (NeedsEscaping(leading)) {
514 StringAppendF(&result, "\\u%04x", leading);
515 } else {
516 result += leading;
517 }
518
519 const uint32_t trailing = GetTrailingUtf16Char(ch);
520 if (trailing != 0) {
521 // All high surrogates will need escaping.
522 StringAppendF(&result, "\\u%04x", trailing);
523 }
Elliott Hughes82914b62012-04-09 15:56:29 -0700524 }
525 }
526 result += '"';
527 return result;
528}
529
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800530// 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 -0700531std::string MangleForJni(const std::string& s) {
532 std::string result;
533 size_t char_count = CountModifiedUtf8Chars(s.c_str());
534 const char* cp = &s[0];
535 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000536 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800537 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
538 result.push_back(ch);
539 } else if (ch == '.' || ch == '/') {
540 result += "_";
541 } else if (ch == '_') {
542 result += "_1";
543 } else if (ch == ';') {
544 result += "_2";
545 } else if (ch == '[') {
546 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700547 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000548 const uint16_t leading = GetLeadingUtf16Char(ch);
549 const uint32_t trailing = GetTrailingUtf16Char(ch);
550
551 StringAppendF(&result, "_0%04x", leading);
552 if (trailing != 0) {
553 StringAppendF(&result, "_0%04x", trailing);
554 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700555 }
556 }
557 return result;
558}
559
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700560std::string DotToDescriptor(const char* class_name) {
561 std::string descriptor(class_name);
562 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
563 if (descriptor.length() > 0 && descriptor[0] != '[') {
564 descriptor = "L" + descriptor + ";";
565 }
566 return descriptor;
567}
568
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800569std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800570 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700571 if (length > 1) {
572 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
573 // Descriptors have the leading 'L' and trailing ';' stripped.
574 std::string result(descriptor + 1, length - 2);
575 std::replace(result.begin(), result.end(), '/', '.');
576 return result;
577 } else {
578 // For arrays the 'L' and ';' remain intact.
579 std::string result(descriptor);
580 std::replace(result.begin(), result.end(), '/', '.');
581 return result;
582 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800583 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700584 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800585 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800586}
587
588std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800589 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800590 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
591 std::string result(descriptor + 1, length - 2);
592 return result;
593 }
594 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700595}
596
Mathieu Chartiere401d142015-04-22 13:56:20 -0700597std::string JniShortName(ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700598 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700599 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700600 CHECK_EQ(class_name[0], 'L') << class_name;
601 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700602 class_name.erase(0, 1);
603 class_name.erase(class_name.size() - 1, 1);
604
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700605 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700606
607 std::string short_name;
608 short_name += "Java_";
609 short_name += MangleForJni(class_name);
610 short_name += "_";
611 short_name += MangleForJni(method_name);
612 return short_name;
613}
614
Mathieu Chartiere401d142015-04-22 13:56:20 -0700615std::string JniLongName(ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700616 std::string long_name;
617 long_name += JniShortName(m);
618 long_name += "__";
619
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700620 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700621 signature.erase(0, 1);
622 signature.erase(signature.begin() + signature.find(')'), signature.end());
623
624 long_name += MangleForJni(signature);
625
626 return long_name;
627}
628
jeffhao10037c82012-01-23 15:06:23 -0800629// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700630uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700631 0x00000000, // 00..1f low control characters; nothing valid
632 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
633 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
634 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700635};
636
jeffhao10037c82012-01-23 15:06:23 -0800637// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
638bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700639 /*
640 * It's a multibyte encoded character. Decode it and analyze. We
641 * accept anything that isn't (a) an improperly encoded low value,
642 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
643 * control character, or (e) a high space, layout, or special
644 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
645 * U+fff0..U+ffff). This is all specified in the dex format
646 * document.
647 */
648
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000649 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000650 const uint16_t leading = GetLeadingUtf16Char(pair);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000651
Narayan Kamath8508e372015-05-06 14:55:43 +0100652 // We have a surrogate pair resulting from a valid 4 byte UTF sequence.
653 // No further checks are necessary because 4 byte sequences span code
654 // points [U+10000, U+1FFFFF], which are valid codepoints in a dex
655 // identifier. Furthermore, GetUtf16FromUtf8 guarantees that each of
656 // the surrogate halves are valid and well formed in this instance.
657 if (GetTrailingUtf16Char(pair) != 0) {
658 return true;
659 }
660
661
662 // We've encountered a one, two or three byte UTF-8 sequence. The
663 // three byte UTF-8 sequence could be one half of a surrogate pair.
664 switch (leading >> 8) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000665 case 0x00:
666 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
667 return (leading > 0x00a0);
668 case 0xd8:
669 case 0xd9:
670 case 0xda:
671 case 0xdb:
Narayan Kamath8508e372015-05-06 14:55:43 +0100672 {
673 // We found a three byte sequence encoding one half of a surrogate.
674 // Look for the other half.
675 const uint32_t pair2 = GetUtf16FromUtf8(pUtf8Ptr);
676 const uint16_t trailing = GetLeadingUtf16Char(pair2);
677
678 return (GetTrailingUtf16Char(pair2) == 0) && (0xdc00 <= trailing && trailing <= 0xdfff);
679 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000680 case 0xdc:
681 case 0xdd:
682 case 0xde:
683 case 0xdf:
684 // It's a trailing surrogate, which is not valid at this point.
685 return false;
686 case 0x20:
687 case 0xff:
688 // It's in the range that has spaces, controls, and specials.
689 switch (leading & 0xfff8) {
Narayan Kamath8508e372015-05-06 14:55:43 +0100690 case 0x2000:
691 case 0x2008:
692 case 0x2028:
693 case 0xfff0:
694 case 0xfff8:
695 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000696 }
Narayan Kamath8508e372015-05-06 14:55:43 +0100697 return true;
698 default:
699 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700700 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000701
Narayan Kamath8508e372015-05-06 14:55:43 +0100702 UNREACHABLE();
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700703}
704
705/* Return whether the pointed-at modified-UTF-8 encoded character is
706 * valid as part of a member name, updating the pointer to point past
707 * the consumed character. This will consume two encoded UTF-16 code
708 * points if the character is encoded as a surrogate pair. Also, if
709 * this function returns false, then the given pointer may only have
710 * been partially advanced.
711 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700712static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700713 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700714 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700715 // It's low-ascii, so check the table.
716 uint32_t wordIdx = c >> 5;
717 uint32_t bitIdx = c & 0x1f;
718 (*pUtf8Ptr)++;
719 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
720 }
721
722 // It's a multibyte encoded character. Call a non-inline function
723 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800724 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
725}
726
727bool IsValidMemberName(const char* s) {
728 bool angle_name = false;
729
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700730 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800731 case '\0':
732 // The empty string is not a valid name.
733 return false;
734 case '<':
735 angle_name = true;
736 s++;
737 break;
738 }
739
740 while (true) {
741 switch (*s) {
742 case '\0':
743 return !angle_name;
744 case '>':
745 return angle_name && s[1] == '\0';
746 }
747
748 if (!IsValidPartOfMemberNameUtf8(&s)) {
749 return false;
750 }
751 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700752}
753
Elliott Hughes906e6852011-10-28 14:52:10 -0700754enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700755template<ClassNameType kType, char kSeparator>
756static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700757 int arrayCount = 0;
758 while (*s == '[') {
759 arrayCount++;
760 s++;
761 }
762
763 if (arrayCount > 255) {
764 // Arrays may have no more than 255 dimensions.
765 return false;
766 }
767
Ian Rogers7b078e82014-09-10 14:44:24 -0700768 ClassNameType type = kType;
769 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700770 /*
771 * If we're looking at an array of some sort, then it doesn't
772 * matter if what is being asked for is a class name; the
773 * format looks the same as a type descriptor in that case, so
774 * treat it as such.
775 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700776 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700777 }
778
Elliott Hughes906e6852011-10-28 14:52:10 -0700779 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700780 /*
781 * We are looking for a descriptor. Either validate it as a
782 * single-character primitive type, or continue on to check the
783 * embedded class name (bracketed by "L" and ";").
784 */
785 switch (*(s++)) {
786 case 'B':
787 case 'C':
788 case 'D':
789 case 'F':
790 case 'I':
791 case 'J':
792 case 'S':
793 case 'Z':
794 // These are all single-character descriptors for primitive types.
795 return (*s == '\0');
796 case 'V':
797 // Non-array void is valid, but you can't have an array of void.
798 return (arrayCount == 0) && (*s == '\0');
799 case 'L':
800 // Class name: Break out and continue below.
801 break;
802 default:
803 // Oddball descriptor character.
804 return false;
805 }
806 }
807
808 /*
809 * We just consumed the 'L' that introduces a class name as part
810 * of a type descriptor, or we are looking for an unadorned class
811 * name.
812 */
813
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700814 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700815 for (;;) {
816 uint8_t c = (uint8_t) *s;
817 switch (c) {
818 case '\0':
819 /*
820 * Premature end for a type descriptor, but valid for
821 * a class name as long as we haven't encountered an
822 * empty component (including the degenerate case of
823 * the empty string "").
824 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700825 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700826 case ';':
827 /*
828 * Invalid character for a class name, but the
829 * legitimate end of a type descriptor. In the latter
830 * case, make sure that this is the end of the string
831 * and that it doesn't end with an empty component
832 * (including the degenerate case of "L;").
833 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700834 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700835 case '/':
836 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700837 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700838 // The wrong separator character.
839 return false;
840 }
841 if (sepOrFirst) {
842 // Separator at start or two separators in a row.
843 return false;
844 }
845 sepOrFirst = true;
846 s++;
847 break;
848 default:
jeffhao10037c82012-01-23 15:06:23 -0800849 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700850 return false;
851 }
852 sepOrFirst = false;
853 break;
854 }
855 }
856}
857
Elliott Hughes906e6852011-10-28 14:52:10 -0700858bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700859 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700860}
861
862bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700863 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700864}
865
866bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700867 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700868}
869
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700870void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700871 const char* p = s.data();
872 const char* end = p + s.size();
873 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800874 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700875 ++p;
876 } else {
877 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800878 while (++p != end && *p != separator) {
879 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700880 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700881 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700882 }
883 }
884}
885
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700886std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -0700887 std::string result;
888 unsigned int start_index = 0;
889 unsigned int end_index = s.size() - 1;
890
891 // Skip initial whitespace.
892 while (start_index < s.size()) {
893 if (!isspace(s[start_index])) {
894 break;
895 }
896 start_index++;
897 }
898
899 // Skip terminating whitespace.
900 while (end_index >= start_index) {
901 if (!isspace(s[end_index])) {
902 break;
903 }
904 end_index--;
905 }
906
907 // All spaces, no beef.
908 if (end_index < start_index) {
909 return "";
910 }
911 // Start_index is the first non-space, end_index is the last one.
912 return s.substr(start_index, end_index - start_index + 1);
913}
914
Elliott Hughes48436bb2012-02-07 15:23:28 -0800915template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700916std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800917 if (strings.empty()) {
918 return "";
919 }
920
921 std::string result(strings[0]);
922 for (size_t i = 1; i < strings.size(); ++i) {
923 result += separator;
924 result += strings[i];
925 }
926 return result;
927}
928
929// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700930template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
931template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -0800932
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800933bool StartsWith(const std::string& s, const char* prefix) {
934 return s.compare(0, strlen(prefix), prefix) == 0;
935}
936
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700937bool EndsWith(const std::string& s, const char* suffix) {
938 size_t suffix_length = strlen(suffix);
939 size_t string_length = s.size();
940 if (suffix_length > string_length) {
941 return false;
942 }
943 size_t offset = string_length - suffix_length;
944 return s.compare(offset, suffix_length, suffix) == 0;
945}
946
Elliott Hughes22869a92012-03-27 14:08:24 -0700947void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700948 int hasAt = 0;
949 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700950 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700951 while (*s) {
952 if (*s == '.') {
953 hasDot = 1;
954 } else if (*s == '@') {
955 hasAt = 1;
956 }
957 s++;
958 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700959 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700960 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700961 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700962 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700963 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700964 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800965#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700966 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800967 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700968 strncpy(buf, s, sizeof(buf)-1);
969 buf[sizeof(buf)-1] = '\0';
970 errno = pthread_setname_np(pthread_self(), buf);
971 if (errno != 0) {
972 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
973 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800974#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700975 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700976#endif
977}
978
Brian Carlstrom29212012013-09-12 22:18:30 -0700979void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
980 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700981 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700982 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700983 return;
984 }
985 // Skip the command, which may contain spaces.
986 stats = stats.substr(stats.find(')') + 2);
987 // Extract the three fields we care about.
988 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700989 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700990 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700991 *utime = strtoull(fields[11].c_str(), nullptr, 10);
992 *stime = strtoull(fields[12].c_str(), nullptr, 10);
993 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700994}
995
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700996std::string GetSchedulerGroupName(pid_t tid) {
997 // /proc/<pid>/cgroup looks like this:
998 // 2:devices:/
999 // 1:cpuacct,cpu:/
1000 // We want the third field from the line whose second field contains the "cpu" token.
1001 std::string cgroup_file;
1002 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1003 return "";
1004 }
1005 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001006 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001007 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1008 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001009 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001010 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001011 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001012 for (size_t j = 0; j < cgroups.size(); ++j) {
1013 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001014 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001015 }
1016 }
1017 }
1018 return "";
1019}
1020
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001021const char* GetAndroidRoot() {
1022 const char* android_root = getenv("ANDROID_ROOT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001023 if (android_root == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001024 if (OS::DirectoryExists("/system")) {
1025 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001026 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001027 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1028 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001029 }
1030 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001031 if (!OS::DirectoryExists(android_root)) {
1032 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001033 return "";
1034 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001035 return android_root;
1036}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001037
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001038const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001039 std::string error_msg;
1040 const char* dir = GetAndroidDataSafe(&error_msg);
1041 if (dir != nullptr) {
1042 return dir;
1043 } else {
1044 LOG(FATAL) << error_msg;
1045 return "";
1046 }
1047}
1048
1049const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001050 const char* android_data = getenv("ANDROID_DATA");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001051 if (android_data == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001052 if (OS::DirectoryExists("/data")) {
1053 android_data = "/data";
1054 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001055 *error_msg = "ANDROID_DATA not set and /data does not exist";
1056 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001057 }
1058 }
1059 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001060 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1061 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001062 }
1063 return android_data;
1064}
1065
Alex Lighta59dd802014-07-02 16:28:08 -07001066void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001067 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001068 CHECK(subdir != nullptr);
1069 std::string error_msg;
1070 const char* android_data = GetAndroidDataSafe(&error_msg);
1071 if (android_data == nullptr) {
1072 *have_android_data = false;
1073 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001074 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001075 return;
1076 } else {
1077 *have_android_data = true;
1078 }
1079 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1080 *dalvik_cache = dalvik_cache_root + subdir;
1081 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001082 *is_global_cache = strcmp(android_data, "/data") == 0;
1083 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001084 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1085 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1086 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1087 }
1088}
1089
Andreas Gampe40da2862015-02-27 12:49:04 -08001090static std::string GetDalvikCacheImpl(const char* subdir,
1091 const bool create_if_absent,
1092 const bool abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001093 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001094 const char* android_data = GetAndroidData();
1095 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001096 const std::string dalvik_cache = dalvik_cache_root + subdir;
Andreas Gampe40da2862015-02-27 12:49:04 -08001097 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1098 if (!create_if_absent) {
1099 // TODO: Check callers. Traditional behavior is to not to abort, even when abort_on_error.
1100 return "";
1101 }
1102
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001103 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
Andreas Gampe40da2862015-02-27 12:49:04 -08001104 if (strcmp(android_data, "/data") == 0) {
1105 if (abort_on_error) {
1106 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache
1107 << ", cannot create /data dalvik-cache.";
1108 UNREACHABLE();
Narayan Kamath11d9f062014-04-23 20:24:57 +01001109 }
Andreas Gampe40da2862015-02-27 12:49:04 -08001110 return "";
1111 }
1112
1113 int result = mkdir(dalvik_cache_root.c_str(), 0700);
1114 if (result != 0 && errno != EEXIST) {
1115 if (abort_on_error) {
1116 PLOG(FATAL) << "Failed to create dalvik-cache root directory " << dalvik_cache_root;
1117 UNREACHABLE();
1118 }
1119 return "";
1120 }
1121
1122 result = mkdir(dalvik_cache.c_str(), 0700);
1123 if (result != 0) {
1124 if (abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001125 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Andreas Gampe40da2862015-02-27 12:49:04 -08001126 UNREACHABLE();
Brian Carlstroma9f19782011-10-13 00:14:47 -07001127 }
Brian Carlstroma9f19782011-10-13 00:14:47 -07001128 return "";
1129 }
1130 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001131 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001132}
1133
Andreas Gampe40da2862015-02-27 12:49:04 -08001134std::string GetDalvikCache(const char* subdir, const bool create_if_absent) {
1135 return GetDalvikCacheImpl(subdir, create_if_absent, false);
1136}
1137
1138std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1139 return GetDalvikCacheImpl(subdir, create_if_absent, true);
1140}
1141
Alex Lighta59dd802014-07-02 16:28:08 -07001142bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1143 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001144 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001145 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1146 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001147 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001148 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001149 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001150 cache_file += "/";
1151 cache_file += DexFile::kClassesDex;
1152 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001153 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001154 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1155 return true;
1156}
1157
1158std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1159 std::string ret;
1160 std::string error_msg;
1161 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1162 LOG(FATAL) << error_msg;
1163 }
1164 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001165}
1166
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001167static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001168 // in = /foo/bar/baz
1169 // out = /foo/bar/<isa>/baz
1170 size_t pos = filename->rfind('/');
1171 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1172 filename->insert(pos, "/", 1);
1173 filename->insert(pos + 1, GetInstructionSetString(isa));
1174}
1175
1176std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1177 // location = /system/framework/boot.art
1178 // filename = /system/framework/<isa>/boot.art
1179 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001180 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001181 return filename;
1182}
1183
Calin Juravle2e2db782016-02-23 12:00:03 +00001184int ExecAndReturnCode(std::vector<std::string>& arg_vector, std::string* error_msg) {
Brian Carlstrom6449c622014-02-10 23:48:36 -08001185 const std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom6449c622014-02-10 23:48:36 -08001186 CHECK_GE(arg_vector.size(), 1U) << command_line;
1187
1188 // Convert the args to char pointers.
1189 const char* program = arg_vector[0].c_str();
1190 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001191 for (size_t i = 0; i < arg_vector.size(); ++i) {
1192 const std::string& arg = arg_vector[i];
1193 char* arg_str = const_cast<char*>(arg.c_str());
1194 CHECK(arg_str != nullptr) << i;
1195 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001196 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001197 args.push_back(nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001198
1199 // fork and exec
1200 pid_t pid = fork();
1201 if (pid == 0) {
1202 // no allocation allowed between fork and exec
1203
1204 // change process groups, so we don't get reaped by ProcessManager
1205 setpgid(0, 0);
1206
1207 execv(program, &args[0]);
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001208 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
Tobias Lindskogae35c372015-11-04 19:41:21 +01001209 // _exit to avoid atexit handlers in child.
1210 _exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001211 } else {
1212 if (pid == -1) {
1213 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1214 command_line.c_str(), strerror(errno));
Calin Juravle2e2db782016-02-23 12:00:03 +00001215 return -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001216 }
1217
1218 // wait for subprocess to finish
Calin Juravle2e2db782016-02-23 12:00:03 +00001219 int status = -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001220 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1221 if (got_pid != pid) {
1222 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1223 "wanted %d, got %d: %s",
1224 command_line.c_str(), pid, got_pid, strerror(errno));
Calin Juravle2e2db782016-02-23 12:00:03 +00001225 return -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001226 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001227 if (WIFEXITED(status)) {
1228 return WEXITSTATUS(status);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001229 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001230 return -1;
1231 }
1232}
1233
1234bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1235 int status = ExecAndReturnCode(arg_vector, error_msg);
1236 if (status != 0) {
1237 const std::string command_line(Join(arg_vector, ' '));
1238 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1239 command_line.c_str());
1240 return false;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001241 }
1242 return true;
1243}
1244
Calin Juravle5e2b9712015-12-18 14:10:00 +02001245bool FileExists(const std::string& filename) {
1246 struct stat buffer;
1247 return stat(filename.c_str(), &buffer) == 0;
1248}
1249
Calin Juravleb9c1b9b2016-03-17 17:07:52 +00001250bool FileExistsAndNotEmpty(const std::string& filename) {
1251 struct stat buffer;
1252 if (stat(filename.c_str(), &buffer) != 0) {
1253 return false;
1254 }
1255 return buffer.st_size > 0;
1256}
1257
Mathieu Chartier76433272014-09-26 14:32:37 -07001258std::string PrettyDescriptor(Primitive::Type type) {
1259 return PrettyDescriptor(Primitive::Descriptor(type));
1260}
1261
Andreas Gampe5073fed2015-08-10 11:40:25 -07001262static void DumpMethodCFGImpl(const DexFile* dex_file,
1263 uint32_t dex_method_idx,
1264 const DexFile::CodeItem* code_item,
1265 std::ostream& os) {
1266 os << "digraph {\n";
1267 os << " # /* " << PrettyMethod(dex_method_idx, *dex_file, true) << " */\n";
1268
1269 std::set<uint32_t> dex_pc_is_branch_target;
1270 {
1271 // Go and populate.
1272 const Instruction* inst = Instruction::At(code_item->insns_);
1273 for (uint32_t dex_pc = 0;
1274 dex_pc < code_item->insns_size_in_code_units_;
1275 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1276 if (inst->IsBranch()) {
1277 dex_pc_is_branch_target.insert(dex_pc + inst->GetTargetOffset());
1278 } else if (inst->IsSwitch()) {
1279 const uint16_t* insns = code_item->insns_ + dex_pc;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001280 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001281 const uint16_t* switch_insns = insns + switch_offset;
1282 uint32_t switch_count = switch_insns[1];
1283 int32_t targets_offset;
1284 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1285 /* 0=sig, 1=count, 2/3=firstKey */
1286 targets_offset = 4;
1287 } else {
1288 /* 0=sig, 1=count, 2..count*2 = keys */
1289 targets_offset = 2 + 2 * switch_count;
1290 }
1291 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001292 int32_t offset =
1293 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1294 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001295 dex_pc_is_branch_target.insert(dex_pc + offset);
1296 }
1297 }
1298 }
1299 }
1300
1301 // Create nodes for "basic blocks."
1302 std::map<uint32_t, uint32_t> dex_pc_to_node_id; // This only has entries for block starts.
1303 std::map<uint32_t, uint32_t> dex_pc_to_incl_id; // This has entries for all dex pcs.
1304
1305 {
1306 const Instruction* inst = Instruction::At(code_item->insns_);
1307 bool first_in_block = true;
1308 bool force_new_block = false;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001309 for (uint32_t dex_pc = 0;
1310 dex_pc < code_item->insns_size_in_code_units_;
1311 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001312 if (dex_pc == 0 ||
1313 (dex_pc_is_branch_target.find(dex_pc) != dex_pc_is_branch_target.end()) ||
1314 force_new_block) {
1315 uint32_t id = dex_pc_to_node_id.size();
1316 if (id > 0) {
1317 // End last node.
1318 os << "}\"];\n";
1319 }
1320 // Start next node.
1321 os << " node" << id << " [shape=record,label=\"{";
1322 dex_pc_to_node_id.insert(std::make_pair(dex_pc, id));
1323 first_in_block = true;
1324 force_new_block = false;
1325 }
1326
1327 // Register instruction.
1328 dex_pc_to_incl_id.insert(std::make_pair(dex_pc, dex_pc_to_node_id.size() - 1));
1329
1330 // Print instruction.
1331 if (!first_in_block) {
1332 os << " | ";
1333 } else {
1334 first_in_block = false;
1335 }
1336
1337 // Dump the instruction. Need to escape '"', '<', '>', '{' and '}'.
1338 os << "<" << "p" << dex_pc << ">";
1339 os << " 0x" << std::hex << dex_pc << std::dec << ": ";
1340 std::string inst_str = inst->DumpString(dex_file);
1341 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 -07001342 // we need to escape.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001343 while (cur_start != std::string::npos) {
1344 size_t next_escape = inst_str.find_first_of("\"{}<>", cur_start + 1);
1345 if (next_escape == std::string::npos) {
1346 os << inst_str.substr(cur_start, inst_str.size() - cur_start);
1347 break;
1348 } else {
1349 os << inst_str.substr(cur_start, next_escape - cur_start);
1350 // Escape all necessary characters.
1351 while (next_escape < inst_str.size()) {
1352 char c = inst_str.at(next_escape);
1353 if (c == '"' || c == '{' || c == '}' || c == '<' || c == '>') {
1354 os << '\\' << c;
1355 } else {
1356 break;
1357 }
1358 next_escape++;
1359 }
1360 if (next_escape >= inst_str.size()) {
1361 next_escape = std::string::npos;
1362 }
1363 cur_start = next_escape;
1364 }
1365 }
1366
1367 // Force a new block for some fall-throughs and some instructions that terminate the "local"
1368 // control flow.
1369 force_new_block = inst->IsSwitch() || inst->IsBasicBlockEnd();
1370 }
1371 // Close last node.
1372 if (dex_pc_to_node_id.size() > 0) {
1373 os << "}\"];\n";
1374 }
1375 }
1376
1377 // Create edges between them.
1378 {
1379 std::ostringstream regular_edges;
1380 std::ostringstream taken_edges;
1381 std::ostringstream exception_edges;
1382
1383 // Common set of exception edges.
1384 std::set<uint32_t> exception_targets;
1385
1386 // These blocks (given by the first dex pc) need exception per dex-pc handling in a second
1387 // pass. In the first pass we try and see whether we can use a common set of edges.
1388 std::set<uint32_t> blocks_with_detailed_exceptions;
1389
1390 {
1391 uint32_t last_node_id = std::numeric_limits<uint32_t>::max();
1392 uint32_t old_dex_pc = 0;
1393 uint32_t block_start_dex_pc = std::numeric_limits<uint32_t>::max();
1394 const Instruction* inst = Instruction::At(code_item->insns_);
1395 for (uint32_t dex_pc = 0;
1396 dex_pc < code_item->insns_size_in_code_units_;
1397 old_dex_pc = dex_pc, dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1398 {
1399 auto it = dex_pc_to_node_id.find(dex_pc);
1400 if (it != dex_pc_to_node_id.end()) {
1401 if (!exception_targets.empty()) {
1402 // It seems the last block had common exception handlers. Add the exception edges now.
1403 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1404 for (uint32_t handler_pc : exception_targets) {
1405 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1406 if (node_id_it != dex_pc_to_incl_id.end()) {
1407 exception_edges << " node" << node_id
1408 << " -> node" << node_id_it->second << ":p" << handler_pc
1409 << ";\n";
1410 }
1411 }
1412 exception_targets.clear();
1413 }
1414
1415 block_start_dex_pc = dex_pc;
1416
1417 // Seems to be a fall-through, connect to last_node_id. May be spurious edges for things
1418 // like switch data.
1419 uint32_t old_last = last_node_id;
1420 last_node_id = it->second;
1421 if (old_last != std::numeric_limits<uint32_t>::max()) {
1422 regular_edges << " node" << old_last << ":p" << old_dex_pc
1423 << " -> node" << last_node_id << ":p" << dex_pc
1424 << ";\n";
1425 }
1426 }
1427
1428 // Look at the exceptions of the first entry.
1429 CatchHandlerIterator catch_it(*code_item, dex_pc);
1430 for (; catch_it.HasNext(); catch_it.Next()) {
1431 exception_targets.insert(catch_it.GetHandlerAddress());
1432 }
1433 }
1434
1435 // Handle instruction.
1436
1437 // Branch: something with at most two targets.
1438 if (inst->IsBranch()) {
1439 const int32_t offset = inst->GetTargetOffset();
1440 const bool conditional = !inst->IsUnconditional();
1441
1442 auto target_it = dex_pc_to_node_id.find(dex_pc + offset);
1443 if (target_it != dex_pc_to_node_id.end()) {
1444 taken_edges << " node" << last_node_id << ":p" << dex_pc
1445 << " -> node" << target_it->second << ":p" << (dex_pc + offset)
1446 << ";\n";
1447 }
1448 if (!conditional) {
1449 // No fall-through.
1450 last_node_id = std::numeric_limits<uint32_t>::max();
1451 }
1452 } else if (inst->IsSwitch()) {
1453 // TODO: Iterate through all switch targets.
1454 const uint16_t* insns = code_item->insns_ + dex_pc;
1455 /* make sure the start of the switch is in range */
Andreas Gampe53de99c2015-08-17 13:43:55 -07001456 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001457 /* offset to switch table is a relative branch-style offset */
1458 const uint16_t* switch_insns = insns + switch_offset;
1459 uint32_t switch_count = switch_insns[1];
1460 int32_t targets_offset;
1461 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1462 /* 0=sig, 1=count, 2/3=firstKey */
1463 targets_offset = 4;
1464 } else {
1465 /* 0=sig, 1=count, 2..count*2 = keys */
1466 targets_offset = 2 + 2 * switch_count;
1467 }
1468 /* make sure the end of the switch is in range */
1469 /* verify each switch target */
1470 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001471 int32_t offset =
1472 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1473 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001474 int32_t abs_offset = dex_pc + offset;
1475 auto target_it = dex_pc_to_node_id.find(abs_offset);
1476 if (target_it != dex_pc_to_node_id.end()) {
1477 // TODO: value label.
1478 taken_edges << " node" << last_node_id << ":p" << dex_pc
1479 << " -> node" << target_it->second << ":p" << (abs_offset)
1480 << ";\n";
1481 }
1482 }
1483 }
1484
1485 // Exception edges. If this is not the first instruction in the block
1486 if (block_start_dex_pc != dex_pc) {
1487 std::set<uint32_t> current_handler_pcs;
1488 CatchHandlerIterator catch_it(*code_item, dex_pc);
1489 for (; catch_it.HasNext(); catch_it.Next()) {
1490 current_handler_pcs.insert(catch_it.GetHandlerAddress());
1491 }
1492 if (current_handler_pcs != exception_targets) {
1493 exception_targets.clear(); // Clear so we don't do something at the end.
1494 blocks_with_detailed_exceptions.insert(block_start_dex_pc);
1495 }
1496 }
1497
1498 if (inst->IsReturn() ||
1499 (inst->Opcode() == Instruction::THROW) ||
1500 (inst->IsBranch() && inst->IsUnconditional())) {
1501 // No fall-through.
1502 last_node_id = std::numeric_limits<uint32_t>::max();
1503 }
1504 }
1505 // Finish up the last block, if it had common exceptions.
1506 if (!exception_targets.empty()) {
1507 // It seems the last block had common exception handlers. Add the exception edges now.
1508 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1509 for (uint32_t handler_pc : exception_targets) {
1510 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1511 if (node_id_it != dex_pc_to_incl_id.end()) {
1512 exception_edges << " node" << node_id
1513 << " -> node" << node_id_it->second << ":p" << handler_pc
1514 << ";\n";
1515 }
1516 }
1517 exception_targets.clear();
1518 }
1519 }
1520
1521 // Second pass for detailed exception blocks.
1522 // TODO
1523 // Exception edges. If this is not the first instruction in the block
1524 for (uint32_t dex_pc : blocks_with_detailed_exceptions) {
1525 const Instruction* inst = Instruction::At(&code_item->insns_[dex_pc]);
1526 uint32_t this_node_id = dex_pc_to_incl_id.find(dex_pc)->second;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001527 while (true) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001528 CatchHandlerIterator catch_it(*code_item, dex_pc);
1529 if (catch_it.HasNext()) {
1530 std::set<uint32_t> handled_targets;
1531 for (; catch_it.HasNext(); catch_it.Next()) {
1532 uint32_t handler_pc = catch_it.GetHandlerAddress();
1533 auto it = handled_targets.find(handler_pc);
1534 if (it == handled_targets.end()) {
1535 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1536 if (node_id_it != dex_pc_to_incl_id.end()) {
1537 exception_edges << " node" << this_node_id << ":p" << dex_pc
1538 << " -> node" << node_id_it->second << ":p" << handler_pc
1539 << ";\n";
1540 }
1541
1542 // Mark as done.
1543 handled_targets.insert(handler_pc);
1544 }
1545 }
1546 }
1547 if (inst->IsBasicBlockEnd()) {
1548 break;
1549 }
1550
Andreas Gampe53de99c2015-08-17 13:43:55 -07001551 // Loop update. Have a break-out if the next instruction is a branch target and thus in
1552 // another block.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001553 dex_pc += inst->SizeInCodeUnits();
1554 if (dex_pc >= code_item->insns_size_in_code_units_) {
1555 break;
1556 }
1557 if (dex_pc_to_node_id.find(dex_pc) != dex_pc_to_node_id.end()) {
1558 break;
1559 }
1560 inst = inst->Next();
1561 }
1562 }
1563
1564 // Write out the sub-graphs to make edges styled.
1565 os << "\n";
1566 os << " subgraph regular_edges {\n";
1567 os << " edge [color=\"#000000\",weight=.3,len=3];\n\n";
1568 os << " " << regular_edges.str() << "\n";
1569 os << " }\n\n";
1570
1571 os << " subgraph taken_edges {\n";
1572 os << " edge [color=\"#00FF00\",weight=.3,len=3];\n\n";
1573 os << " " << taken_edges.str() << "\n";
1574 os << " }\n\n";
1575
1576 os << " subgraph exception_edges {\n";
1577 os << " edge [color=\"#FF0000\",weight=.3,len=3];\n\n";
1578 os << " " << exception_edges.str() << "\n";
1579 os << " }\n\n";
1580 }
1581
1582 os << "}\n";
1583}
1584
1585void DumpMethodCFG(ArtMethod* method, std::ostream& os) {
1586 const DexFile* dex_file = method->GetDexFile();
1587 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1588
1589 DumpMethodCFGImpl(dex_file, method->GetDexMethodIndex(), code_item, os);
1590}
1591
1592void DumpMethodCFG(const DexFile* dex_file, uint32_t dex_method_idx, std::ostream& os) {
1593 // This is painful, we need to find the code item. That means finding the class, and then
1594 // iterating the table.
1595 if (dex_method_idx >= dex_file->NumMethodIds()) {
1596 os << "Could not find method-idx.";
1597 return;
1598 }
1599 const DexFile::MethodId& method_id = dex_file->GetMethodId(dex_method_idx);
1600
1601 const DexFile::ClassDef* class_def = dex_file->FindClassDef(method_id.class_idx_);
1602 if (class_def == nullptr) {
1603 os << "Could not find class-def.";
1604 return;
1605 }
1606
1607 const uint8_t* class_data = dex_file->GetClassData(*class_def);
1608 if (class_data == nullptr) {
1609 os << "No class data.";
1610 return;
1611 }
1612
1613 ClassDataItemIterator it(*dex_file, class_data);
1614 // Skip fields
1615 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
1616 it.Next();
1617 }
1618
1619 // Find method, and dump it.
1620 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
1621 uint32_t method_idx = it.GetMemberIndex();
1622 if (method_idx == dex_method_idx) {
1623 DumpMethodCFGImpl(dex_file, dex_method_idx, it.GetMethodCodeItem(), os);
1624 return;
1625 }
1626 it.Next();
1627 }
1628
1629 // Otherwise complain.
1630 os << "Something went wrong, didn't find the method in the class data.";
1631}
1632
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001633static void ParseStringAfterChar(const std::string& s,
1634 char c,
1635 std::string* parsed_value,
1636 UsageFn Usage) {
1637 std::string::size_type colon = s.find(c);
1638 if (colon == std::string::npos) {
1639 Usage("Missing char %c in option %s\n", c, s.c_str());
1640 }
1641 // Add one to remove the char we were trimming until.
1642 *parsed_value = s.substr(colon + 1);
1643}
1644
1645void ParseDouble(const std::string& option,
1646 char after_char,
1647 double min,
1648 double max,
1649 double* parsed_value,
1650 UsageFn Usage) {
1651 std::string substring;
1652 ParseStringAfterChar(option, after_char, &substring, Usage);
1653 bool sane_val = true;
1654 double value;
1655 if ((false)) {
1656 // TODO: this doesn't seem to work on the emulator. b/15114595
1657 std::stringstream iss(substring);
1658 iss >> value;
1659 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
1660 sane_val = iss.eof() && (value >= min) && (value <= max);
1661 } else {
1662 char* end = nullptr;
1663 value = strtod(substring.c_str(), &end);
1664 sane_val = *end == '\0' && value >= min && value <= max;
1665 }
1666 if (!sane_val) {
1667 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
1668 }
1669 *parsed_value = value;
1670}
1671
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001672int64_t GetFileSizeBytes(const std::string& filename) {
1673 struct stat stat_buf;
1674 int rc = stat(filename.c_str(), &stat_buf);
1675 return rc == 0 ? stat_buf.st_size : -1;
1676}
1677
Mathieu Chartier4d87df62016-01-07 15:14:19 -08001678void SleepForever() {
1679 while (true) {
1680 usleep(1000000);
1681 }
1682}
1683
Elliott Hughes42ee1422011-09-06 12:33:32 -07001684} // namespace art