1 /*
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 */
16
17 #include "utils.h"
18
19 #include <inttypes.h>
20 #include <pthread.h>
21 #include <sys/stat.h>
22 #include <sys/syscall.h>
23 #include <sys/types.h>
24 #include <sys/wait.h>
25 #include <unistd.h>
26 #include <memory>
27
28 #include "base/stl_util.h"
29 #include "base/unix_file/fd_file.h"
30 #include "dex_file-inl.h"
31 #include "field_helper.h"
32 #include "mirror/art_field-inl.h"
33 #include "mirror/art_method-inl.h"
34 #include "mirror/class-inl.h"
35 #include "mirror/class_loader.h"
36 #include "mirror/object-inl.h"
37 #include "mirror/object_array-inl.h"
38 #include "mirror/string.h"
39 #include "os.h"
40 #include "scoped_thread_state_change.h"
41 #include "utf-inl.h"
42
43 #if !defined(HAVE_POSIX_CLOCKS)
44 #include <sys/time.h>
45 #endif
46
47 #if defined(HAVE_PRCTL)
48 #include <sys/prctl.h>
49 #endif
50
51 #if defined(__APPLE__)
52 #include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
53 #include <sys/syscall.h>
54 #endif
55
56 #include <backtrace/Backtrace.h> // For DumpNativeStack.
57
58 #if defined(__linux__)
59 #include <linux/unistd.h>
60 #endif
61
62 namespace art {
63
GetTid()64 pid_t GetTid() {
65 #if defined(__APPLE__)
66 uint64_t owner;
67 CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__); // Requires Mac OS 10.6
68 return owner;
69 #else
70 // Neither bionic nor glibc exposes gettid(2).
71 return syscall(__NR_gettid);
72 #endif
73 }
74
GetThreadName(pid_t tid)75 std::string GetThreadName(pid_t tid) {
76 std::string result;
77 if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
78 result.resize(result.size() - 1); // Lose the trailing '\n'.
79 } else {
80 result = "<unknown>";
81 }
82 return result;
83 }
84
GetThreadStack(pthread_t thread,void ** stack_base,size_t * stack_size,size_t * guard_size)85 void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size) {
86 #if defined(__APPLE__)
87 *stack_size = pthread_get_stacksize_np(thread);
88 void* stack_addr = pthread_get_stackaddr_np(thread);
89
90 // Check whether stack_addr is the base or end of the stack.
91 // (On Mac OS 10.7, it's the end.)
92 int stack_variable;
93 if (stack_addr > &stack_variable) {
94 *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
95 } else {
96 *stack_base = stack_addr;
97 }
98
99 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
100 pthread_attr_t attributes;
101 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
102 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
103 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
104 #else
105 pthread_attr_t attributes;
106 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
107 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
108 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
109 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
110 #endif
111 }
112
ReadFileToString(const std::string & file_name,std::string * result)113 bool ReadFileToString(const std::string& file_name, std::string* result) {
114 std::unique_ptr<File> file(new File);
115 if (!file->Open(file_name, O_RDONLY)) {
116 return false;
117 }
118
119 std::vector<char> buf(8 * KB);
120 while (true) {
121 int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
122 if (n == -1) {
123 return false;
124 }
125 if (n == 0) {
126 return true;
127 }
128 result->append(&buf[0], n);
129 }
130 }
131
GetIsoDate()132 std::string GetIsoDate() {
133 time_t now = time(NULL);
134 tm tmbuf;
135 tm* ptm = localtime_r(&now, &tmbuf);
136 return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
137 ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
138 ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
139 }
140
MilliTime()141 uint64_t MilliTime() {
142 #if defined(HAVE_POSIX_CLOCKS)
143 timespec now;
144 clock_gettime(CLOCK_MONOTONIC, &now);
145 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_nsec / UINT64_C(1000000);
146 #else
147 timeval now;
148 gettimeofday(&now, NULL);
149 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000) + now.tv_usec / UINT64_C(1000);
150 #endif
151 }
152
MicroTime()153 uint64_t MicroTime() {
154 #if defined(HAVE_POSIX_CLOCKS)
155 timespec now;
156 clock_gettime(CLOCK_MONOTONIC, &now);
157 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
158 #else
159 timeval now;
160 gettimeofday(&now, NULL);
161 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_usec;
162 #endif
163 }
164
NanoTime()165 uint64_t NanoTime() {
166 #if defined(HAVE_POSIX_CLOCKS)
167 timespec now;
168 clock_gettime(CLOCK_MONOTONIC, &now);
169 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
170 #else
171 timeval now;
172 gettimeofday(&now, NULL);
173 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_usec * UINT64_C(1000);
174 #endif
175 }
176
ThreadCpuNanoTime()177 uint64_t ThreadCpuNanoTime() {
178 #if defined(HAVE_POSIX_CLOCKS)
179 timespec now;
180 clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
181 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
182 #else
183 UNIMPLEMENTED(WARNING);
184 return -1;
185 #endif
186 }
187
NanoSleep(uint64_t ns)188 void NanoSleep(uint64_t ns) {
189 timespec tm;
190 tm.tv_sec = 0;
191 tm.tv_nsec = ns;
192 nanosleep(&tm, NULL);
193 }
194
InitTimeSpec(bool absolute,int clock,int64_t ms,int32_t ns,timespec * ts)195 void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
196 int64_t endSec;
197
198 if (absolute) {
199 #if !defined(__APPLE__)
200 clock_gettime(clock, ts);
201 #else
202 UNUSED(clock);
203 timeval tv;
204 gettimeofday(&tv, NULL);
205 ts->tv_sec = tv.tv_sec;
206 ts->tv_nsec = tv.tv_usec * 1000;
207 #endif
208 } else {
209 ts->tv_sec = 0;
210 ts->tv_nsec = 0;
211 }
212 endSec = ts->tv_sec + ms / 1000;
213 if (UNLIKELY(endSec >= 0x7fffffff)) {
214 std::ostringstream ss;
215 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
216 endSec = 0x7ffffffe;
217 }
218 ts->tv_sec = endSec;
219 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
220
221 // Catch rollover.
222 if (ts->tv_nsec >= 1000000000L) {
223 ts->tv_sec++;
224 ts->tv_nsec -= 1000000000L;
225 }
226 }
227
PrettyDescriptor(mirror::String * java_descriptor)228 std::string PrettyDescriptor(mirror::String* java_descriptor) {
229 if (java_descriptor == NULL) {
230 return "null";
231 }
232 return PrettyDescriptor(java_descriptor->ToModifiedUtf8().c_str());
233 }
234
PrettyDescriptor(mirror::Class * klass)235 std::string PrettyDescriptor(mirror::Class* klass) {
236 if (klass == NULL) {
237 return "null";
238 }
239 std::string temp;
240 return PrettyDescriptor(klass->GetDescriptor(&temp));
241 }
242
PrettyDescriptor(const char * descriptor)243 std::string PrettyDescriptor(const char* descriptor) {
244 // Count the number of '['s to get the dimensionality.
245 const char* c = descriptor;
246 size_t dim = 0;
247 while (*c == '[') {
248 dim++;
249 c++;
250 }
251
252 // Reference or primitive?
253 if (*c == 'L') {
254 // "[[La/b/C;" -> "a.b.C[][]".
255 c++; // Skip the 'L'.
256 } else {
257 // "[[B" -> "byte[][]".
258 // To make life easier, we make primitives look like unqualified
259 // reference types.
260 switch (*c) {
261 case 'B': c = "byte;"; break;
262 case 'C': c = "char;"; break;
263 case 'D': c = "double;"; break;
264 case 'F': c = "float;"; break;
265 case 'I': c = "int;"; break;
266 case 'J': c = "long;"; break;
267 case 'S': c = "short;"; break;
268 case 'Z': c = "boolean;"; break;
269 case 'V': c = "void;"; break; // Used when decoding return types.
270 default: return descriptor;
271 }
272 }
273
274 // At this point, 'c' is a string of the form "fully/qualified/Type;"
275 // or "primitive;". Rewrite the type with '.' instead of '/':
276 std::string result;
277 const char* p = c;
278 while (*p != ';') {
279 char ch = *p++;
280 if (ch == '/') {
281 ch = '.';
282 }
283 result.push_back(ch);
284 }
285 // ...and replace the semicolon with 'dim' "[]" pairs:
286 for (size_t i = 0; i < dim; ++i) {
287 result += "[]";
288 }
289 return result;
290 }
291
PrettyField(mirror::ArtField * f,bool with_type)292 std::string PrettyField(mirror::ArtField* f, bool with_type) {
293 if (f == NULL) {
294 return "null";
295 }
296 std::string result;
297 if (with_type) {
298 result += PrettyDescriptor(f->GetTypeDescriptor());
299 result += ' ';
300 }
301 StackHandleScope<1> hs(Thread::Current());
302 result += PrettyDescriptor(FieldHelper(hs.NewHandle(f)).GetDeclaringClassDescriptor());
303 result += '.';
304 result += f->GetName();
305 return result;
306 }
307
PrettyField(uint32_t field_idx,const DexFile & dex_file,bool with_type)308 std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
309 if (field_idx >= dex_file.NumFieldIds()) {
310 return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
311 }
312 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
313 std::string result;
314 if (with_type) {
315 result += dex_file.GetFieldTypeDescriptor(field_id);
316 result += ' ';
317 }
318 result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
319 result += '.';
320 result += dex_file.GetFieldName(field_id);
321 return result;
322 }
323
PrettyType(uint32_t type_idx,const DexFile & dex_file)324 std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
325 if (type_idx >= dex_file.NumTypeIds()) {
326 return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
327 }
328 const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
329 return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
330 }
331
PrettyArguments(const char * signature)332 std::string PrettyArguments(const char* signature) {
333 std::string result;
334 result += '(';
335 CHECK_EQ(*signature, '(');
336 ++signature; // Skip the '('.
337 while (*signature != ')') {
338 size_t argument_length = 0;
339 while (signature[argument_length] == '[') {
340 ++argument_length;
341 }
342 if (signature[argument_length] == 'L') {
343 argument_length = (strchr(signature, ';') - signature + 1);
344 } else {
345 ++argument_length;
346 }
347 {
348 std::string argument_descriptor(signature, argument_length);
349 result += PrettyDescriptor(argument_descriptor.c_str());
350 }
351 if (signature[argument_length] != ')') {
352 result += ", ";
353 }
354 signature += argument_length;
355 }
356 CHECK_EQ(*signature, ')');
357 ++signature; // Skip the ')'.
358 result += ')';
359 return result;
360 }
361
PrettyReturnType(const char * signature)362 std::string PrettyReturnType(const char* signature) {
363 const char* return_type = strchr(signature, ')');
364 CHECK(return_type != NULL);
365 ++return_type; // Skip ')'.
366 return PrettyDescriptor(return_type);
367 }
368
PrettyMethod(mirror::ArtMethod * m,bool with_signature)369 std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
370 if (m == nullptr) {
371 return "null";
372 }
373 std::string result(PrettyDescriptor(m->GetDeclaringClassDescriptor()));
374 result += '.';
375 result += m->GetName();
376 if (UNLIKELY(m->IsFastNative())) {
377 result += "!";
378 }
379 if (with_signature) {
380 const Signature signature = m->GetSignature();
381 std::string sig_as_string(signature.ToString());
382 if (signature == Signature::NoSignature()) {
383 return result + sig_as_string;
384 }
385 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
386 PrettyArguments(sig_as_string.c_str());
387 }
388 return result;
389 }
390
PrettyMethod(uint32_t method_idx,const DexFile & dex_file,bool with_signature)391 std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
392 if (method_idx >= dex_file.NumMethodIds()) {
393 return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
394 }
395 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
396 std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
397 result += '.';
398 result += dex_file.GetMethodName(method_id);
399 if (with_signature) {
400 const Signature signature = dex_file.GetMethodSignature(method_id);
401 std::string sig_as_string(signature.ToString());
402 if (signature == Signature::NoSignature()) {
403 return result + sig_as_string;
404 }
405 result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
406 PrettyArguments(sig_as_string.c_str());
407 }
408 return result;
409 }
410
PrettyTypeOf(mirror::Object * obj)411 std::string PrettyTypeOf(mirror::Object* obj) {
412 if (obj == NULL) {
413 return "null";
414 }
415 if (obj->GetClass() == NULL) {
416 return "(raw)";
417 }
418 std::string temp;
419 std::string result(PrettyDescriptor(obj->GetClass()->GetDescriptor(&temp)));
420 if (obj->IsClass()) {
421 result += "<" + PrettyDescriptor(obj->AsClass()->GetDescriptor(&temp)) + ">";
422 }
423 return result;
424 }
425
PrettyClass(mirror::Class * c)426 std::string PrettyClass(mirror::Class* c) {
427 if (c == NULL) {
428 return "null";
429 }
430 std::string result;
431 result += "java.lang.Class<";
432 result += PrettyDescriptor(c);
433 result += ">";
434 return result;
435 }
436
PrettyClassAndClassLoader(mirror::Class * c)437 std::string PrettyClassAndClassLoader(mirror::Class* c) {
438 if (c == NULL) {
439 return "null";
440 }
441 std::string result;
442 result += "java.lang.Class<";
443 result += PrettyDescriptor(c);
444 result += ",";
445 result += PrettyTypeOf(c->GetClassLoader());
446 // TODO: add an identifying hash value for the loader
447 result += ">";
448 return result;
449 }
450
PrettySize(int64_t byte_count)451 std::string PrettySize(int64_t byte_count) {
452 // The byte thresholds at which we display amounts. A byte count is displayed
453 // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
454 static const int64_t kUnitThresholds[] = {
455 0, // B up to...
456 3*1024, // KB up to...
457 2*1024*1024, // MB up to...
458 1024*1024*1024 // GB from here.
459 };
460 static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
461 static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
462 const char* negative_str = "";
463 if (byte_count < 0) {
464 negative_str = "-";
465 byte_count = -byte_count;
466 }
467 int i = arraysize(kUnitThresholds);
468 while (--i > 0) {
469 if (byte_count >= kUnitThresholds[i]) {
470 break;
471 }
472 }
473 return StringPrintf("%s%" PRId64 "%s",
474 negative_str, byte_count / kBytesPerUnit[i], kUnitStrings[i]);
475 }
476
PrettyDuration(uint64_t nano_duration,size_t max_fraction_digits)477 std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits) {
478 if (nano_duration == 0) {
479 return "0";
480 } else {
481 return FormatDuration(nano_duration, GetAppropriateTimeUnit(nano_duration),
482 max_fraction_digits);
483 }
484 }
485
GetAppropriateTimeUnit(uint64_t nano_duration)486 TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration) {
487 const uint64_t one_sec = 1000 * 1000 * 1000;
488 const uint64_t one_ms = 1000 * 1000;
489 const uint64_t one_us = 1000;
490 if (nano_duration >= one_sec) {
491 return kTimeUnitSecond;
492 } else if (nano_duration >= one_ms) {
493 return kTimeUnitMillisecond;
494 } else if (nano_duration >= one_us) {
495 return kTimeUnitMicrosecond;
496 } else {
497 return kTimeUnitNanosecond;
498 }
499 }
500
GetNsToTimeUnitDivisor(TimeUnit time_unit)501 uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit) {
502 const uint64_t one_sec = 1000 * 1000 * 1000;
503 const uint64_t one_ms = 1000 * 1000;
504 const uint64_t one_us = 1000;
505
506 switch (time_unit) {
507 case kTimeUnitSecond:
508 return one_sec;
509 case kTimeUnitMillisecond:
510 return one_ms;
511 case kTimeUnitMicrosecond:
512 return one_us;
513 case kTimeUnitNanosecond:
514 return 1;
515 }
516 return 0;
517 }
518
FormatDuration(uint64_t nano_duration,TimeUnit time_unit,size_t max_fraction_digits)519 std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
520 size_t max_fraction_digits) {
521 const char* unit = nullptr;
522 uint64_t divisor = GetNsToTimeUnitDivisor(time_unit);
523 switch (time_unit) {
524 case kTimeUnitSecond:
525 unit = "s";
526 break;
527 case kTimeUnitMillisecond:
528 unit = "ms";
529 break;
530 case kTimeUnitMicrosecond:
531 unit = "us";
532 break;
533 case kTimeUnitNanosecond:
534 unit = "ns";
535 break;
536 }
537 const uint64_t whole_part = nano_duration / divisor;
538 uint64_t fractional_part = nano_duration % divisor;
539 if (fractional_part == 0) {
540 return StringPrintf("%" PRIu64 "%s", whole_part, unit);
541 } else {
542 static constexpr size_t kMaxDigits = 30;
543 size_t avail_digits = kMaxDigits;
544 char fraction_buffer[kMaxDigits];
545 char* ptr = fraction_buffer;
546 uint64_t multiplier = 10;
547 // This infinite loops if fractional part is 0.
548 while (avail_digits > 1 && fractional_part * multiplier < divisor) {
549 multiplier *= 10;
550 *ptr++ = '0';
551 avail_digits--;
552 }
553 snprintf(ptr, avail_digits, "%" PRIu64, fractional_part);
554 fraction_buffer[std::min(kMaxDigits - 1, max_fraction_digits)] = '\0';
555 return StringPrintf("%" PRIu64 ".%s%s", whole_part, fraction_buffer, unit);
556 }
557 }
558
PrintableChar(uint16_t ch)559 std::string PrintableChar(uint16_t ch) {
560 std::string result;
561 result += '\'';
562 if (NeedsEscaping(ch)) {
563 StringAppendF(&result, "\\u%04x", ch);
564 } else {
565 result += ch;
566 }
567 result += '\'';
568 return result;
569 }
570
PrintableString(const char * utf)571 std::string PrintableString(const char* utf) {
572 std::string result;
573 result += '"';
574 const char* p = utf;
575 size_t char_count = CountModifiedUtf8Chars(p);
576 for (size_t i = 0; i < char_count; ++i) {
577 uint16_t ch = GetUtf16FromUtf8(&p);
578 if (ch == '\\') {
579 result += "\\\\";
580 } else if (ch == '\n') {
581 result += "\\n";
582 } else if (ch == '\r') {
583 result += "\\r";
584 } else if (ch == '\t') {
585 result += "\\t";
586 } else if (NeedsEscaping(ch)) {
587 StringAppendF(&result, "\\u%04x", ch);
588 } else {
589 result += ch;
590 }
591 }
592 result += '"';
593 return result;
594 }
595
596 // See http://java.sun.com/j2se/1.5.0/docs/guide/jni/spec/design.html#wp615 for the full rules.
MangleForJni(const std::string & s)597 std::string MangleForJni(const std::string& s) {
598 std::string result;
599 size_t char_count = CountModifiedUtf8Chars(s.c_str());
600 const char* cp = &s[0];
601 for (size_t i = 0; i < char_count; ++i) {
602 uint16_t ch = GetUtf16FromUtf8(&cp);
603 if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
604 result.push_back(ch);
605 } else if (ch == '.' || ch == '/') {
606 result += "_";
607 } else if (ch == '_') {
608 result += "_1";
609 } else if (ch == ';') {
610 result += "_2";
611 } else if (ch == '[') {
612 result += "_3";
613 } else {
614 StringAppendF(&result, "_0%04x", ch);
615 }
616 }
617 return result;
618 }
619
DotToDescriptor(const char * class_name)620 std::string DotToDescriptor(const char* class_name) {
621 std::string descriptor(class_name);
622 std::replace(descriptor.begin(), descriptor.end(), '.', '/');
623 if (descriptor.length() > 0 && descriptor[0] != '[') {
624 descriptor = "L" + descriptor + ";";
625 }
626 return descriptor;
627 }
628
DescriptorToDot(const char * descriptor)629 std::string DescriptorToDot(const char* descriptor) {
630 size_t length = strlen(descriptor);
631 if (length > 1) {
632 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
633 // Descriptors have the leading 'L' and trailing ';' stripped.
634 std::string result(descriptor + 1, length - 2);
635 std::replace(result.begin(), result.end(), '/', '.');
636 return result;
637 } else {
638 // For arrays the 'L' and ';' remain intact.
639 std::string result(descriptor);
640 std::replace(result.begin(), result.end(), '/', '.');
641 return result;
642 }
643 }
644 // Do nothing for non-class/array descriptors.
645 return descriptor;
646 }
647
DescriptorToName(const char * descriptor)648 std::string DescriptorToName(const char* descriptor) {
649 size_t length = strlen(descriptor);
650 if (descriptor[0] == 'L' && descriptor[length - 1] == ';') {
651 std::string result(descriptor + 1, length - 2);
652 return result;
653 }
654 return descriptor;
655 }
656
JniShortName(mirror::ArtMethod * m)657 std::string JniShortName(mirror::ArtMethod* m) {
658 std::string class_name(m->GetDeclaringClassDescriptor());
659 // Remove the leading 'L' and trailing ';'...
660 CHECK_EQ(class_name[0], 'L') << class_name;
661 CHECK_EQ(class_name[class_name.size() - 1], ';') << class_name;
662 class_name.erase(0, 1);
663 class_name.erase(class_name.size() - 1, 1);
664
665 std::string method_name(m->GetName());
666
667 std::string short_name;
668 short_name += "Java_";
669 short_name += MangleForJni(class_name);
670 short_name += "_";
671 short_name += MangleForJni(method_name);
672 return short_name;
673 }
674
JniLongName(mirror::ArtMethod * m)675 std::string JniLongName(mirror::ArtMethod* m) {
676 std::string long_name;
677 long_name += JniShortName(m);
678 long_name += "__";
679
680 std::string signature(m->GetSignature().ToString());
681 signature.erase(0, 1);
682 signature.erase(signature.begin() + signature.find(')'), signature.end());
683
684 long_name += MangleForJni(signature);
685
686 return long_name;
687 }
688
689 // Helper for IsValidPartOfMemberNameUtf8(), a bit vector indicating valid low ascii.
690 uint32_t DEX_MEMBER_VALID_LOW_ASCII[4] = {
691 0x00000000, // 00..1f low control characters; nothing valid
692 0x03ff2010, // 20..3f digits and symbols; valid: '0'..'9', '$', '-'
693 0x87fffffe, // 40..5f uppercase etc.; valid: 'A'..'Z', '_'
694 0x07fffffe // 60..7f lowercase etc.; valid: 'a'..'z'
695 };
696
697 // Helper for IsValidPartOfMemberNameUtf8(); do not call directly.
IsValidPartOfMemberNameUtf8Slow(const char ** pUtf8Ptr)698 bool IsValidPartOfMemberNameUtf8Slow(const char** pUtf8Ptr) {
699 /*
700 * It's a multibyte encoded character. Decode it and analyze. We
701 * accept anything that isn't (a) an improperly encoded low value,
702 * (b) an improper surrogate pair, (c) an encoded '\0', (d) a high
703 * control character, or (e) a high space, layout, or special
704 * character (U+00a0, U+2000..U+200f, U+2028..U+202f,
705 * U+fff0..U+ffff). This is all specified in the dex format
706 * document.
707 */
708
709 uint16_t utf16 = GetUtf16FromUtf8(pUtf8Ptr);
710
711 // Perform follow-up tests based on the high 8 bits.
712 switch (utf16 >> 8) {
713 case 0x00:
714 // It's only valid if it's above the ISO-8859-1 high space (0xa0).
715 return (utf16 > 0x00a0);
716 case 0xd8:
717 case 0xd9:
718 case 0xda:
719 case 0xdb:
720 // It's a leading surrogate. Check to see that a trailing
721 // surrogate follows.
722 utf16 = GetUtf16FromUtf8(pUtf8Ptr);
723 return (utf16 >= 0xdc00) && (utf16 <= 0xdfff);
724 case 0xdc:
725 case 0xdd:
726 case 0xde:
727 case 0xdf:
728 // It's a trailing surrogate, which is not valid at this point.
729 return false;
730 case 0x20:
731 case 0xff:
732 // It's in the range that has spaces, controls, and specials.
733 switch (utf16 & 0xfff8) {
734 case 0x2000:
735 case 0x2008:
736 case 0x2028:
737 case 0xfff0:
738 case 0xfff8:
739 return false;
740 }
741 break;
742 }
743 return true;
744 }
745
746 /* Return whether the pointed-at modified-UTF-8 encoded character is
747 * valid as part of a member name, updating the pointer to point past
748 * the consumed character. This will consume two encoded UTF-16 code
749 * points if the character is encoded as a surrogate pair. Also, if
750 * this function returns false, then the given pointer may only have
751 * been partially advanced.
752 */
IsValidPartOfMemberNameUtf8(const char ** pUtf8Ptr)753 static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
754 uint8_t c = (uint8_t) **pUtf8Ptr;
755 if (LIKELY(c <= 0x7f)) {
756 // It's low-ascii, so check the table.
757 uint32_t wordIdx = c >> 5;
758 uint32_t bitIdx = c & 0x1f;
759 (*pUtf8Ptr)++;
760 return (DEX_MEMBER_VALID_LOW_ASCII[wordIdx] & (1 << bitIdx)) != 0;
761 }
762
763 // It's a multibyte encoded character. Call a non-inline function
764 // for the heavy lifting.
765 return IsValidPartOfMemberNameUtf8Slow(pUtf8Ptr);
766 }
767
IsValidMemberName(const char * s)768 bool IsValidMemberName(const char* s) {
769 bool angle_name = false;
770
771 switch (*s) {
772 case '\0':
773 // The empty string is not a valid name.
774 return false;
775 case '<':
776 angle_name = true;
777 s++;
778 break;
779 }
780
781 while (true) {
782 switch (*s) {
783 case '\0':
784 return !angle_name;
785 case '>':
786 return angle_name && s[1] == '\0';
787 }
788
789 if (!IsValidPartOfMemberNameUtf8(&s)) {
790 return false;
791 }
792 }
793 }
794
795 enum ClassNameType { kName, kDescriptor };
IsValidClassName(const char * s,ClassNameType type,char separator)796 static bool IsValidClassName(const char* s, ClassNameType type, char separator) {
797 int arrayCount = 0;
798 while (*s == '[') {
799 arrayCount++;
800 s++;
801 }
802
803 if (arrayCount > 255) {
804 // Arrays may have no more than 255 dimensions.
805 return false;
806 }
807
808 if (arrayCount != 0) {
809 /*
810 * If we're looking at an array of some sort, then it doesn't
811 * matter if what is being asked for is a class name; the
812 * format looks the same as a type descriptor in that case, so
813 * treat it as such.
814 */
815 type = kDescriptor;
816 }
817
818 if (type == kDescriptor) {
819 /*
820 * We are looking for a descriptor. Either validate it as a
821 * single-character primitive type, or continue on to check the
822 * embedded class name (bracketed by "L" and ";").
823 */
824 switch (*(s++)) {
825 case 'B':
826 case 'C':
827 case 'D':
828 case 'F':
829 case 'I':
830 case 'J':
831 case 'S':
832 case 'Z':
833 // These are all single-character descriptors for primitive types.
834 return (*s == '\0');
835 case 'V':
836 // Non-array void is valid, but you can't have an array of void.
837 return (arrayCount == 0) && (*s == '\0');
838 case 'L':
839 // Class name: Break out and continue below.
840 break;
841 default:
842 // Oddball descriptor character.
843 return false;
844 }
845 }
846
847 /*
848 * We just consumed the 'L' that introduces a class name as part
849 * of a type descriptor, or we are looking for an unadorned class
850 * name.
851 */
852
853 bool sepOrFirst = true; // first character or just encountered a separator.
854 for (;;) {
855 uint8_t c = (uint8_t) *s;
856 switch (c) {
857 case '\0':
858 /*
859 * Premature end for a type descriptor, but valid for
860 * a class name as long as we haven't encountered an
861 * empty component (including the degenerate case of
862 * the empty string "").
863 */
864 return (type == kName) && !sepOrFirst;
865 case ';':
866 /*
867 * Invalid character for a class name, but the
868 * legitimate end of a type descriptor. In the latter
869 * case, make sure that this is the end of the string
870 * and that it doesn't end with an empty component
871 * (including the degenerate case of "L;").
872 */
873 return (type == kDescriptor) && !sepOrFirst && (s[1] == '\0');
874 case '/':
875 case '.':
876 if (c != separator) {
877 // The wrong separator character.
878 return false;
879 }
880 if (sepOrFirst) {
881 // Separator at start or two separators in a row.
882 return false;
883 }
884 sepOrFirst = true;
885 s++;
886 break;
887 default:
888 if (!IsValidPartOfMemberNameUtf8(&s)) {
889 return false;
890 }
891 sepOrFirst = false;
892 break;
893 }
894 }
895 }
896
IsValidBinaryClassName(const char * s)897 bool IsValidBinaryClassName(const char* s) {
898 return IsValidClassName(s, kName, '.');
899 }
900
IsValidJniClassName(const char * s)901 bool IsValidJniClassName(const char* s) {
902 return IsValidClassName(s, kName, '/');
903 }
904
IsValidDescriptor(const char * s)905 bool IsValidDescriptor(const char* s) {
906 return IsValidClassName(s, kDescriptor, '/');
907 }
908
Split(const std::string & s,char separator,std::vector<std::string> & result)909 void Split(const std::string& s, char separator, std::vector<std::string>& result) {
910 const char* p = s.data();
911 const char* end = p + s.size();
912 while (p != end) {
913 if (*p == separator) {
914 ++p;
915 } else {
916 const char* start = p;
917 while (++p != end && *p != separator) {
918 // Skip to the next occurrence of the separator.
919 }
920 result.push_back(std::string(start, p - start));
921 }
922 }
923 }
924
Trim(std::string s)925 std::string Trim(std::string s) {
926 std::string result;
927 unsigned int start_index = 0;
928 unsigned int end_index = s.size() - 1;
929
930 // Skip initial whitespace.
931 while (start_index < s.size()) {
932 if (!isspace(s[start_index])) {
933 break;
934 }
935 start_index++;
936 }
937
938 // Skip terminating whitespace.
939 while (end_index >= start_index) {
940 if (!isspace(s[end_index])) {
941 break;
942 }
943 end_index--;
944 }
945
946 // All spaces, no beef.
947 if (end_index < start_index) {
948 return "";
949 }
950 // Start_index is the first non-space, end_index is the last one.
951 return s.substr(start_index, end_index - start_index + 1);
952 }
953
954 template <typename StringT>
Join(std::vector<StringT> & strings,char separator)955 std::string Join(std::vector<StringT>& strings, char separator) {
956 if (strings.empty()) {
957 return "";
958 }
959
960 std::string result(strings[0]);
961 for (size_t i = 1; i < strings.size(); ++i) {
962 result += separator;
963 result += strings[i];
964 }
965 return result;
966 }
967
968 // Explicit instantiations.
969 template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
970 template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
971 template std::string Join<char*>(std::vector<char*>& strings, char separator);
972
StartsWith(const std::string & s,const char * prefix)973 bool StartsWith(const std::string& s, const char* prefix) {
974 return s.compare(0, strlen(prefix), prefix) == 0;
975 }
976
EndsWith(const std::string & s,const char * suffix)977 bool EndsWith(const std::string& s, const char* suffix) {
978 size_t suffix_length = strlen(suffix);
979 size_t string_length = s.size();
980 if (suffix_length > string_length) {
981 return false;
982 }
983 size_t offset = string_length - suffix_length;
984 return s.compare(offset, suffix_length, suffix) == 0;
985 }
986
SetThreadName(const char * thread_name)987 void SetThreadName(const char* thread_name) {
988 int hasAt = 0;
989 int hasDot = 0;
990 const char* s = thread_name;
991 while (*s) {
992 if (*s == '.') {
993 hasDot = 1;
994 } else if (*s == '@') {
995 hasAt = 1;
996 }
997 s++;
998 }
999 int len = s - thread_name;
1000 if (len < 15 || hasAt || !hasDot) {
1001 s = thread_name;
1002 } else {
1003 s = thread_name + len - 15;
1004 }
1005 #if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
1006 // pthread_setname_np fails rather than truncating long strings.
1007 char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
1008 strncpy(buf, s, sizeof(buf)-1);
1009 buf[sizeof(buf)-1] = '\0';
1010 errno = pthread_setname_np(pthread_self(), buf);
1011 if (errno != 0) {
1012 PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
1013 }
1014 #elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
1015 pthread_setname_np(thread_name);
1016 #elif defined(HAVE_PRCTL)
1017 prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0); // NOLINT (unsigned long)
1018 #else
1019 UNIMPLEMENTED(WARNING) << thread_name;
1020 #endif
1021 }
1022
GetTaskStats(pid_t tid,char * state,int * utime,int * stime,int * task_cpu)1023 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
1024 *utime = *stime = *task_cpu = 0;
1025 std::string stats;
1026 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
1027 return;
1028 }
1029 // Skip the command, which may contain spaces.
1030 stats = stats.substr(stats.find(')') + 2);
1031 // Extract the three fields we care about.
1032 std::vector<std::string> fields;
1033 Split(stats, ' ', fields);
1034 *state = fields[0][0];
1035 *utime = strtoull(fields[11].c_str(), NULL, 10);
1036 *stime = strtoull(fields[12].c_str(), NULL, 10);
1037 *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
1038 }
1039
GetSchedulerGroupName(pid_t tid)1040 std::string GetSchedulerGroupName(pid_t tid) {
1041 // /proc/<pid>/cgroup looks like this:
1042 // 2:devices:/
1043 // 1:cpuacct,cpu:/
1044 // We want the third field from the line whose second field contains the "cpu" token.
1045 std::string cgroup_file;
1046 if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1047 return "";
1048 }
1049 std::vector<std::string> cgroup_lines;
1050 Split(cgroup_file, '\n', cgroup_lines);
1051 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1052 std::vector<std::string> cgroup_fields;
1053 Split(cgroup_lines[i], ':', cgroup_fields);
1054 std::vector<std::string> cgroups;
1055 Split(cgroup_fields[1], ',', cgroups);
1056 for (size_t i = 0; i < cgroups.size(); ++i) {
1057 if (cgroups[i] == "cpu") {
1058 return cgroup_fields[2].substr(1); // Skip the leading slash.
1059 }
1060 }
1061 }
1062 return "";
1063 }
1064
DumpNativeStack(std::ostream & os,pid_t tid,const char * prefix,mirror::ArtMethod * current_method)1065 void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix,
1066 mirror::ArtMethod* current_method) {
1067 // We may be called from contexts where current_method is not null, so we must assert this.
1068 if (current_method != nullptr) {
1069 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1070 }
1071 #ifdef __linux__
1072 std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
1073 if (!backtrace->Unwind(0)) {
1074 os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
1075 return;
1076 } else if (backtrace->NumFrames() == 0) {
1077 os << prefix << "(no native stack frames for thread " << tid << ")\n";
1078 return;
1079 }
1080
1081 for (Backtrace::const_iterator it = backtrace->begin();
1082 it != backtrace->end(); ++it) {
1083 // We produce output like this:
1084 // ] #00 pc 000075bb8 /system/lib/libc.so (unwind_backtrace_thread+536)
1085 // In order for parsing tools to continue to function, the stack dump
1086 // format must at least adhere to this format:
1087 // #XX pc <RELATIVE_ADDR> <FULL_PATH_TO_SHARED_LIBRARY> ...
1088 // The parsers require a single space before and after pc, and two spaces
1089 // after the <RELATIVE_ADDR>. There can be any prefix data before the
1090 // #XX. <RELATIVE_ADDR> has to be a hex number but with no 0x prefix.
1091 os << prefix << StringPrintf("#%02zu pc ", it->num);
1092 if (!it->map) {
1093 os << StringPrintf("%08" PRIxPTR " ???", it->pc);
1094 } else {
1095 os << StringPrintf("%08" PRIxPTR " ", it->pc - it->map->start)
1096 << it->map->name << " (";
1097 if (!it->func_name.empty()) {
1098 os << it->func_name;
1099 if (it->func_offset != 0) {
1100 os << "+" << it->func_offset;
1101 }
1102 } else if (current_method != nullptr && current_method->IsWithinQuickCode(it->pc)) {
1103 const void* start_of_code = current_method->GetEntryPointFromQuickCompiledCode();
1104 os << JniLongName(current_method) << "+"
1105 << (it->pc - reinterpret_cast<uintptr_t>(start_of_code));
1106 } else {
1107 os << "???";
1108 }
1109 os << ")";
1110 }
1111 os << "\n";
1112 }
1113 #endif
1114 }
1115
1116 #if defined(__APPLE__)
1117
1118 // TODO: is there any way to get the kernel stack on Mac OS?
DumpKernelStack(std::ostream &,pid_t,const char *,bool)1119 void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1120
1121 #else
1122
DumpKernelStack(std::ostream & os,pid_t tid,const char * prefix,bool include_count)1123 void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
1124 if (tid == GetTid()) {
1125 // There's no point showing that we're reading our stack out of /proc!
1126 return;
1127 }
1128
1129 std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1130 std::string kernel_stack;
1131 if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
1132 os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
1133 return;
1134 }
1135
1136 std::vector<std::string> kernel_stack_frames;
1137 Split(kernel_stack, '\n', kernel_stack_frames);
1138 // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1139 // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1140 kernel_stack_frames.pop_back();
1141 for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1142 // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110"
1143 // into "futex_wait_queue_me+0xcd/0x110".
1144 const char* text = kernel_stack_frames[i].c_str();
1145 const char* close_bracket = strchr(text, ']');
1146 if (close_bracket != NULL) {
1147 text = close_bracket + 2;
1148 }
1149 os << prefix;
1150 if (include_count) {
1151 os << StringPrintf("#%02zd ", i);
1152 }
1153 os << text << "\n";
1154 }
1155 }
1156
1157 #endif
1158
GetAndroidRoot()1159 const char* GetAndroidRoot() {
1160 const char* android_root = getenv("ANDROID_ROOT");
1161 if (android_root == NULL) {
1162 if (OS::DirectoryExists("/system")) {
1163 android_root = "/system";
1164 } else {
1165 LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1166 return "";
1167 }
1168 }
1169 if (!OS::DirectoryExists(android_root)) {
1170 LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
1171 return "";
1172 }
1173 return android_root;
1174 }
1175
GetAndroidData()1176 const char* GetAndroidData() {
1177 std::string error_msg;
1178 const char* dir = GetAndroidDataSafe(&error_msg);
1179 if (dir != nullptr) {
1180 return dir;
1181 } else {
1182 LOG(FATAL) << error_msg;
1183 return "";
1184 }
1185 }
1186
GetAndroidDataSafe(std::string * error_msg)1187 const char* GetAndroidDataSafe(std::string* error_msg) {
1188 const char* android_data = getenv("ANDROID_DATA");
1189 if (android_data == NULL) {
1190 if (OS::DirectoryExists("/data")) {
1191 android_data = "/data";
1192 } else {
1193 *error_msg = "ANDROID_DATA not set and /data does not exist";
1194 return nullptr;
1195 }
1196 }
1197 if (!OS::DirectoryExists(android_data)) {
1198 *error_msg = StringPrintf("Failed to find ANDROID_DATA directory %s", android_data);
1199 return nullptr;
1200 }
1201 return android_data;
1202 }
1203
GetDalvikCache(const char * subdir,const bool create_if_absent,std::string * dalvik_cache,bool * have_android_data,bool * dalvik_cache_exists,bool * is_global_cache)1204 void GetDalvikCache(const char* subdir, const bool create_if_absent, std::string* dalvik_cache,
1205 bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache) {
1206 CHECK(subdir != nullptr);
1207 std::string error_msg;
1208 const char* android_data = GetAndroidDataSafe(&error_msg);
1209 if (android_data == nullptr) {
1210 *have_android_data = false;
1211 *dalvik_cache_exists = false;
1212 *is_global_cache = false;
1213 return;
1214 } else {
1215 *have_android_data = true;
1216 }
1217 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1218 *dalvik_cache = dalvik_cache_root + subdir;
1219 *dalvik_cache_exists = OS::DirectoryExists(dalvik_cache->c_str());
1220 *is_global_cache = strcmp(android_data, "/data") == 0;
1221 if (create_if_absent && !*dalvik_cache_exists && !*is_global_cache) {
1222 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1223 *dalvik_cache_exists = ((mkdir(dalvik_cache_root.c_str(), 0700) == 0 || errno == EEXIST) &&
1224 (mkdir(dalvik_cache->c_str(), 0700) == 0 || errno == EEXIST));
1225 }
1226 }
1227
GetDalvikCacheOrDie(const char * subdir,const bool create_if_absent)1228 std::string GetDalvikCacheOrDie(const char* subdir, const bool create_if_absent) {
1229 CHECK(subdir != nullptr);
1230 const char* android_data = GetAndroidData();
1231 const std::string dalvik_cache_root(StringPrintf("%s/dalvik-cache/", android_data));
1232 const std::string dalvik_cache = dalvik_cache_root + subdir;
1233 if (create_if_absent && !OS::DirectoryExists(dalvik_cache.c_str())) {
1234 // Don't create the system's /data/dalvik-cache/... because it needs special permissions.
1235 if (strcmp(android_data, "/data") != 0) {
1236 int result = mkdir(dalvik_cache_root.c_str(), 0700);
1237 if (result != 0 && errno != EEXIST) {
1238 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache_root;
1239 return "";
1240 }
1241 result = mkdir(dalvik_cache.c_str(), 0700);
1242 if (result != 0) {
1243 PLOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
1244 return "";
1245 }
1246 } else {
1247 LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
1248 return "";
1249 }
1250 }
1251 return dalvik_cache;
1252 }
1253
GetDalvikCacheFilename(const char * location,const char * cache_location,std::string * filename,std::string * error_msg)1254 bool GetDalvikCacheFilename(const char* location, const char* cache_location,
1255 std::string* filename, std::string* error_msg) {
1256 if (location[0] != '/') {
1257 *error_msg = StringPrintf("Expected path in location to be absolute: %s", location);
1258 return false;
1259 }
1260 std::string cache_file(&location[1]); // skip leading slash
1261 if (!EndsWith(location, ".dex") && !EndsWith(location, ".art") && !EndsWith(location, ".oat")) {
1262 cache_file += "/";
1263 cache_file += DexFile::kClassesDex;
1264 }
1265 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1266 *filename = StringPrintf("%s/%s", cache_location, cache_file.c_str());
1267 return true;
1268 }
1269
GetDalvikCacheFilenameOrDie(const char * location,const char * cache_location)1270 std::string GetDalvikCacheFilenameOrDie(const char* location, const char* cache_location) {
1271 std::string ret;
1272 std::string error_msg;
1273 if (!GetDalvikCacheFilename(location, cache_location, &ret, &error_msg)) {
1274 LOG(FATAL) << error_msg;
1275 }
1276 return ret;
1277 }
1278
InsertIsaDirectory(const InstructionSet isa,std::string * filename)1279 static void InsertIsaDirectory(const InstructionSet isa, std::string* filename) {
1280 // in = /foo/bar/baz
1281 // out = /foo/bar/<isa>/baz
1282 size_t pos = filename->rfind('/');
1283 CHECK_NE(pos, std::string::npos) << *filename << " " << isa;
1284 filename->insert(pos, "/", 1);
1285 filename->insert(pos + 1, GetInstructionSetString(isa));
1286 }
1287
GetSystemImageFilename(const char * location,const InstructionSet isa)1288 std::string GetSystemImageFilename(const char* location, const InstructionSet isa) {
1289 // location = /system/framework/boot.art
1290 // filename = /system/framework/<isa>/boot.art
1291 std::string filename(location);
1292 InsertIsaDirectory(isa, &filename);
1293 return filename;
1294 }
1295
DexFilenameToOdexFilename(const std::string & location,const InstructionSet isa)1296 std::string DexFilenameToOdexFilename(const std::string& location, const InstructionSet isa) {
1297 // location = /foo/bar/baz.jar
1298 // odex_location = /foo/bar/<isa>/baz.odex
1299
1300 CHECK_GE(location.size(), 4U) << location; // must be at least .123
1301 std::string odex_location(location);
1302 InsertIsaDirectory(isa, &odex_location);
1303 size_t dot_index = odex_location.size() - 3 - 1; // 3=dex or zip or apk
1304 CHECK_EQ('.', odex_location[dot_index]) << location;
1305 odex_location.resize(dot_index + 1);
1306 CHECK_EQ('.', odex_location[odex_location.size()-1]) << location << " " << odex_location;
1307 odex_location += "odex";
1308 return odex_location;
1309 }
1310
IsZipMagic(uint32_t magic)1311 bool IsZipMagic(uint32_t magic) {
1312 return (('P' == ((magic >> 0) & 0xff)) &&
1313 ('K' == ((magic >> 8) & 0xff)));
1314 }
1315
IsDexMagic(uint32_t magic)1316 bool IsDexMagic(uint32_t magic) {
1317 return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
1318 }
1319
IsOatMagic(uint32_t magic)1320 bool IsOatMagic(uint32_t magic) {
1321 return (memcmp(reinterpret_cast<const byte*>(magic),
1322 OatHeader::kOatMagic,
1323 sizeof(OatHeader::kOatMagic)) == 0);
1324 }
1325
Exec(std::vector<std::string> & arg_vector,std::string * error_msg)1326 bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1327 const std::string command_line(Join(arg_vector, ' '));
1328
1329 CHECK_GE(arg_vector.size(), 1U) << command_line;
1330
1331 // Convert the args to char pointers.
1332 const char* program = arg_vector[0].c_str();
1333 std::vector<char*> args;
1334 for (size_t i = 0; i < arg_vector.size(); ++i) {
1335 const std::string& arg = arg_vector[i];
1336 char* arg_str = const_cast<char*>(arg.c_str());
1337 CHECK(arg_str != nullptr) << i;
1338 args.push_back(arg_str);
1339 }
1340 args.push_back(NULL);
1341
1342 // fork and exec
1343 pid_t pid = fork();
1344 if (pid == 0) {
1345 // no allocation allowed between fork and exec
1346
1347 // change process groups, so we don't get reaped by ProcessManager
1348 setpgid(0, 0);
1349
1350 execv(program, &args[0]);
1351
1352 PLOG(ERROR) << "Failed to execv(" << command_line << ")";
1353 exit(1);
1354 } else {
1355 if (pid == -1) {
1356 *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1357 command_line.c_str(), strerror(errno));
1358 return false;
1359 }
1360
1361 // wait for subprocess to finish
1362 int status;
1363 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1364 if (got_pid != pid) {
1365 *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1366 "wanted %d, got %d: %s",
1367 command_line.c_str(), pid, got_pid, strerror(errno));
1368 return false;
1369 }
1370 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1371 *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1372 command_line.c_str());
1373 return false;
1374 }
1375 }
1376 return true;
1377 }
1378
PrettyDescriptor(Primitive::Type type)1379 std::string PrettyDescriptor(Primitive::Type type) {
1380 return PrettyDescriptor(Primitive::Descriptor(type));
1381 }
1382
1383 } // namespace art
1384