blob: 2671b46bad9695ccc803f1d927280744db87f6f1 [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"
Brian Carlstrom6449c622014-02-10 23:48:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070031#include "dex_file-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070032#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070033#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "mirror/class_loader.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/object-inl.h"
36#include "mirror/object_array-inl.h"
37#include "mirror/string.h"
buzbeec143c552011-08-20 17:38:58 -070038#include "os.h"
Kenny Root067d20f2014-03-05 14:57:21 -080039#include "scoped_thread_state_change.h"
Ian Rogersa6724902013-09-23 09:23:37 -070040#include "utf-inl.h"
Elliott Hughes11e45072011-08-16 17:40:46 -070041
Elliott Hughes4ae722a2012-03-13 11:08:51 -070042#if defined(__APPLE__)
Brian Carlstrom7934ac22013-07-26 10:54:15 -070043#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
Elliott Hughesf1498432012-03-28 19:34:27 -070044#include <sys/syscall.h>
Elliott Hughes4ae722a2012-03-13 11:08:51 -070045#endif
46
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -070047#include <backtrace/Backtrace.h> // For DumpNativeStack.
Elliott Hughes46e251b2012-05-22 15:10:45 -070048
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
Andreas Gampe8e1cb912015-01-08 20:11:09 -080055#if defined(__linux__)
56static constexpr bool kUseAddr2line = !kIsTargetBuild;
57#endif
58
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080059pid_t GetTid() {
Brian Carlstromf3a26412012-08-24 11:06:02 -070060#if defined(__APPLE__)
61 uint64_t owner;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070062 CHECK_PTHREAD_CALL(pthread_threadid_np, (nullptr, &owner), __FUNCTION__); // Requires Mac OS 10.6
Brian Carlstromf3a26412012-08-24 11:06:02 -070063 return owner;
Elliott Hughes323aa862014-08-20 15:00:04 -070064#elif defined(__BIONIC__)
65 return gettid();
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080066#else
Elliott Hughes11d1b0c2012-01-23 16:57:47 -080067 return syscall(__NR_gettid);
68#endif
69}
70
Elliott Hughes289be852012-06-12 13:57:20 -070071std::string GetThreadName(pid_t tid) {
72 std::string result;
73 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -070074 result.resize(result.size() - 1); // Lose the trailing '\n'.
Elliott Hughes289be852012-06-12 13:57:20 -070075 } else {
76 result = "<unknown>";
77 }
78 return result;
79}
80
Elliott Hughes6d3fc562014-08-27 11:47:01 -070081void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
Elliott Hughese1884192012-04-23 12:38:15 -070082#if defined(__APPLE__)
Brian Carlstrom29212012013-09-12 22:18:30 -070083 *stack_size = pthread_get_stacksize_np(thread);
Ian Rogers120f1c72012-09-28 17:17:10 -070084 void* stack_addr = pthread_get_stackaddr_np(thread);
Elliott Hughese1884192012-04-23 12:38:15 -070085
86 // Check whether stack_addr is the base or end of the stack.
87 // (On Mac OS 10.7, it's the end.)
88 int stack_variable;
89 if (stack_addr > &stack_variable) {
Ian Rogers13735952014-10-08 12:43:28 -070090 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
Elliott Hughese1884192012-04-23 12:38:15 -070091 } else {
Brian Carlstrom29212012013-09-12 22:18:30 -070092 *stack_base = stack_addr;
Elliott Hughese1884192012-04-23 12:38:15 -070093 }
Elliott Hughes6d3fc562014-08-27 11:47:01 -070094
95 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
96 pthread_attr_t attributes;
97 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
98 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
99 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700100#else
101 pthread_attr_t attributes;
Ian Rogers120f1c72012-09-28 17:17:10 -0700102 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
Brian Carlstrom29212012013-09-12 22:18:30 -0700103 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
Elliott Hughes6d3fc562014-08-27 11:47:01 -0700104 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
Elliott Hughese1884192012-04-23 12:38:15 -0700105 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
Elliott Hughes839cc302014-08-28 10:24:44 -0700106
107#if defined(__GLIBC__)
108 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
109 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
110 // will be broken because we'll die long before we get close to 2GB.
111 bool is_main_thread = (::art::GetTid() == getpid());
112 if (is_main_thread) {
113 rlimit stack_limit;
114 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
115 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
116 }
117 if (stack_limit.rlim_cur == RLIM_INFINITY) {
118 size_t old_stack_size = *stack_size;
119
120 // Use the kernel default limit as our size, and adjust the base to match.
121 *stack_size = 8 * MB;
122 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
123
124 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
125 << " to " << PrettySize(*stack_size)
126 << " with base " << *stack_base;
127 }
128 }
129#endif
130
Elliott Hughese1884192012-04-23 12:38:15 -0700131#endif
132}
133
Elliott Hughesd92bec42011-09-02 17:04:36 -0700134bool ReadFileToString(const std::string& file_name, std::string* result) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800135 File file;
136 if (!file.Open(file_name, O_RDONLY)) {
Elliott Hughesd92bec42011-09-02 17:04:36 -0700137 return false;
138 }
buzbeec143c552011-08-20 17:38:58 -0700139
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700140 std::vector<char> buf(8 * KB);
buzbeec143c552011-08-20 17:38:58 -0700141 while (true) {
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800142 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[0], buf.size()));
Elliott Hughesd92bec42011-09-02 17:04:36 -0700143 if (n == -1) {
144 return false;
buzbeec143c552011-08-20 17:38:58 -0700145 }
Elliott Hughesd92bec42011-09-02 17:04:36 -0700146 if (n == 0) {
147 return true;
148 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700149 result->append(&buf[0], n);
buzbeec143c552011-08-20 17:38:58 -0700150 }
buzbeec143c552011-08-20 17:38:58 -0700151}
152
Andreas Gampea6dfdae2015-02-24 15:50:19 -0800153bool PrintFileToLog(const std::string& file_name, LogSeverity level) {
154 File file;
155 if (!file.Open(file_name, O_RDONLY)) {
156 return false;
157 }
158
159 constexpr size_t kBufSize = 256; // Small buffer. Avoid stack overflow and stack size warnings.
160 char buf[kBufSize + 1]; // +1 for terminator.
161 size_t filled_to = 0;
162 while (true) {
163 DCHECK_LT(filled_to, kBufSize);
164 int64_t n = TEMP_FAILURE_RETRY(read(file.Fd(), &buf[filled_to], kBufSize - filled_to));
165 if (n <= 0) {
166 // Print the rest of the buffer, if it exists.
167 if (filled_to > 0) {
168 buf[filled_to] = 0;
169 LOG(level) << buf;
170 }
171 return n == 0;
172 }
173 // Scan for '\n'.
174 size_t i = filled_to;
175 bool found_newline = false;
176 for (; i < filled_to + n; ++i) {
177 if (buf[i] == '\n') {
178 // Found a line break, that's something to print now.
179 buf[i] = 0;
180 LOG(level) << buf;
181 // Copy the rest to the front.
182 if (i + 1 < filled_to + n) {
183 memmove(&buf[0], &buf[i + 1], filled_to + n - i - 1);
184 filled_to = filled_to + n - i - 1;
185 } else {
186 filled_to = 0;
187 }
188 found_newline = true;
189 break;
190 }
191 }
192 if (found_newline) {
193 continue;
194 } else {
195 filled_to += n;
196 // Check if we must flush now.
197 if (filled_to == kBufSize) {
198 buf[kBufSize] = 0;
199 LOG(level) << buf;
200 filled_to = 0;
201 }
202 }
203 }
204}
205
Ian Rogersef7d42f2014-01-06 12:55:46 -0800206std::string PrettyDescriptor(mirror::String* java_descriptor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700207 if (java_descriptor == nullptr) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700208 return "null";
209 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700210 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700211}
Elliott Hughes5174fe62011-08-23 15:12:35 -0700212
Ian Rogersef7d42f2014-01-06 12:55:46 -0800213std::string PrettyDescriptor(mirror::Class* klass) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700214 if (klass == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800215 return "null";
216 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700217 std::string temp;
218 return PrettyDescriptor(klass->GetDescriptor(&temp));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800219}
220
Ian Rogers1ff3c982014-08-12 02:30:58 -0700221std::string PrettyDescriptor(const char* descriptor) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700222 // Count the number of '['s to get the dimensionality.
Ian Rogers1ff3c982014-08-12 02:30:58 -0700223 const char* c = descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700224 size_t dim = 0;
225 while (*c == '[') {
226 dim++;
227 c++;
228 }
229
230 // Reference or primitive?
231 if (*c == 'L') {
232 // "[[La/b/C;" -> "a.b.C[][]".
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700233 c++; // Skip the 'L'.
Elliott Hughes11e45072011-08-16 17:40:46 -0700234 } else {
235 // "[[B" -> "byte[][]".
236 // To make life easier, we make primitives look like unqualified
237 // reference types.
238 switch (*c) {
239 case 'B': c = "byte;"; break;
240 case 'C': c = "char;"; break;
241 case 'D': c = "double;"; break;
242 case 'F': c = "float;"; break;
243 case 'I': c = "int;"; break;
244 case 'J': c = "long;"; break;
245 case 'S': c = "short;"; break;
246 case 'Z': c = "boolean;"; break;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700247 case 'V': c = "void;"; break; // Used when decoding return types.
Elliott Hughes5174fe62011-08-23 15:12:35 -0700248 default: return descriptor;
Elliott Hughes11e45072011-08-16 17:40:46 -0700249 }
250 }
251
252 // At this point, 'c' is a string of the form "fully/qualified/Type;"
253 // or "primitive;". Rewrite the type with '.' instead of '/':
254 std::string result;
255 const char* p = c;
256 while (*p != ';') {
257 char ch = *p++;
258 if (ch == '/') {
259 ch = '.';
260 }
261 result.push_back(ch);
262 }
263 // ...and replace the semicolon with 'dim' "[]" pairs:
Ian Rogers1ff3c982014-08-12 02:30:58 -0700264 for (size_t i = 0; i < dim; ++i) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700265 result += "[]";
266 }
267 return result;
268}
269
Mathieu Chartierc7853442015-03-27 14:35:38 -0700270std::string PrettyField(ArtField* f, bool with_type) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700271 if (f == nullptr) {
Elliott Hughesa2501992011-08-26 19:39:54 -0700272 return "null";
273 }
Elliott Hughes54e7df12011-09-16 11:47:04 -0700274 std::string result;
275 if (with_type) {
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700276 result += PrettyDescriptor(f->GetTypeDescriptor());
Elliott Hughes54e7df12011-09-16 11:47:04 -0700277 result += ' ';
278 }
Ian Rogers08f1f502014-12-02 15:04:37 -0800279 std::string temp;
280 result += PrettyDescriptor(f->GetDeclaringClass()->GetDescriptor(&temp));
Elliott Hughesa2501992011-08-26 19:39:54 -0700281 result += '.';
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700282 result += f->GetName();
Elliott Hughesa2501992011-08-26 19:39:54 -0700283 return result;
284}
285
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700286std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800287 if (field_idx >= dex_file.NumFieldIds()) {
288 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
289 }
Brian Carlstrom6f29d0e2012-05-11 15:50:29 -0700290 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
291 std::string result;
292 if (with_type) {
293 result += dex_file.GetFieldTypeDescriptor(field_id);
294 result += ' ';
295 }
296 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
297 result += '.';
298 result += dex_file.GetFieldName(field_id);
299 return result;
300}
301
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700302std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800303 if (type_idx >= dex_file.NumTypeIds()) {
304 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
305 }
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700306 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
Mathieu Chartier4c70d772012-09-10 14:08:32 -0700307 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
Mathieu Chartier18c24b62012-09-10 08:54:25 -0700308}
309
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700310std::string PrettyArguments(const char* signature) {
311 std::string result;
312 result += '(';
313 CHECK_EQ(*signature, '(');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700314 ++signature; // Skip the '('.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700315 while (*signature != ')') {
316 size_t argument_length = 0;
317 while (signature[argument_length] == '[') {
318 ++argument_length;
319 }
320 if (signature[argument_length] == 'L') {
321 argument_length = (strchr(signature, ';') - signature + 1);
322 } else {
323 ++argument_length;
324 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700325 {
326 std::string argument_descriptor(signature, argument_length);
327 result += PrettyDescriptor(argument_descriptor.c_str());
328 }
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700329 if (signature[argument_length] != ')') {
330 result += ", ";
331 }
332 signature += argument_length;
333 }
334 CHECK_EQ(*signature, ')');
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700335 ++signature; // Skip the ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700336 result += ')';
337 return result;
338}
339
340std::string PrettyReturnType(const char* signature) {
341 const char* return_type = strchr(signature, ')');
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700342 CHECK(return_type != nullptr);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700343 ++return_type; // Skip ')'.
Elliott Hughes9058f2b2012-03-22 18:06:48 -0700344 return PrettyDescriptor(return_type);
345}
346
Ian Rogersef7d42f2014-01-06 12:55:46 -0800347std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
Ian Rogers16ce0922014-01-10 14:59:36 -0800348 if (m == nullptr) {
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700349 return "null";
350 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700351 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700352 result += '.';
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700353 result += m->GetName();
Ian Rogers16ce0922014-01-10 14:59:36 -0800354 if (UNLIKELY(m->IsFastNative())) {
355 result += "!";
356 }
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700357 if (with_signature) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700358 const Signature signature = m->GetSignature();
Ian Rogersd91d6d62013-09-25 20:26:14 -0700359 std::string sig_as_string(signature.ToString());
360 if (signature == Signature::NoSignature()) {
361 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700362 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700363 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
364 PrettyArguments(sig_as_string.c_str());
Elliott Hughesa0b8feb2011-08-20 09:50:55 -0700365 }
366 return result;
367}
368
Ian Rogers0571d352011-11-03 19:51:38 -0700369std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
Elliott Hughes60641a72013-02-27 14:36:16 -0800370 if (method_idx >= dex_file.NumMethodIds()) {
371 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
372 }
Ian Rogers0571d352011-11-03 19:51:38 -0700373 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
374 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
375 result += '.';
376 result += dex_file.GetMethodName(method_id);
377 if (with_signature) {
Ian Rogersd91d6d62013-09-25 20:26:14 -0700378 const Signature signature = dex_file.GetMethodSignature(method_id);
379 std::string sig_as_string(signature.ToString());
380 if (signature == Signature::NoSignature()) {
381 return result + sig_as_string;
Elliott Hughesf8c11932012-03-23 19:53:59 -0700382 }
Ian Rogersd91d6d62013-09-25 20:26:14 -0700383 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
384 PrettyArguments(sig_as_string.c_str());
Ian Rogers0571d352011-11-03 19:51:38 -0700385 }
386 return result;
387}
388
Ian Rogersef7d42f2014-01-06 12:55:46 -0800389std::string PrettyTypeOf(mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700390 if (obj == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700391 return "null";
392 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700393 if (obj->GetClass() == nullptr) {
Elliott Hughes11e45072011-08-16 17:40:46 -0700394 return "(raw)";
395 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700396 std::string temp;
397 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
Elliott Hughes11e45072011-08-16 17:40:46 -0700398 if (obj->IsClass()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700399 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
Elliott Hughes11e45072011-08-16 17:40:46 -0700400 }
401 return result;
402}
403
Ian Rogersef7d42f2014-01-06 12:55:46 -0800404std::string PrettyClass(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700405 if (c == nullptr) {
Elliott Hughes54e7df12011-09-16 11:47:04 -0700406 return "null";
407 }
408 std::string result;
409 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800410 result += PrettyDescriptor(c);
Elliott Hughes54e7df12011-09-16 11:47:04 -0700411 result += ">";
412 return result;
413}
414
Ian Rogersef7d42f2014-01-06 12:55:46 -0800415std::string PrettyClassAndClassLoader(mirror::Class* c) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700416 if (c == nullptr) {
Ian Rogersd81871c2011-10-03 13:57:23 -0700417 return "null";
418 }
419 std::string result;
420 result += "java.lang.Class<";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800421 result += PrettyDescriptor(c);
Ian Rogersd81871c2011-10-03 13:57:23 -0700422 result += ",";
423 result += PrettyTypeOf(c->GetClassLoader());
424 // TODO: add an identifying hash value for the loader
425 result += ">";
426 return result;
427}
428
Andreas Gampec0d82292014-09-23 10:38:30 -0700429std::string PrettyJavaAccessFlags(uint32_t access_flags) {
430 std::string result;
431 if ((access_flags & kAccPublic) != 0) {
432 result += "public ";
433 }
434 if ((access_flags & kAccProtected) != 0) {
435 result += "protected ";
436 }
437 if ((access_flags & kAccPrivate) != 0) {
438 result += "private ";
439 }
440 if ((access_flags & kAccFinal) != 0) {
441 result += "final ";
442 }
443 if ((access_flags & kAccStatic) != 0) {
444 result += "static ";
445 }
446 if ((access_flags & kAccTransient) != 0) {
447 result += "transient ";
448 }
449 if ((access_flags & kAccVolatile) != 0) {
450 result += "volatile ";
451 }
452 if ((access_flags & kAccSynchronized) != 0) {
453 result += "synchronized ";
454 }
455 return result;
456}
457
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800458std::string PrettySize(int64_t byte_count) {
Elliott Hughesc967f782012-04-16 10:23:15 -0700459 // The byte thresholds at which we display amounts. A byte count is displayed
460 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
Ian Rogersef7d42f2014-01-06 12:55:46 -0800461 static const int64_t kUnitThresholds[] = {
Elliott Hughesc967f782012-04-16 10:23:15 -0700462 0, // B up to...
463 3*1024, // KB up to...
464 2*1024*1024, // MB up to...
465 1024*1024*1024 // GB from here.
466 };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800467 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
Elliott Hughesc967f782012-04-16 10:23:15 -0700468 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800469 const char* negative_str = "";
470 if (byte_count < 0) {
471 negative_str = "-";
472 byte_count = -byte_count;
473 }
Elliott Hughesc967f782012-04-16 10:23:15 -0700474 int i = arraysize(kUnitThresholds);
475 while (--i > 0) {
476 if (byte_count >= kUnitThresholds[i]) {
477 break;
478 }
Ian Rogers3bb17a62012-01-27 23:56:44 -0800479 }
Brian Carlstrom474cc792014-03-07 14:18:15 -0800480 return StringPrintf("%s%" PRId64 "%s",
481 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
Ian Rogers3bb17a62012-01-27 23:56:44 -0800482}
483
Ian Rogers576ca0c2014-06-06 15:58:22 -0700484std::string PrintableChar(uint16_t ch) {
485 std::string result;
486 result += '\'';
487 if (NeedsEscaping(ch)) {
488 StringAppendF(&result, "\\u%04x", ch);
489 } else {
490 result += ch;
491 }
492 result += '\'';
493 return result;
494}
495
Ian Rogers68b56852014-08-29 20:19:11 -0700496std::string PrintableString(const char* utf) {
Elliott Hughes82914b62012-04-09 15:56:29 -0700497 std::string result;
498 result += '"';
Ian Rogers68b56852014-08-29 20:19:11 -0700499 const char* p = utf;
Elliott Hughes82914b62012-04-09 15:56:29 -0700500 size_t char_count = CountModifiedUtf8Chars(p);
501 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000502 uint32_t ch = GetUtf16FromUtf8(&p);
Elliott Hughes82914b62012-04-09 15:56:29 -0700503 if (ch == '\\') {
504 result += "\\\\";
505 } else if (ch == '\n') {
506 result += "\\n";
507 } else if (ch == '\r') {
508 result += "\\r";
509 } else if (ch == '\t') {
510 result += "\\t";
Elliott Hughes82914b62012-04-09 15:56:29 -0700511 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000512 const uint16_t leading = GetLeadingUtf16Char(ch);
513
514 if (NeedsEscaping(leading)) {
515 StringAppendF(&result, "\\u%04x", leading);
516 } else {
517 result += leading;
518 }
519
520 const uint32_t trailing = GetTrailingUtf16Char(ch);
521 if (trailing != 0) {
522 // All high surrogates will need escaping.
523 StringAppendF(&result, "\\u%04x", trailing);
524 }
Elliott Hughes82914b62012-04-09 15:56:29 -0700525 }
526 }
527 result += '"';
528 return result;
529}
530
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800531// 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 -0700532std::string MangleForJni(const std::string& s) {
533 std::string result;
534 size_t char_count = CountModifiedUtf8Chars(s.c_str());
535 const char* cp = &s[0];
536 for (size_t i = 0; i < char_count; ++i) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000537 uint32_t ch = GetUtf16FromUtf8(&cp);
Elliott Hughesd8c00d02012-01-30 14:08:31 -0800538 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
539 result.push_back(ch);
540 } else if (ch == '.' || ch == '/') {
541 result += "_";
542 } else if (ch == '_') {
543 result += "_1";
544 } else if (ch == ';') {
545 result += "_2";
546 } else if (ch == '[') {
547 result += "_3";
Elliott Hughes79082e32011-08-25 12:07:32 -0700548 } else {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000549 const uint16_t leading = GetLeadingUtf16Char(ch);
550 const uint32_t trailing = GetTrailingUtf16Char(ch);
551
552 StringAppendF(&result, "_0%04x", leading);
553 if (trailing != 0) {
554 StringAppendF(&result, "_0%04x", trailing);
555 }
Elliott Hughes79082e32011-08-25 12:07:32 -0700556 }
557 }
558 return result;
559}
560
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700561std::string DotToDescriptor(const char* class_name) {
562 std::string descriptor(class_name);
563 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
564 if (descriptor.length() > 0 && descriptor[0] != '[') {
565 descriptor = "L" + descriptor + ";";
566 }
567 return descriptor;
568}
569
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800570std::string DescriptorToDot(const char* descriptor) {
Elliott Hughes2435a572012-02-17 16:07:41 -0800571 size_t length = strlen(descriptor);
Ian Rogers1ff3c982014-08-12 02:30:58 -0700572 if (length > 1) {
573 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
574 // Descriptors have the leading 'L' and trailing ';' stripped.
575 std::string result(descriptor + 1, length - 2);
576 std::replace(result.begin(), result.end(), '/', '.');
577 return result;
578 } else {
579 // For arrays the 'L' and ';' remain intact.
580 std::string result(descriptor);
581 std::replace(result.begin(), result.end(), '/', '.');
582 return result;
583 }
Elliott Hughes2435a572012-02-17 16:07:41 -0800584 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700585 // Do nothing for non-class/array descriptors.
Elliott Hughes2435a572012-02-17 16:07:41 -0800586 return descriptor;
Elliott Hughes91bf6cd2012-02-14 17:27:48 -0800587}
588
589std::string DescriptorToName(const char* descriptor) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800590 size_t length = strlen(descriptor);
Elliott Hughes2435a572012-02-17 16:07:41 -0800591 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
592 std::string result(descriptor + 1, length - 2);
593 return result;
594 }
595 return descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700596}
597
Ian Rogersef7d42f2014-01-06 12:55:46 -0800598std::string JniShortName(mirror::ArtMethod* m) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700599 std::string class_name(m->GetDeclaringClassDescriptor());
Elliott Hughes79082e32011-08-25 12:07:32 -0700600 // Remove the leading 'L' and trailing ';'...
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700601 CHECK_EQ(class_name[0], 'L') << class_name;
602 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
Elliott Hughes79082e32011-08-25 12:07:32 -0700603 class_name.erase(0, 1);
604 class_name.erase(class_name.size() - 1, 1);
605
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700606 std::string method_name(m->GetName());
Elliott Hughes79082e32011-08-25 12:07:32 -0700607
608 std::string short_name;
609 short_name += "Java_";
610 short_name += MangleForJni(class_name);
611 short_name += "_";
612 short_name += MangleForJni(method_name);
613 return short_name;
614}
615
Ian Rogersef7d42f2014-01-06 12:55:46 -0800616std::string JniLongName(mirror::ArtMethod* m) {
Elliott Hughes79082e32011-08-25 12:07:32 -0700617 std::string long_name;
618 long_name += JniShortName(m);
619 long_name += "__";
620
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700621 std::string signature(m->GetSignature().ToString());
Elliott Hughes79082e32011-08-25 12:07:32 -0700622 signature.erase(0, 1);
623 signature.erase(signature.begin() + signature.find(')'), signature.end());
624
625 long_name += MangleForJni(signature);
626
627 return long_name;
628}
629
jeffhao10037c82012-01-23 15:06:23 -0800630// Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700631uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700632 0x00000000, // 00..1f low control characters; nothing valid
633 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
634 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
635 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700636};
637
jeffhao10037c82012-01-23 15:06:23 -0800638// Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
639bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700640 /*
641 * It's a multibyte encoded character. Decode it and analyze. We
642 * accept anything that isn't (a) an improperly encoded low value,
643 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
644 * control character, or (e) a high space, layout, or special
645 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
646 * U+fff0..U+ffff). This is all specified in the dex format
647 * document.
648 */
649
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000650 const uint32_t pair = GetUtf16FromUtf8(pUtf8Ptr);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000651 const uint16_t leading = GetLeadingUtf16Char(pair);
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000652
Narayan Kamath8508e372015-05-06 14:55:43 +0100653 // We have a surrogate pair resulting from a valid 4 byte UTF sequence.
654 // No further checks are necessary because 4 byte sequences span code
655 // points [U+10000, U+1FFFFF], which are valid codepoints in a dex
656 // identifier. Furthermore, GetUtf16FromUtf8 guarantees that each of
657 // the surrogate halves are valid and well formed in this instance.
658 if (GetTrailingUtf16Char(pair) != 0) {
659 return true;
660 }
661
662
663 // We've encountered a one, two or three byte UTF-8 sequence. The
664 // three byte UTF-8 sequence could be one half of a surrogate pair.
665 switch (leading >> 8) {
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000666 case 0x00:
667 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
668 return (leading > 0x00a0);
669 case 0xd8:
670 case 0xd9:
671 case 0xda:
672 case 0xdb:
Narayan Kamath8508e372015-05-06 14:55:43 +0100673 {
674 // We found a three byte sequence encoding one half of a surrogate.
675 // Look for the other half.
676 const uint32_t pair2 = GetUtf16FromUtf8(pUtf8Ptr);
677 const uint16_t trailing = GetLeadingUtf16Char(pair2);
678
679 return (GetTrailingUtf16Char(pair2) == 0) && (0xdc00 <= trailing && trailing <= 0xdfff);
680 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000681 case 0xdc:
682 case 0xdd:
683 case 0xde:
684 case 0xdf:
685 // It's a trailing surrogate, which is not valid at this point.
686 return false;
687 case 0x20:
688 case 0xff:
689 // It's in the range that has spaces, controls, and specials.
690 switch (leading & 0xfff8) {
Narayan Kamath8508e372015-05-06 14:55:43 +0100691 case 0x2000:
692 case 0x2008:
693 case 0x2028:
694 case 0xfff0:
695 case 0xfff8:
696 return false;
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000697 }
Narayan Kamath8508e372015-05-06 14:55:43 +0100698 return true;
699 default:
700 return true;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700701 }
Narayan Kamatha5afcfc2015-01-29 20:06:46 +0000702
Narayan Kamath8508e372015-05-06 14:55:43 +0100703 UNREACHABLE();
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700704}
705
706/* Return whether the pointed-at modified-UTF-8 encoded character is
707 * valid as part of a member name, updating the pointer to point past
708 * the consumed character. This will consume two encoded UTF-16 code
709 * points if the character is encoded as a surrogate pair. Also, if
710 * this function returns false, then the given pointer may only have
711 * been partially advanced.
712 */
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700713static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700714 uint8_t c = (uint8_t) **pUtf8Ptr;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700715 if (LIKELY(c <= 0x7f)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700716 // It's low-ascii, so check the table.
717 uint32_t wordIdx = c >> 5;
718 uint32_t bitIdx = c & 0x1f;
719 (*pUtf8Ptr)++;
720 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
721 }
722
723 // It's a multibyte encoded character. Call a non-inline function
724 // for the heavy lifting.
jeffhao10037c82012-01-23 15:06:23 -0800725 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
726}
727
728bool IsValidMemberName(const char* s) {
729 bool angle_name = false;
730
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700731 switch (*s) {
jeffhao10037c82012-01-23 15:06:23 -0800732 case '\0':
733 // The empty string is not a valid name.
734 return false;
735 case '<':
736 angle_name = true;
737 s++;
738 break;
739 }
740
741 while (true) {
742 switch (*s) {
743 case '\0':
744 return !angle_name;
745 case '>':
746 return angle_name && s[1] == '\0';
747 }
748
749 if (!IsValidPartOfMemberNameUtf8(&s)) {
750 return false;
751 }
752 }
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700753}
754
Elliott Hughes906e6852011-10-28 14:52:10 -0700755enum ClassNameType { kName, kDescriptor };
Ian Rogers7b078e82014-09-10 14:44:24 -0700756template<ClassNameType kType, char kSeparator>
757static bool IsValidClassName(const char* s) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700758 int arrayCount = 0;
759 while (*s == '[') {
760 arrayCount++;
761 s++;
762 }
763
764 if (arrayCount > 255) {
765 // Arrays may have no more than 255 dimensions.
766 return false;
767 }
768
Ian Rogers7b078e82014-09-10 14:44:24 -0700769 ClassNameType type = kType;
770 if (type != kDescriptor && arrayCount != 0) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700771 /*
772 * If we're looking at an array of some sort, then it doesn't
773 * matter if what is being asked for is a class name; the
774 * format looks the same as a type descriptor in that case, so
775 * treat it as such.
776 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700777 type = kDescriptor;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700778 }
779
Elliott Hughes906e6852011-10-28 14:52:10 -0700780 if (type == kDescriptor) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700781 /*
782 * We are looking for a descriptor. Either validate it as a
783 * single-character primitive type, or continue on to check the
784 * embedded class name (bracketed by "L" and ";").
785 */
786 switch (*(s++)) {
787 case 'B':
788 case 'C':
789 case 'D':
790 case 'F':
791 case 'I':
792 case 'J':
793 case 'S':
794 case 'Z':
795 // These are all single-character descriptors for primitive types.
796 return (*s == '\0');
797 case 'V':
798 // Non-array void is valid, but you can't have an array of void.
799 return (arrayCount == 0) && (*s == '\0');
800 case 'L':
801 // Class name: Break out and continue below.
802 break;
803 default:
804 // Oddball descriptor character.
805 return false;
806 }
807 }
808
809 /*
810 * We just consumed the 'L' that introduces a class name as part
811 * of a type descriptor, or we are looking for an unadorned class
812 * name.
813 */
814
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700815 bool sepOrFirst = true; // first character or just encountered a separator.
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700816 for (;;) {
817 uint8_t c = (uint8_t) *s;
818 switch (c) {
819 case '\0':
820 /*
821 * Premature end for a type descriptor, but valid for
822 * a class name as long as we haven't encountered an
823 * empty component (including the degenerate case of
824 * the empty string "").
825 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700826 return (type == kName) && !sepOrFirst;
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700827 case ';':
828 /*
829 * Invalid character for a class name, but the
830 * legitimate end of a type descriptor. In the latter
831 * case, make sure that this is the end of the string
832 * and that it doesn't end with an empty component
833 * (including the degenerate case of "L;").
834 */
Elliott Hughes906e6852011-10-28 14:52:10 -0700835 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700836 case '/':
837 case '.':
Ian Rogers7b078e82014-09-10 14:44:24 -0700838 if (c != kSeparator) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700839 // The wrong separator character.
840 return false;
841 }
842 if (sepOrFirst) {
843 // Separator at start or two separators in a row.
844 return false;
845 }
846 sepOrFirst = true;
847 s++;
848 break;
849 default:
jeffhao10037c82012-01-23 15:06:23 -0800850 if (!IsValidPartOfMemberNameUtf8(&s)) {
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700851 return false;
852 }
853 sepOrFirst = false;
854 break;
855 }
856 }
857}
858
Elliott Hughes906e6852011-10-28 14:52:10 -0700859bool IsValidBinaryClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700860 return IsValidClassName<kName, '.'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700861}
862
863bool IsValidJniClassName(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700864 return IsValidClassName<kName, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700865}
866
867bool IsValidDescriptor(const char* s) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700868 return IsValidClassName<kDescriptor, '/'>(s);
Elliott Hughes906e6852011-10-28 14:52:10 -0700869}
870
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700871void Split(const std::string& s, char separator, std::vector<std::string>* result) {
Elliott Hughes34023802011-08-30 12:06:17 -0700872 const char* p = s.data();
873 const char* end = p + s.size();
874 while (p != end) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800875 if (*p == separator) {
Elliott Hughes34023802011-08-30 12:06:17 -0700876 ++p;
877 } else {
878 const char* start = p;
Elliott Hughes48436bb2012-02-07 15:23:28 -0800879 while (++p != end && *p != separator) {
880 // Skip to the next occurrence of the separator.
Elliott Hughes34023802011-08-30 12:06:17 -0700881 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700882 result->push_back(std::string(start, p - start));
Elliott Hughes34023802011-08-30 12:06:17 -0700883 }
884 }
885}
886
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700887std::string Trim(const std::string& s) {
Dave Allison70202782013-10-22 17:52:19 -0700888 std::string result;
889 unsigned int start_index = 0;
890 unsigned int end_index = s.size() - 1;
891
892 // Skip initial whitespace.
893 while (start_index < s.size()) {
894 if (!isspace(s[start_index])) {
895 break;
896 }
897 start_index++;
898 }
899
900 // Skip terminating whitespace.
901 while (end_index >= start_index) {
902 if (!isspace(s[end_index])) {
903 break;
904 }
905 end_index--;
906 }
907
908 // All spaces, no beef.
909 if (end_index < start_index) {
910 return "";
911 }
912 // Start_index is the first non-space, end_index is the last one.
913 return s.substr(start_index, end_index - start_index + 1);
914}
915
Elliott Hughes48436bb2012-02-07 15:23:28 -0800916template <typename StringT>
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700917std::string Join(const std::vector<StringT>& strings, char separator) {
Elliott Hughes48436bb2012-02-07 15:23:28 -0800918 if (strings.empty()) {
919 return "";
920 }
921
922 std::string result(strings[0]);
923 for (size_t i = 1; i < strings.size(); ++i) {
924 result += separator;
925 result += strings[i];
926 }
927 return result;
928}
929
930// Explicit instantiations.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700931template std::string Join<std::string>(const std::vector<std::string>& strings, char separator);
932template std::string Join<const char*>(const std::vector<const char*>& strings, char separator);
Elliott Hughes48436bb2012-02-07 15:23:28 -0800933
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800934bool StartsWith(const std::string& s, const char* prefix) {
935 return s.compare(0, strlen(prefix), prefix) == 0;
936}
937
Brian Carlstrom7a967b32012-03-28 15:23:10 -0700938bool EndsWith(const std::string& s, const char* suffix) {
939 size_t suffix_length = strlen(suffix);
940 size_t string_length = s.size();
941 if (suffix_length > string_length) {
942 return false;
943 }
944 size_t offset = string_length - suffix_length;
945 return s.compare(offset, suffix_length, suffix) == 0;
946}
947
Elliott Hughes22869a92012-03-27 14:08:24 -0700948void SetThreadName(const char* thread_name) {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700949 int hasAt = 0;
950 int hasDot = 0;
Elliott Hughes22869a92012-03-27 14:08:24 -0700951 const char* s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700952 while (*s) {
953 if (*s == '.') {
954 hasDot = 1;
955 } else if (*s == '@') {
956 hasAt = 1;
957 }
958 s++;
959 }
Elliott Hughes22869a92012-03-27 14:08:24 -0700960 int len = s - thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700961 if (len < 15 || hasAt || !hasDot) {
Elliott Hughes22869a92012-03-27 14:08:24 -0700962 s = thread_name;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700963 } else {
Elliott Hughes22869a92012-03-27 14:08:24 -0700964 s = thread_name + len - 15;
Elliott Hughesdcc24742011-09-07 14:02:44 -0700965 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800966#if defined(__linux__)
Elliott Hughes7c6a61e2012-03-12 18:01:41 -0700967 // pthread_setname_np fails rather than truncating long strings.
Elliott Hughes0a18df82015-01-09 15:16:16 -0800968 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
Elliott Hughesdcc24742011-09-07 14:02:44 -0700969 strncpy(buf, s, sizeof(buf)-1);
970 buf[sizeof(buf)-1] = '\0';
971 errno = pthread_setname_np(pthread_self(), buf);
972 if (errno != 0) {
973 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
974 }
Elliott Hughes0a18df82015-01-09 15:16:16 -0800975#else // __APPLE__
Elliott Hughes22869a92012-03-27 14:08:24 -0700976 pthread_setname_np(thread_name);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700977#endif
978}
979
Brian Carlstrom29212012013-09-12 22:18:30 -0700980void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
981 *utime = *stime = *task_cpu = 0;
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700982 std::string stats;
Elliott Hughes8a31b502012-04-30 19:36:11 -0700983 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700984 return;
985 }
986 // Skip the command, which may contain spaces.
987 stats = stats.substr(stats.find(')') + 2);
988 // Extract the three fields we care about.
989 std::vector<std::string> fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700990 Split(stats, ' ', &fields);
Brian Carlstrom29212012013-09-12 22:18:30 -0700991 *state = fields[0][0];
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700992 *utime = strtoull(fields[11].c_str(), nullptr, 10);
993 *stime = strtoull(fields[12].c_str(), nullptr, 10);
994 *task_cpu = strtoull(fields[36].c_str(), nullptr, 10);
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700995}
996
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700997std::string GetSchedulerGroupName(pid_t tid) {
998 // /proc/<pid>/cgroup looks like this:
999 // 2:devices:/
1000 // 1:cpuacct,cpu:/
1001 // We want the third field from the line whose second field contains the "cpu" token.
1002 std::string cgroup_file;
1003 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1004 return "";
1005 }
1006 std::vector<std::string> cgroup_lines;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001007 Split(cgroup_file, '\n', &cgroup_lines);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001008 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1009 std::vector<std::string> cgroup_fields;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001010 Split(cgroup_lines[i], ':', &cgroup_fields);
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001011 std::vector<std::string> cgroups;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001012 Split(cgroup_fields[1], ',', &cgroups);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001013 for (size_t j = 0; j < cgroups.size(); ++j) {
1014 if (cgroups[j] == "cpu") {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001015 return cgroup_fields[2].substr(1); // Skip the leading slash.
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001016 }
1017 }
1018 }
1019 return "";
1020}
1021
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001022#if defined(__linux__)
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001023
1024ALWAYS_INLINE
1025static inline void WritePrefix(std::ostream* os, const char* prefix, bool odd) {
1026 if (prefix != nullptr) {
1027 *os << prefix;
1028 }
1029 *os << " ";
1030 if (!odd) {
1031 *os << " ";
1032 }
1033}
1034
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001035static bool RunCommand(std::string cmd, std::ostream* os, const char* prefix) {
1036 FILE* stream = popen(cmd.c_str(), "r");
1037 if (stream) {
1038 if (os != nullptr) {
1039 bool odd_line = true; // We indent them differently.
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001040 bool wrote_prefix = false; // Have we already written a prefix?
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001041 constexpr size_t kMaxBuffer = 128; // Relatively small buffer. Should be OK as we're on an
1042 // alt stack, but just to be sure...
1043 char buffer[kMaxBuffer];
1044 while (!feof(stream)) {
1045 if (fgets(buffer, kMaxBuffer, stream) != nullptr) {
1046 // Split on newlines.
1047 char* tmp = buffer;
1048 for (;;) {
1049 char* new_line = strchr(tmp, '\n');
1050 if (new_line == nullptr) {
1051 // Print the rest.
1052 if (*tmp != 0) {
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001053 if (!wrote_prefix) {
1054 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001055 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001056 wrote_prefix = true;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001057 *os << tmp;
1058 }
1059 break;
1060 }
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001061 if (!wrote_prefix) {
1062 WritePrefix(os, prefix, odd_line);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001063 }
1064 char saved = *(new_line + 1);
1065 *(new_line + 1) = 0;
1066 *os << tmp;
1067 *(new_line + 1) = saved;
1068 tmp = new_line + 1;
1069 odd_line = !odd_line;
Andreas Gampe00bd2da2015-01-09 15:05:46 -08001070 wrote_prefix = false;
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001071 }
1072 }
1073 }
1074 }
1075 pclose(stream);
1076 return true;
1077 } else {
1078 return false;
1079 }
1080}
1081
1082static void Addr2line(const std::string& map_src, uintptr_t offset, std::ostream& os,
1083 const char* prefix) {
1084 std::string cmdline(StringPrintf("addr2line --functions --inlines --demangle -e %s %zx",
1085 map_src.c_str(), offset));
1086 RunCommand(cmdline.c_str(), &os, prefix);
1087}
1088#endif
1089
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001090void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
Andreas Gampe628a61a2015-01-07 22:08:35 -08001091 mirror::ArtMethod* current_method, void* ucontext_ptr) {
Ian Rogers83597d02014-11-20 10:29:00 -08001092#if __linux__
Andreas Gamped7576322014-10-24 22:13:45 -07001093 // b/18119146
1094 if (RUNNING_ON_VALGRIND != 0) {
1095 return;
1096 }
1097
Ian Rogers700a4022014-05-19 16:49:03 -07001098 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
Andreas Gampe628a61a2015-01-07 22:08:35 -08001099 if (!backtrace->Unwind(0, reinterpret_cast<ucontext*>(ucontext_ptr))) {
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001100 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001101 return;
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001102 } else if (backtrace->NumFrames() == 0) {
Elliott Hughes225f5a12012-06-11 11:23:48 -07001103 os << prefix << "(no native stack frames for thread " << tid << ")\n";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001104 return;
1105 }
1106
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001107 // Check whether we have and should use addr2line.
1108 bool use_addr2line;
1109 if (kUseAddr2line) {
1110 // Try to run it to see whether we have it. Push an argument so that it doesn't assume a.out
1111 // and print to stderr.
Andreas Gampe941c5512015-01-15 10:38:19 -08001112 use_addr2line = (gAborting > 0) && RunCommand("addr2line -h", nullptr, nullptr);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001113 } else {
1114 use_addr2line = false;
1115 }
1116
Christopher Ferris943af7d2014-01-16 12:41:46 -08001117 for (Backtrace::const_iterator it = backtrace->begin();
1118 it != backtrace->end(); ++it) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001119 // We produce output like this:
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001120 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1121 // In order for parsing tools to continue to function, the stack dump
1122 // format must at least adhere to this format:
1123 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1124 // The parsers require a single space before and after pc, and two spaces
1125 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1126 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1127 os << prefix << StringPrintf("#%02zu pc ", it->num);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001128 bool try_addr2line = false;
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001129 if (!BacktraceMap::IsValid(it->map)) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001130 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
Christopher Ferris7b5f0cf2013-11-01 15:18:45 -07001131 } else {
Christopher Ferris5a1b2bf2015-05-01 16:03:49 -07001132 os << StringPrintf("%08" PRIxPTR " ", BacktraceMap::GetRelativePc(it->map, it->pc));
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001133 os << it->map.name;
Andreas Gampe3ef69b42015-01-26 10:38:34 -08001134 os << " (";
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001135 if (!it->func_name.empty()) {
1136 os << it->func_name;
1137 if (it->func_offset != 0) {
1138 os << "+" << it->func_offset;
1139 }
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001140 try_addr2line = true;
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001141 } else if (
1142 current_method != nullptr && Locks::mutator_lock_->IsSharedHeld(Thread::Current()) &&
1143 current_method->PcIsWithinQuickCode(it->pc)) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001144 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1145 os << JniLongName(current_method) << "+"
1146 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
Kenny Root067d20f2014-03-05 14:57:21 -08001147 } else {
1148 os << "???";
1149 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001150 os << ")";
Elliott Hughes46e251b2012-05-22 15:10:45 -07001151 }
Christopher Ferrisa2cee182014-04-16 19:13:59 -07001152 os << "\n";
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001153 if (try_addr2line && use_addr2line) {
Christopher Ferrisa1c96652015-02-06 13:18:58 -08001154 Addr2line(it->map.name, it->pc - it->map.start, os, prefix);
Andreas Gampe8e1cb912015-01-08 20:11:09 -08001155 }
Elliott Hughes46e251b2012-05-22 15:10:45 -07001156 }
Nicolas Geoffraye6ac4fd2014-11-04 13:03:29 +00001157#else
Andreas Gampe9387c722015-01-08 11:32:22 -08001158 UNUSED(os, tid, prefix, current_method, ucontext_ptr);
Ian Rogersc5f17732014-06-05 20:48:42 -07001159#endif
Elliott Hughes46e251b2012-05-22 15:10:45 -07001160}
1161
Elliott Hughes058a6de2012-05-24 19:13:02 -07001162#if defined(__APPLE__)
1163
1164// TODO: is there any way to get the kernel stack on Mac OS?
1165void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1166
1167#else
1168
Elliott Hughes46e251b2012-05-22 15:10:45 -07001169void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
Elliott Hughes12a95022012-05-24 21:41:38 -07001170 if (tid == GetTid()) {
1171 // There's no point showing that we're reading our stack out of /proc!
1172 return;
1173 }
1174
Elliott Hughes46e251b2012-05-22 15:10:45 -07001175 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1176 std::string kernel_stack;
1177 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
Elliott Hughes058a6de2012-05-24 19:13:02 -07001178 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
jeffhaoc4c3ee22012-05-25 16:16:32 -07001179 return;
Elliott Hughes46e251b2012-05-22 15:10:45 -07001180 }
1181
1182 std::vector<std::string> kernel_stack_frames;
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001183 Split(kernel_stack, '\n', &kernel_stack_frames);
Elliott Hughes46e251b2012-05-22 15:10:45 -07001184 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1185 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1186 kernel_stack_frames.pop_back();
1187 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
Brian Carlstrom474cc792014-03-07 14:18:15 -08001188 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1189 // into "futex_wait_queue_me+0xcd/0x110".
Elliott Hughes46e251b2012-05-22 15:10:45 -07001190 const char* text = kernel_stack_frames[i].c_str();
1191 const char* close_bracket = strchr(text, ']');
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001192 if (close_bracket != nullptr) {
Elliott Hughes46e251b2012-05-22 15:10:45 -07001193 text = close_bracket + 2;
1194 }
1195 os << prefix;
1196 if (include_count) {
1197 os << StringPrintf("#%02zd ", i);
1198 }
1199 os << text << "\n";
1200 }
1201}
1202
1203#endif
1204
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001205const char* GetAndroidRoot() {
1206 const char* android_root = getenv("ANDROID_ROOT");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001207 if (android_root == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001208 if (OS::DirectoryExists("/system")) {
1209 android_root = "/system";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001210 } else {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001211 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1212 return "";
Brian Carlstroma9f19782011-10-13 00:14:47 -07001213 }
1214 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001215 if (!OS::DirectoryExists(android_root)) {
1216 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001217 return "";
1218 }
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001219 return android_root;
1220}
Brian Carlstroma9f19782011-10-13 00:14:47 -07001221
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001222const char* GetAndroidData() {
Alex Lighta59dd802014-07-02 16:28:08 -07001223 std::string error_msg;
1224 const char* dir = GetAndroidDataSafe(&error_msg);
1225 if (dir != nullptr) {
1226 return dir;
1227 } else {
1228 LOG(FATAL) << error_msg;
1229 return "";
1230 }
1231}
1232
1233const char* GetAndroidDataSafe(std::string* error_msg) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001234 const char* android_data = getenv("ANDROID_DATA");
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001235 if (android_data == nullptr) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001236 if (OS::DirectoryExists("/data")) {
1237 android_data = "/data";
1238 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001239 *error_msg = "ANDROID_DATA not set and /data does not exist";
1240 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001241 }
1242 }
1243 if (!OS::DirectoryExists(android_data)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001244 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1245 return nullptr;
Brian Carlstroma56fcd62012-02-04 21:23:01 -08001246 }
1247 return android_data;
1248}
1249
Alex Lighta59dd802014-07-02 16:28:08 -07001250void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001251 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001252 CHECK(subdir != nullptr);
1253 std::string error_msg;
1254 const char* android_data = GetAndroidDataSafe(&error_msg);
1255 if (android_data == nullptr) {
1256 *have_android_data = false;
1257 *dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001258 *is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001259 return;
1260 } else {
1261 *have_android_data = true;
1262 }
1263 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1264 *dalvik_cache = dalvik_cache_root + subdir;
1265 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
Andreas Gampe3c13a792014-09-18 20:56:04 -07001266 *is_global_cache = strcmp(android_data, "/data") == 0;
1267 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -07001268 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1269 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1270 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1271 }
1272}
1273
Andreas Gampe40da2862015-02-27 12:49:04 -08001274static std::string GetDalvikCacheImpl(const char* subdir,
1275 const bool create_if_absent,
1276 const bool abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001277 CHECK(subdir != nullptr);
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001278 const char* android_data = GetAndroidData();
1279 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
Narayan Kamath11d9f062014-04-23 20:24:57 +01001280 const std::string dalvik_cache = dalvik_cache_root + subdir;
Andreas Gampe40da2862015-02-27 12:49:04 -08001281 if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1282 if (!create_if_absent) {
1283 // TODO: Check callers. Traditional behavior is to not to abort, even when abort_on_error.
1284 return "";
1285 }
1286
Brian Carlstrom41ccffd2014-05-06 10:37:30 -07001287 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
Andreas Gampe40da2862015-02-27 12:49:04 -08001288 if (strcmp(android_data, "/data") == 0) {
1289 if (abort_on_error) {
1290 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache
1291 << ", cannot create /data dalvik-cache.";
1292 UNREACHABLE();
Narayan Kamath11d9f062014-04-23 20:24:57 +01001293 }
Andreas Gampe40da2862015-02-27 12:49:04 -08001294 return "";
1295 }
1296
1297 int result = mkdir(dalvik_cache_root.c_str(), 0700);
1298 if (result != 0 && errno != EEXIST) {
1299 if (abort_on_error) {
1300 PLOG(FATAL) << "Failed to create dalvik-cache root directory " << dalvik_cache_root;
1301 UNREACHABLE();
1302 }
1303 return "";
1304 }
1305
1306 result = mkdir(dalvik_cache.c_str(), 0700);
1307 if (result != 0) {
1308 if (abort_on_error) {
Narayan Kamath11d9f062014-04-23 20:24:57 +01001309 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
Andreas Gampe40da2862015-02-27 12:49:04 -08001310 UNREACHABLE();
Brian Carlstroma9f19782011-10-13 00:14:47 -07001311 }
Brian Carlstroma9f19782011-10-13 00:14:47 -07001312 return "";
1313 }
1314 }
Brian Carlstrom7675e162013-06-10 16:18:04 -07001315 return dalvik_cache;
Brian Carlstroma9f19782011-10-13 00:14:47 -07001316}
1317
Andreas Gampe40da2862015-02-27 12:49:04 -08001318std::string GetDalvikCache(const char* subdir, const bool create_if_absent) {
1319 return GetDalvikCacheImpl(subdir, create_if_absent, false);
1320}
1321
1322std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1323 return GetDalvikCacheImpl(subdir, create_if_absent, true);
1324}
1325
Alex Lighta59dd802014-07-02 16:28:08 -07001326bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1327 std::string* filename, std::string* error_msg) {
Ian Rogerse6060102013-05-16 12:01:04 -07001328 if (location[0] != '/') {
Alex Lighta59dd802014-07-02 16:28:08 -07001329 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1330 return false;
Ian Rogerse6060102013-05-16 12:01:04 -07001331 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001332 std::string cache_file(&location[1]); // skip leading slash
Alex Light6e183f22014-07-18 14:57:04 -07001333 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
Brian Carlstrom30e2ea42013-06-19 23:25:37 -07001334 cache_file += "/";
1335 cache_file += DexFile::kClassesDex;
1336 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001337 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
Alex Lighta59dd802014-07-02 16:28:08 -07001338 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1339 return true;
1340}
1341
1342std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1343 std::string ret;
1344 std::string error_msg;
1345 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1346 LOG(FATAL) << error_msg;
1347 }
1348 return ret;
Brian Carlstromb7bbba42011-10-13 14:58:47 -07001349}
1350
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001351static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001352 // in = /foo/bar/baz
1353 // out = /foo/bar/<isa>/baz
1354 size_t pos = filename->rfind('/');
1355 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1356 filename->insert(pos, "/", 1);
1357 filename->insert(pos + 1, GetInstructionSetString(isa));
1358}
1359
1360std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1361 // location = /system/framework/boot.art
1362 // filename = /system/framework/<isa>/boot.art
1363 std::string filename(location);
Brian Carlstrom2afe4942014-05-19 10:25:33 -07001364 InsertIsaDirectory(isa, &filename);
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -07001365 return filename;
1366}
1367
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001368bool IsZipMagic(uint32_t magic) {
1369 return (('P' == ((magic >> 0) & 0xff)) &&
1370 ('K' == ((magic >> 8) & 0xff)));
jeffhao262bf462011-10-20 18:36:32 -07001371}
1372
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001373bool IsDexMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001374 return DexFile::IsMagicValid(reinterpret_cast<const uint8_t*>(&magic));
Brian Carlstrom7a967b32012-03-28 15:23:10 -07001375}
1376
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001377bool IsOatMagic(uint32_t magic) {
Ian Rogers13735952014-10-08 12:43:28 -07001378 return (memcmp(reinterpret_cast<const uint8_t*>(magic),
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07001379 OatHeader::kOatMagic,
1380 sizeof(OatHeader::kOatMagic)) == 0);
jeffhao262bf462011-10-20 18:36:32 -07001381}
1382
Brian Carlstrom6449c622014-02-10 23:48:36 -08001383bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1384 const std::string command_line(Join(arg_vector, ' '));
1385
1386 CHECK_GE(arg_vector.size(), 1U) << command_line;
1387
1388 // Convert the args to char pointers.
1389 const char* program = arg_vector[0].c_str();
1390 std::vector<char*> args;
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -08001391 for (size_t i = 0; i < arg_vector.size(); ++i) {
1392 const std::string& arg = arg_vector[i];
1393 char* arg_str = const_cast<char*>(arg.c_str());
1394 CHECK(arg_str != nullptr) << i;
1395 args.push_back(arg_str);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001396 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001397 args.push_back(nullptr);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001398
1399 // fork and exec
1400 pid_t pid = fork();
1401 if (pid == 0) {
1402 // no allocation allowed between fork and exec
1403
1404 // change process groups, so we don't get reaped by ProcessManager
1405 setpgid(0, 0);
1406
1407 execv(program, &args[0]);
1408
Brian Carlstrom13db9aa2014-02-27 12:44:32 -08001409 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1410 exit(1);
Brian Carlstrom6449c622014-02-10 23:48:36 -08001411 } else {
1412 if (pid == -1) {
1413 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1414 command_line.c_str(), strerror(errno));
1415 return false;
1416 }
1417
1418 // wait for subprocess to finish
1419 int status;
1420 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1421 if (got_pid != pid) {
1422 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1423 "wanted %d, got %d: %s",
1424 command_line.c_str(), pid, got_pid, strerror(errno));
1425 return false;
1426 }
1427 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1428 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1429 command_line.c_str());
1430 return false;
1431 }
1432 }
1433 return true;
1434}
1435
Tong Shen547cdfd2014-08-05 01:54:19 -07001436void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001437 Leb128Encoder(dst).PushBackUnsigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001438}
1439
1440void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +07001441 Leb128Encoder(dst).PushBackSigned(data);
Tong Shen547cdfd2014-08-05 01:54:19 -07001442}
1443
Mathieu Chartier76433272014-09-26 14:32:37 -07001444std::string PrettyDescriptor(Primitive::Type type) {
1445 return PrettyDescriptor(Primitive::Descriptor(type));
1446}
1447
Elliott Hughes42ee1422011-09-06 12:33:32 -07001448} // namespace art