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