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