blob: 313190c84db48ab1f9996963171f2fcb210517a0 [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
Richard Uhler55b58b62016-08-12 09:05:13 -07001090std::string GetDalvikCache(const char* subdir) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001091 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001092 const char* android_data = GetAndroidData();
1093 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001094 const std::string dalvik_cache = dalvik_cache_root + subdir;
Andreas Gampe40da2862015-02-27 12:49:04 -08001095 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
Richard Uhler55b58b62016-08-12 09:05:13 -07001096 // TODO: Check callers. Traditional behavior is to not abort.
1097 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001098 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001099 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001100}
1101
Alex Lighta59dd802014-07-02 16:28:08 -07001102bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1103 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001104 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001105 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1106 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001107 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001108 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001109 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001110 cache_file += "/";
1111 cache_file += DexFile::kClassesDex;
1112 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001113 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001114 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1115 return true;
1116}
1117
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001118static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001119 // in = /foo/bar/baz
1120 // out = /foo/bar/<isa>/baz
1121 size_t pos = filename->rfind('/');
1122 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1123 filename->insert(pos, "/", 1);
1124 filename->insert(pos + 1, GetInstructionSetString(isa));
1125}
1126
1127std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1128 // location = /system/framework/boot.art
1129 // filename = /system/framework/<isa>/boot.art
1130 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001131 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001132 return filename;
1133}
1134
Calin Juravle2e2db782016-02-23 12:00:03 +00001135int ExecAndReturnCode(std::vector<std::string>& arg_vector, std::string* error_msg) {
Brian Carlstrom6449c622014-02-10 23:48:36 -08001136 const std::string command_line(Join(arg_vector, ' '));
Brian Carlstrom6449c622014-02-10 23:48:36 -08001137 CHECK_GE(arg_vector.size(), 1U) << command_line;
1138
1139 // Convert the args to char pointers.
1140 const char* program = arg_vector[0].c_str();
1141 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001142 for (size_t i = 0; i < arg_vector.size(); ++i) {
1143 const std::string& arg = arg_vector[i];
1144 char* arg_str = const_cast<char*>(arg.c_str());
1145 CHECK(arg_str != nullptr) << i;
1146 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001147 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001148 args.push_back(nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001149
1150 // fork and exec
1151 pid_t pid = fork();
1152 if (pid == 0) {
1153 // no allocation allowed between fork and exec
1154
1155 // change process groups, so we don't get reaped by ProcessManager
1156 setpgid(0, 0);
1157
David Sehrd106d9f2016-08-16 19:22:57 -07001158 // (b/30160149): protect subprocesses from modifications to LD_LIBRARY_PATH, etc.
1159 // Use the snapshot of the environment from the time the runtime was created.
1160 char** envp = (Runtime::Current() == nullptr) ? nullptr : Runtime::Current()->GetEnvSnapshot();
1161 if (envp == nullptr) {
1162 execv(program, &args[0]);
1163 } else {
1164 execve(program, &args[0], envp);
1165 }
1166 PLOG(ERROR) << "Failed to execve(" << command_line << ")";
Tobias Lindskogae35c372015-11-04 19:41:21 +01001167 // _exit to avoid atexit handlers in child.
1168 _exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001169 } else {
1170 if (pid == -1) {
1171 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1172 command_line.c_str(), strerror(errno));
Calin Juravle2e2db782016-02-23 12:00:03 +00001173 return -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001174 }
1175
1176 // wait for subprocess to finish
Calin Juravle2e2db782016-02-23 12:00:03 +00001177 int status = -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001178 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1179 if (got_pid != pid) {
1180 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1181 "wanted %d, got %d: %s",
1182 command_line.c_str(), pid, got_pid, strerror(errno));
Calin Juravle2e2db782016-02-23 12:00:03 +00001183 return -1;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001184 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001185 if (WIFEXITED(status)) {
1186 return WEXITSTATUS(status);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001187 }
Calin Juravle2e2db782016-02-23 12:00:03 +00001188 return -1;
1189 }
1190}
1191
1192bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1193 int status = ExecAndReturnCode(arg_vector, error_msg);
1194 if (status != 0) {
1195 const std::string command_line(Join(arg_vector, ' '));
1196 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1197 command_line.c_str());
1198 return false;
Brian Carlstrom6449c622014-02-10 23:48:36 -08001199 }
1200 return true;
1201}
1202
Calin Juravle5e2b9712015-12-18 14:10:00 +02001203bool FileExists(const std::string& filename) {
1204 struct stat buffer;
1205 return stat(filename.c_str(), &buffer) == 0;
1206}
1207
Calin Juravleb9c1b9b2016-03-17 17:07:52 +00001208bool FileExistsAndNotEmpty(const std::string& filename) {
1209 struct stat buffer;
1210 if (stat(filename.c_str(), &buffer) != 0) {
1211 return false;
1212 }
1213 return buffer.st_size > 0;
1214}
1215
Mathieu Chartier76433272014-09-26 14:32:37 -07001216std::string PrettyDescriptor(Primitive::Type type) {
1217 return PrettyDescriptor(Primitive::Descriptor(type));
1218}
1219
Andreas Gampe5073fed2015-08-10 11:40:25 -07001220static void DumpMethodCFGImpl(const DexFile* dex_file,
1221 uint32_t dex_method_idx,
1222 const DexFile::CodeItem* code_item,
1223 std::ostream& os) {
1224 os << "digraph {\n";
1225 os << " # /* " << PrettyMethod(dex_method_idx, *dex_file, true) << " */\n";
1226
1227 std::set<uint32_t> dex_pc_is_branch_target;
1228 {
1229 // Go and populate.
1230 const Instruction* inst = Instruction::At(code_item->insns_);
1231 for (uint32_t dex_pc = 0;
1232 dex_pc < code_item->insns_size_in_code_units_;
1233 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1234 if (inst->IsBranch()) {
1235 dex_pc_is_branch_target.insert(dex_pc + inst->GetTargetOffset());
1236 } else if (inst->IsSwitch()) {
1237 const uint16_t* insns = code_item->insns_ + dex_pc;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001238 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001239 const uint16_t* switch_insns = insns + switch_offset;
1240 uint32_t switch_count = switch_insns[1];
1241 int32_t targets_offset;
1242 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1243 /* 0=sig, 1=count, 2/3=firstKey */
1244 targets_offset = 4;
1245 } else {
1246 /* 0=sig, 1=count, 2..count*2 = keys */
1247 targets_offset = 2 + 2 * switch_count;
1248 }
1249 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001250 int32_t offset =
1251 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1252 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001253 dex_pc_is_branch_target.insert(dex_pc + offset);
1254 }
1255 }
1256 }
1257 }
1258
1259 // Create nodes for "basic blocks."
1260 std::map<uint32_t, uint32_t> dex_pc_to_node_id; // This only has entries for block starts.
1261 std::map<uint32_t, uint32_t> dex_pc_to_incl_id; // This has entries for all dex pcs.
1262
1263 {
1264 const Instruction* inst = Instruction::At(code_item->insns_);
1265 bool first_in_block = true;
1266 bool force_new_block = false;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001267 for (uint32_t dex_pc = 0;
1268 dex_pc < code_item->insns_size_in_code_units_;
1269 dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001270 if (dex_pc == 0 ||
1271 (dex_pc_is_branch_target.find(dex_pc) != dex_pc_is_branch_target.end()) ||
1272 force_new_block) {
1273 uint32_t id = dex_pc_to_node_id.size();
1274 if (id > 0) {
1275 // End last node.
1276 os << "}\"];\n";
1277 }
1278 // Start next node.
1279 os << " node" << id << " [shape=record,label=\"{";
1280 dex_pc_to_node_id.insert(std::make_pair(dex_pc, id));
1281 first_in_block = true;
1282 force_new_block = false;
1283 }
1284
1285 // Register instruction.
1286 dex_pc_to_incl_id.insert(std::make_pair(dex_pc, dex_pc_to_node_id.size() - 1));
1287
1288 // Print instruction.
1289 if (!first_in_block) {
1290 os << " | ";
1291 } else {
1292 first_in_block = false;
1293 }
1294
1295 // Dump the instruction. Need to escape '"', '<', '>', '{' and '}'.
1296 os << "<" << "p" << dex_pc << ">";
1297 os << " 0x" << std::hex << dex_pc << std::dec << ": ";
1298 std::string inst_str = inst->DumpString(dex_file);
1299 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 -07001300 // we need to escape.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001301 while (cur_start != std::string::npos) {
1302 size_t next_escape = inst_str.find_first_of("\"{}<>", cur_start + 1);
1303 if (next_escape == std::string::npos) {
1304 os << inst_str.substr(cur_start, inst_str.size() - cur_start);
1305 break;
1306 } else {
1307 os << inst_str.substr(cur_start, next_escape - cur_start);
1308 // Escape all necessary characters.
1309 while (next_escape < inst_str.size()) {
1310 char c = inst_str.at(next_escape);
1311 if (c == '"' || c == '{' || c == '}' || c == '<' || c == '>') {
1312 os << '\\' << c;
1313 } else {
1314 break;
1315 }
1316 next_escape++;
1317 }
1318 if (next_escape >= inst_str.size()) {
1319 next_escape = std::string::npos;
1320 }
1321 cur_start = next_escape;
1322 }
1323 }
1324
1325 // Force a new block for some fall-throughs and some instructions that terminate the "local"
1326 // control flow.
1327 force_new_block = inst->IsSwitch() || inst->IsBasicBlockEnd();
1328 }
1329 // Close last node.
1330 if (dex_pc_to_node_id.size() > 0) {
1331 os << "}\"];\n";
1332 }
1333 }
1334
1335 // Create edges between them.
1336 {
1337 std::ostringstream regular_edges;
1338 std::ostringstream taken_edges;
1339 std::ostringstream exception_edges;
1340
1341 // Common set of exception edges.
1342 std::set<uint32_t> exception_targets;
1343
1344 // These blocks (given by the first dex pc) need exception per dex-pc handling in a second
1345 // pass. In the first pass we try and see whether we can use a common set of edges.
1346 std::set<uint32_t> blocks_with_detailed_exceptions;
1347
1348 {
1349 uint32_t last_node_id = std::numeric_limits<uint32_t>::max();
1350 uint32_t old_dex_pc = 0;
1351 uint32_t block_start_dex_pc = std::numeric_limits<uint32_t>::max();
1352 const Instruction* inst = Instruction::At(code_item->insns_);
1353 for (uint32_t dex_pc = 0;
1354 dex_pc < code_item->insns_size_in_code_units_;
1355 old_dex_pc = dex_pc, dex_pc += inst->SizeInCodeUnits(), inst = inst->Next()) {
1356 {
1357 auto it = dex_pc_to_node_id.find(dex_pc);
1358 if (it != dex_pc_to_node_id.end()) {
1359 if (!exception_targets.empty()) {
1360 // It seems the last block had common exception handlers. Add the exception edges now.
1361 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1362 for (uint32_t handler_pc : exception_targets) {
1363 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1364 if (node_id_it != dex_pc_to_incl_id.end()) {
1365 exception_edges << " node" << node_id
1366 << " -> node" << node_id_it->second << ":p" << handler_pc
1367 << ";\n";
1368 }
1369 }
1370 exception_targets.clear();
1371 }
1372
1373 block_start_dex_pc = dex_pc;
1374
1375 // Seems to be a fall-through, connect to last_node_id. May be spurious edges for things
1376 // like switch data.
1377 uint32_t old_last = last_node_id;
1378 last_node_id = it->second;
1379 if (old_last != std::numeric_limits<uint32_t>::max()) {
1380 regular_edges << " node" << old_last << ":p" << old_dex_pc
1381 << " -> node" << last_node_id << ":p" << dex_pc
1382 << ";\n";
1383 }
1384 }
1385
1386 // Look at the exceptions of the first entry.
1387 CatchHandlerIterator catch_it(*code_item, dex_pc);
1388 for (; catch_it.HasNext(); catch_it.Next()) {
1389 exception_targets.insert(catch_it.GetHandlerAddress());
1390 }
1391 }
1392
1393 // Handle instruction.
1394
1395 // Branch: something with at most two targets.
1396 if (inst->IsBranch()) {
1397 const int32_t offset = inst->GetTargetOffset();
1398 const bool conditional = !inst->IsUnconditional();
1399
1400 auto target_it = dex_pc_to_node_id.find(dex_pc + offset);
1401 if (target_it != dex_pc_to_node_id.end()) {
1402 taken_edges << " node" << last_node_id << ":p" << dex_pc
1403 << " -> node" << target_it->second << ":p" << (dex_pc + offset)
1404 << ";\n";
1405 }
1406 if (!conditional) {
1407 // No fall-through.
1408 last_node_id = std::numeric_limits<uint32_t>::max();
1409 }
1410 } else if (inst->IsSwitch()) {
1411 // TODO: Iterate through all switch targets.
1412 const uint16_t* insns = code_item->insns_ + dex_pc;
1413 /* make sure the start of the switch is in range */
Andreas Gampe53de99c2015-08-17 13:43:55 -07001414 int32_t switch_offset = insns[1] | (static_cast<int32_t>(insns[2]) << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001415 /* offset to switch table is a relative branch-style offset */
1416 const uint16_t* switch_insns = insns + switch_offset;
1417 uint32_t switch_count = switch_insns[1];
1418 int32_t targets_offset;
1419 if ((*insns & 0xff) == Instruction::PACKED_SWITCH) {
1420 /* 0=sig, 1=count, 2/3=firstKey */
1421 targets_offset = 4;
1422 } else {
1423 /* 0=sig, 1=count, 2..count*2 = keys */
1424 targets_offset = 2 + 2 * switch_count;
1425 }
1426 /* make sure the end of the switch is in range */
1427 /* verify each switch target */
1428 for (uint32_t targ = 0; targ < switch_count; targ++) {
Andreas Gampe53de99c2015-08-17 13:43:55 -07001429 int32_t offset =
1430 static_cast<int32_t>(switch_insns[targets_offset + targ * 2]) |
1431 static_cast<int32_t>(switch_insns[targets_offset + targ * 2 + 1] << 16);
Andreas Gampe5073fed2015-08-10 11:40:25 -07001432 int32_t abs_offset = dex_pc + offset;
1433 auto target_it = dex_pc_to_node_id.find(abs_offset);
1434 if (target_it != dex_pc_to_node_id.end()) {
1435 // TODO: value label.
1436 taken_edges << " node" << last_node_id << ":p" << dex_pc
1437 << " -> node" << target_it->second << ":p" << (abs_offset)
1438 << ";\n";
1439 }
1440 }
1441 }
1442
1443 // Exception edges. If this is not the first instruction in the block
1444 if (block_start_dex_pc != dex_pc) {
1445 std::set<uint32_t> current_handler_pcs;
1446 CatchHandlerIterator catch_it(*code_item, dex_pc);
1447 for (; catch_it.HasNext(); catch_it.Next()) {
1448 current_handler_pcs.insert(catch_it.GetHandlerAddress());
1449 }
1450 if (current_handler_pcs != exception_targets) {
1451 exception_targets.clear(); // Clear so we don't do something at the end.
1452 blocks_with_detailed_exceptions.insert(block_start_dex_pc);
1453 }
1454 }
1455
1456 if (inst->IsReturn() ||
1457 (inst->Opcode() == Instruction::THROW) ||
1458 (inst->IsBranch() && inst->IsUnconditional())) {
1459 // No fall-through.
1460 last_node_id = std::numeric_limits<uint32_t>::max();
1461 }
1462 }
1463 // Finish up the last block, if it had common exceptions.
1464 if (!exception_targets.empty()) {
1465 // It seems the last block had common exception handlers. Add the exception edges now.
1466 uint32_t node_id = dex_pc_to_node_id.find(block_start_dex_pc)->second;
1467 for (uint32_t handler_pc : exception_targets) {
1468 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1469 if (node_id_it != dex_pc_to_incl_id.end()) {
1470 exception_edges << " node" << node_id
1471 << " -> node" << node_id_it->second << ":p" << handler_pc
1472 << ";\n";
1473 }
1474 }
1475 exception_targets.clear();
1476 }
1477 }
1478
1479 // Second pass for detailed exception blocks.
1480 // TODO
1481 // Exception edges. If this is not the first instruction in the block
1482 for (uint32_t dex_pc : blocks_with_detailed_exceptions) {
1483 const Instruction* inst = Instruction::At(&code_item->insns_[dex_pc]);
1484 uint32_t this_node_id = dex_pc_to_incl_id.find(dex_pc)->second;
Andreas Gampe53de99c2015-08-17 13:43:55 -07001485 while (true) {
Andreas Gampe5073fed2015-08-10 11:40:25 -07001486 CatchHandlerIterator catch_it(*code_item, dex_pc);
1487 if (catch_it.HasNext()) {
1488 std::set<uint32_t> handled_targets;
1489 for (; catch_it.HasNext(); catch_it.Next()) {
1490 uint32_t handler_pc = catch_it.GetHandlerAddress();
1491 auto it = handled_targets.find(handler_pc);
1492 if (it == handled_targets.end()) {
1493 auto node_id_it = dex_pc_to_incl_id.find(handler_pc);
1494 if (node_id_it != dex_pc_to_incl_id.end()) {
1495 exception_edges << " node" << this_node_id << ":p" << dex_pc
1496 << " -> node" << node_id_it->second << ":p" << handler_pc
1497 << ";\n";
1498 }
1499
1500 // Mark as done.
1501 handled_targets.insert(handler_pc);
1502 }
1503 }
1504 }
1505 if (inst->IsBasicBlockEnd()) {
1506 break;
1507 }
1508
Andreas Gampe53de99c2015-08-17 13:43:55 -07001509 // Loop update. Have a break-out if the next instruction is a branch target and thus in
1510 // another block.
Andreas Gampe5073fed2015-08-10 11:40:25 -07001511 dex_pc += inst->SizeInCodeUnits();
1512 if (dex_pc >= code_item->insns_size_in_code_units_) {
1513 break;
1514 }
1515 if (dex_pc_to_node_id.find(dex_pc) != dex_pc_to_node_id.end()) {
1516 break;
1517 }
1518 inst = inst->Next();
1519 }
1520 }
1521
1522 // Write out the sub-graphs to make edges styled.
1523 os << "\n";
1524 os << " subgraph regular_edges {\n";
1525 os << " edge [color=\"#000000\",weight=.3,len=3];\n\n";
1526 os << " " << regular_edges.str() << "\n";
1527 os << " }\n\n";
1528
1529 os << " subgraph taken_edges {\n";
1530 os << " edge [color=\"#00FF00\",weight=.3,len=3];\n\n";
1531 os << " " << taken_edges.str() << "\n";
1532 os << " }\n\n";
1533
1534 os << " subgraph exception_edges {\n";
1535 os << " edge [color=\"#FF0000\",weight=.3,len=3];\n\n";
1536 os << " " << exception_edges.str() << "\n";
1537 os << " }\n\n";
1538 }
1539
1540 os << "}\n";
1541}
1542
1543void DumpMethodCFG(ArtMethod* method, std::ostream& os) {
1544 const DexFile* dex_file = method->GetDexFile();
1545 const DexFile::CodeItem* code_item = dex_file->GetCodeItem(method->GetCodeItemOffset());
1546
1547 DumpMethodCFGImpl(dex_file, method->GetDexMethodIndex(), code_item, os);
1548}
1549
1550void DumpMethodCFG(const DexFile* dex_file, uint32_t dex_method_idx, std::ostream& os) {
1551 // This is painful, we need to find the code item. That means finding the class, and then
1552 // iterating the table.
1553 if (dex_method_idx >= dex_file->NumMethodIds()) {
1554 os << "Could not find method-idx.";
1555 return;
1556 }
1557 const DexFile::MethodId& method_id = dex_file->GetMethodId(dex_method_idx);
1558
1559 const DexFile::ClassDef* class_def = dex_file->FindClassDef(method_id.class_idx_);
1560 if (class_def == nullptr) {
1561 os << "Could not find class-def.";
1562 return;
1563 }
1564
1565 const uint8_t* class_data = dex_file->GetClassData(*class_def);
1566 if (class_data == nullptr) {
1567 os << "No class data.";
1568 return;
1569 }
1570
1571 ClassDataItemIterator it(*dex_file, class_data);
1572 // Skip fields
1573 while (it.HasNextStaticField() || it.HasNextInstanceField()) {
1574 it.Next();
1575 }
1576
1577 // Find method, and dump it.
1578 while (it.HasNextDirectMethod() || it.HasNextVirtualMethod()) {
1579 uint32_t method_idx = it.GetMemberIndex();
1580 if (method_idx == dex_method_idx) {
1581 DumpMethodCFGImpl(dex_file, dex_method_idx, it.GetMethodCodeItem(), os);
1582 return;
1583 }
1584 it.Next();
1585 }
1586
1587 // Otherwise complain.
1588 os << "Something went wrong, didn't find the method in the class data.";
1589}
1590
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001591static void ParseStringAfterChar(const std::string& s,
1592 char c,
1593 std::string* parsed_value,
1594 UsageFn Usage) {
1595 std::string::size_type colon = s.find(c);
1596 if (colon == std::string::npos) {
1597 Usage("Missing char %c in option %s\n", c, s.c_str());
1598 }
1599 // Add one to remove the char we were trimming until.
1600 *parsed_value = s.substr(colon + 1);
1601}
1602
1603void ParseDouble(const std::string& option,
1604 char after_char,
1605 double min,
1606 double max,
1607 double* parsed_value,
1608 UsageFn Usage) {
1609 std::string substring;
1610 ParseStringAfterChar(option, after_char, &substring, Usage);
1611 bool sane_val = true;
1612 double value;
1613 if ((false)) {
1614 // TODO: this doesn't seem to work on the emulator. b/15114595
1615 std::stringstream iss(substring);
1616 iss >> value;
1617 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
1618 sane_val = iss.eof() && (value >= min) && (value <= max);
1619 } else {
1620 char* end = nullptr;
1621 value = strtod(substring.c_str(), &end);
1622 sane_val = *end == '\0' && value >= min && value <= max;
1623 }
1624 if (!sane_val) {
1625 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
1626 }
1627 *parsed_value = value;
1628}
1629
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001630int64_t GetFileSizeBytes(const std::string& filename) {
1631 struct stat stat_buf;
1632 int rc = stat(filename.c_str(), &stat_buf);
1633 return rc == 0 ? stat_buf.st_size : -1;
1634}
1635
Mathieu Chartier4d87df62016-01-07 15:14:19 -08001636void SleepForever() {
1637 while (true) {
1638 usleep(1000000);
1639 }
1640}
1641
Elliott Hughes42ee1422011-09-06 12:33:32 -07001642} // namespace art